es6.js 4.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461
  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. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. var finalVertexCode;
  216. this._loadVertexShaderAsync(vertexSource)
  217. .then(function (vertexCode) {
  218. return _this._processIncludesAsync(vertexCode);
  219. })
  220. .then(function (vertexCodeWithIncludes) {
  221. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  222. return _this._loadFragmentShaderAsync(fragmentSource);
  223. })
  224. .then(function (fragmentCode) {
  225. return _this._processIncludesAsync(fragmentCode);
  226. })
  227. .then(function (fragmentCodeWithIncludes) {
  228. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  229. if (baseName) {
  230. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  231. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  232. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  233. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  234. }
  235. else {
  236. _this._vertexSourceCode = finalVertexCode;
  237. _this._fragmentSourceCode = migratedFragmentCode;
  238. }
  239. _this._prepareEffect();
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @ignore */
  348. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. return Promise.resolve(vertexCode);
  354. }
  355. }
  356. // Base64 encoded ?
  357. if (vertex.substr(0, 7) === "base64:") {
  358. var vertexBinary = window.atob(vertex.substr(7));
  359. return Promise.resolve(vertexBinary);
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  374. };
  375. /** @ignore */
  376. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. return Promise.resolve(fragmentCode);
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (fragment.substr(0, 7) === "base64:") {
  386. var fragmentBinary = window.atob(fragment.substr(7));
  387. return Promise.resolve(fragmentBinary);
  388. }
  389. // Is in local store ?
  390. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  391. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  392. }
  393. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  394. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  395. }
  396. var fragmentShaderUrl;
  397. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  398. fragmentShaderUrl = fragment;
  399. }
  400. else {
  401. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  402. }
  403. // Fragment shader
  404. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  405. };
  406. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  407. // Rebuild shaders source code
  408. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  409. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  410. vertexCode = prefix + vertexCode;
  411. fragmentCode = prefix + fragmentCode;
  412. // Number lines of shaders source code
  413. var i = 2;
  414. var regex = /\n/gm;
  415. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  416. i = 2;
  417. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  418. // Dump shaders name and formatted source code
  419. if (this.name.vertexElement) {
  420. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  421. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  422. }
  423. else if (this.name.vertex) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  426. }
  427. else {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  430. }
  431. };
  432. ;
  433. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  434. var preparedSourceCode = this._processPrecision(sourceCode);
  435. if (this._engine.webGLVersion == 1) {
  436. return preparedSourceCode;
  437. }
  438. // Already converted
  439. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  440. return preparedSourceCode.replace("#version 300 es", "");
  441. }
  442. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  443. // Remove extensions
  444. // #extension GL_OES_standard_derivatives : enable
  445. // #extension GL_EXT_shader_texture_lod : enable
  446. // #extension GL_EXT_frag_depth : enable
  447. // #extension GL_EXT_draw_buffers : require
  448. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  449. var result = preparedSourceCode.replace(regex, "");
  450. // Migrate to GLSL v300
  451. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  452. result = result.replace(/attribute[ \t]/g, "in ");
  453. result = result.replace(/[ \t]attribute/g, " in");
  454. if (isFragment) {
  455. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  456. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  457. result = result.replace(/texture2D\s*\(/g, "texture(");
  458. result = result.replace(/textureCube\s*\(/g, "texture(");
  459. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  460. result = result.replace(/gl_FragColor/g, "glFragColor");
  461. result = result.replace(/gl_FragData/g, "glFragData");
  462. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  463. }
  464. return result;
  465. };
  466. Effect.prototype._processIncludesAsync = function (sourceCode) {
  467. var _this = this;
  468. return new Promise(function (resolve, reject) {
  469. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  470. var match = regex.exec(sourceCode);
  471. var returnValue = sourceCode;
  472. while (match != null) {
  473. var includeFile = match[1];
  474. // Uniform declaration
  475. if (includeFile.indexOf("__decl__") !== -1) {
  476. includeFile = includeFile.replace(/__decl__/, "");
  477. if (_this._engine.supportsUniformBuffers) {
  478. includeFile = includeFile.replace(/Vertex/, "Ubo");
  479. includeFile = includeFile.replace(/Fragment/, "Ubo");
  480. }
  481. includeFile = includeFile + "Declaration";
  482. }
  483. if (Effect.IncludesShadersStore[includeFile]) {
  484. // Substitution
  485. var includeContent = Effect.IncludesShadersStore[includeFile];
  486. if (match[2]) {
  487. var splits = match[3].split(",");
  488. for (var index = 0; index < splits.length; index += 2) {
  489. var source = new RegExp(splits[index], "g");
  490. var dest = splits[index + 1];
  491. includeContent = includeContent.replace(source, dest);
  492. }
  493. }
  494. if (match[4]) {
  495. var indexString = match[5];
  496. if (indexString.indexOf("..") !== -1) {
  497. var indexSplits = indexString.split("..");
  498. var minIndex = parseInt(indexSplits[0]);
  499. var maxIndex = parseInt(indexSplits[1]);
  500. var sourceIncludeContent = includeContent.slice(0);
  501. includeContent = "";
  502. if (isNaN(maxIndex)) {
  503. maxIndex = _this._indexParameters[indexSplits[1]];
  504. }
  505. for (var i = minIndex; i < maxIndex; i++) {
  506. if (!_this._engine.supportsUniformBuffers) {
  507. // Ubo replacement
  508. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  509. return p1 + "{X}";
  510. });
  511. }
  512. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  513. }
  514. }
  515. else {
  516. if (!_this._engine.supportsUniformBuffers) {
  517. // Ubo replacement
  518. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  519. return p1 + "{X}";
  520. });
  521. }
  522. includeContent = includeContent.replace(/\{X\}/g, indexString);
  523. }
  524. }
  525. // Replace
  526. returnValue = returnValue.replace(match[0], includeContent);
  527. }
  528. else {
  529. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  530. _this._engine._loadFileAsync(includeShaderUrl)
  531. .then(function (fileContent) {
  532. Effect.IncludesShadersStore[includeFile] = fileContent;
  533. return _this._processIncludesAsync(returnValue);
  534. })
  535. .then(function (returnValue) {
  536. resolve(returnValue);
  537. });
  538. return;
  539. }
  540. match = regex.exec(sourceCode);
  541. }
  542. resolve(returnValue);
  543. });
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else {
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets an array of textures on the engine to be used in the shader.
  714. * @param channel Name of the variable.
  715. * @param textures Textures to set.
  716. */
  717. Effect.prototype.setTextureArray = function (channel, textures) {
  718. if (this._samplers.indexOf(channel + "Ex") === -1) {
  719. var initialPos = this._samplers.indexOf(channel);
  720. for (var index = 1; index < textures.length; index++) {
  721. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  722. }
  723. }
  724. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  725. };
  726. /**
  727. * 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)
  728. * @param channel Name of the sampler variable.
  729. * @param postProcess Post process to get the input texture from.
  730. */
  731. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  732. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  733. };
  734. /** @ignore */
  735. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  736. var cache = this._valueCache[uniformName];
  737. var flag = matrix.updateFlag;
  738. if (cache !== undefined && cache === flag) {
  739. return false;
  740. }
  741. this._valueCache[uniformName] = flag;
  742. return true;
  743. };
  744. /** @ignore */
  745. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  746. var cache = this._valueCache[uniformName];
  747. if (!cache) {
  748. cache = [x, y];
  749. this._valueCache[uniformName] = cache;
  750. return true;
  751. }
  752. var changed = false;
  753. if (cache[0] !== x) {
  754. cache[0] = x;
  755. changed = true;
  756. }
  757. if (cache[1] !== y) {
  758. cache[1] = y;
  759. changed = true;
  760. }
  761. return changed;
  762. };
  763. /** @ignore */
  764. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  765. var cache = this._valueCache[uniformName];
  766. if (!cache) {
  767. cache = [x, y, z];
  768. this._valueCache[uniformName] = cache;
  769. return true;
  770. }
  771. var changed = false;
  772. if (cache[0] !== x) {
  773. cache[0] = x;
  774. changed = true;
  775. }
  776. if (cache[1] !== y) {
  777. cache[1] = y;
  778. changed = true;
  779. }
  780. if (cache[2] !== z) {
  781. cache[2] = z;
  782. changed = true;
  783. }
  784. return changed;
  785. };
  786. /** @ignore */
  787. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  788. var cache = this._valueCache[uniformName];
  789. if (!cache) {
  790. cache = [x, y, z, w];
  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. if (cache[2] !== z) {
  804. cache[2] = z;
  805. changed = true;
  806. }
  807. if (cache[3] !== w) {
  808. cache[3] = w;
  809. changed = true;
  810. }
  811. return changed;
  812. };
  813. /**
  814. * Binds a buffer to a uniform.
  815. * @param buffer Buffer to bind.
  816. * @param name Name of the uniform variable to bind to.
  817. */
  818. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  819. var bufferName = this._uniformBuffersNames[name];
  820. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  821. return;
  822. }
  823. Effect._baseCache[bufferName] = buffer;
  824. this._engine.bindUniformBufferBase(buffer, bufferName);
  825. };
  826. /**
  827. * Binds block to a uniform.
  828. * @param blockName Name of the block to bind.
  829. * @param index Index to bind.
  830. */
  831. Effect.prototype.bindUniformBlock = function (blockName, index) {
  832. this._engine.bindUniformBlock(this._program, blockName, index);
  833. };
  834. /**
  835. * Sets an interger value on a uniform variable.
  836. * @param uniformName Name of the variable.
  837. * @param value Value to be set.
  838. * @returns this effect.
  839. */
  840. Effect.prototype.setInt = function (uniformName, value) {
  841. var cache = this._valueCache[uniformName];
  842. if (cache !== undefined && cache === value)
  843. return this;
  844. this._valueCache[uniformName] = value;
  845. this._engine.setInt(this.getUniform(uniformName), value);
  846. return this;
  847. };
  848. /**
  849. * Sets an int array on a uniform variable.
  850. * @param uniformName Name of the variable.
  851. * @param array array to be set.
  852. * @returns this effect.
  853. */
  854. Effect.prototype.setIntArray = function (uniformName, array) {
  855. this._valueCache[uniformName] = null;
  856. this._engine.setIntArray(this.getUniform(uniformName), array);
  857. return this;
  858. };
  859. /**
  860. * 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)
  861. * @param uniformName Name of the variable.
  862. * @param array array to be set.
  863. * @returns this effect.
  864. */
  865. Effect.prototype.setIntArray2 = function (uniformName, array) {
  866. this._valueCache[uniformName] = null;
  867. this._engine.setIntArray2(this.getUniform(uniformName), array);
  868. return this;
  869. };
  870. /**
  871. * 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)
  872. * @param uniformName Name of the variable.
  873. * @param array array to be set.
  874. * @returns this effect.
  875. */
  876. Effect.prototype.setIntArray3 = function (uniformName, array) {
  877. this._valueCache[uniformName] = null;
  878. this._engine.setIntArray3(this.getUniform(uniformName), array);
  879. return this;
  880. };
  881. /**
  882. * 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)
  883. * @param uniformName Name of the variable.
  884. * @param array array to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setIntArray4 = function (uniformName, array) {
  888. this._valueCache[uniformName] = null;
  889. this._engine.setIntArray4(this.getUniform(uniformName), array);
  890. return this;
  891. };
  892. /**
  893. * Sets an float array on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param array array to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setFloatArray = function (uniformName, array) {
  899. this._valueCache[uniformName] = null;
  900. this._engine.setFloatArray(this.getUniform(uniformName), array);
  901. return this;
  902. };
  903. /**
  904. * 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)
  905. * @param uniformName Name of the variable.
  906. * @param array array to be set.
  907. * @returns this effect.
  908. */
  909. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  910. this._valueCache[uniformName] = null;
  911. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  912. return this;
  913. };
  914. /**
  915. * 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)
  916. * @param uniformName Name of the variable.
  917. * @param array array to be set.
  918. * @returns this effect.
  919. */
  920. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  921. this._valueCache[uniformName] = null;
  922. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  923. return this;
  924. };
  925. /**
  926. * 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)
  927. * @param uniformName Name of the variable.
  928. * @param array array to be set.
  929. * @returns this effect.
  930. */
  931. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  932. this._valueCache[uniformName] = null;
  933. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  934. return this;
  935. };
  936. /**
  937. * Sets an array on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param array array to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setArray = function (uniformName, array) {
  943. this._valueCache[uniformName] = null;
  944. this._engine.setArray(this.getUniform(uniformName), array);
  945. return this;
  946. };
  947. /**
  948. * 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)
  949. * @param uniformName Name of the variable.
  950. * @param array array to be set.
  951. * @returns this effect.
  952. */
  953. Effect.prototype.setArray2 = function (uniformName, array) {
  954. this._valueCache[uniformName] = null;
  955. this._engine.setArray2(this.getUniform(uniformName), array);
  956. return this;
  957. };
  958. /**
  959. * 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)
  960. * @param uniformName Name of the variable.
  961. * @param array array to be set.
  962. * @returns this effect.
  963. */
  964. Effect.prototype.setArray3 = function (uniformName, array) {
  965. this._valueCache[uniformName] = null;
  966. this._engine.setArray3(this.getUniform(uniformName), array);
  967. return this;
  968. };
  969. /**
  970. * 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)
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setArray4 = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setArray4(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * Sets matrices on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param matrices matrices to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setMatrices = function (uniformName, matrices) {
  987. if (!matrices) {
  988. return this;
  989. }
  990. this._valueCache[uniformName] = null;
  991. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  992. return this;
  993. };
  994. /**
  995. * Sets matrix on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param matrix matrix to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1001. if (this._cacheMatrix(uniformName, matrix)) {
  1002. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1003. }
  1004. return this;
  1005. };
  1006. /**
  1007. * 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)
  1008. * @param uniformName Name of the variable.
  1009. * @param matrix matrix to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1019. * @param uniformName Name of the variable.
  1020. * @param matrix matrix to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets a float on a uniform variable.
  1030. * @param uniformName Name of the variable.
  1031. * @param value value to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setFloat = function (uniformName, value) {
  1035. var cache = this._valueCache[uniformName];
  1036. if (cache !== undefined && cache === value)
  1037. return this;
  1038. this._valueCache[uniformName] = value;
  1039. this._engine.setFloat(this.getUniform(uniformName), value);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a boolean on a uniform variable.
  1044. * @param uniformName Name of the variable.
  1045. * @param bool value to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setBool = function (uniformName, bool) {
  1049. var cache = this._valueCache[uniformName];
  1050. if (cache !== undefined && cache === bool)
  1051. return this;
  1052. this._valueCache[uniformName] = bool;
  1053. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1054. return this;
  1055. };
  1056. /**
  1057. * Sets a Vector2 on a uniform variable.
  1058. * @param uniformName Name of the variable.
  1059. * @param vector2 vector2 to be set.
  1060. * @returns this effect.
  1061. */
  1062. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1063. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1064. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1065. }
  1066. return this;
  1067. };
  1068. /**
  1069. * Sets a float2 on a uniform variable.
  1070. * @param uniformName Name of the variable.
  1071. * @param x First float in float2.
  1072. * @param y Second float in float2.
  1073. * @returns this effect.
  1074. */
  1075. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1076. if (this._cacheFloat2(uniformName, x, y)) {
  1077. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1078. }
  1079. return this;
  1080. };
  1081. /**
  1082. * Sets a Vector3 on a uniform variable.
  1083. * @param uniformName Name of the variable.
  1084. * @param vector3 Value to be set.
  1085. * @returns this effect.
  1086. */
  1087. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1088. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1089. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1090. }
  1091. return this;
  1092. };
  1093. /**
  1094. * Sets a float3 on a uniform variable.
  1095. * @param uniformName Name of the variable.
  1096. * @param x First float in float3.
  1097. * @param y Second float in float3.
  1098. * @param z Third float in float3.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1102. if (this._cacheFloat3(uniformName, x, y, z)) {
  1103. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1104. }
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets a Vector4 on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param vector4 Value to be set.
  1111. * @returns this effect.
  1112. */
  1113. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1114. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1115. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1116. }
  1117. return this;
  1118. };
  1119. /**
  1120. * Sets a float4 on a uniform variable.
  1121. * @param uniformName Name of the variable.
  1122. * @param x First float in float4.
  1123. * @param y Second float in float4.
  1124. * @param z Third float in float4.
  1125. * @param w Fourth float in float4.
  1126. * @returns this effect.
  1127. */
  1128. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1129. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1130. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1131. }
  1132. return this;
  1133. };
  1134. /**
  1135. * Sets a Color3 on a uniform variable.
  1136. * @param uniformName Name of the variable.
  1137. * @param color3 Value to be set.
  1138. * @returns this effect.
  1139. */
  1140. Effect.prototype.setColor3 = function (uniformName, color3) {
  1141. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1142. this._engine.setColor3(this.getUniform(uniformName), color3);
  1143. }
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a Color4 on a uniform variable.
  1148. * @param uniformName Name of the variable.
  1149. * @param color3 Value to be set.
  1150. * @param alpha Alpha value to be set.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1154. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1155. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a Color4 on a uniform variable
  1161. * @param uniformName defines the name of the variable
  1162. * @param color4 defines the value to be set
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1166. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1167. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * Resets the cache of effects.
  1173. */
  1174. Effect.ResetCache = function () {
  1175. Effect._baseCache = {};
  1176. };
  1177. Effect._uniqueIdSeed = 0;
  1178. Effect._baseCache = {};
  1179. // Statics
  1180. /**
  1181. * Store of each shader (The can be looked up using effect.key)
  1182. */
  1183. Effect.ShadersStore = {};
  1184. /**
  1185. * Store of each included file for a shader (The can be looked up using effect.key)
  1186. */
  1187. Effect.IncludesShadersStore = {};
  1188. return Effect;
  1189. }());
  1190. BABYLON.Effect = Effect;
  1191. })(BABYLON || (BABYLON = {}));
  1192. //# sourceMappingURL=babylon.effect.js.map
  1193. //# sourceMappingURL=babylon.types.js.map
  1194. var BABYLON;
  1195. (function (BABYLON) {
  1196. var KeyboardEventTypes = /** @class */ (function () {
  1197. function KeyboardEventTypes() {
  1198. }
  1199. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1200. get: function () {
  1201. return KeyboardEventTypes._KEYDOWN;
  1202. },
  1203. enumerable: true,
  1204. configurable: true
  1205. });
  1206. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1207. get: function () {
  1208. return KeyboardEventTypes._KEYUP;
  1209. },
  1210. enumerable: true,
  1211. configurable: true
  1212. });
  1213. KeyboardEventTypes._KEYDOWN = 0x01;
  1214. KeyboardEventTypes._KEYUP = 0x02;
  1215. return KeyboardEventTypes;
  1216. }());
  1217. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1218. var KeyboardInfo = /** @class */ (function () {
  1219. function KeyboardInfo(type, event) {
  1220. this.type = type;
  1221. this.event = event;
  1222. }
  1223. return KeyboardInfo;
  1224. }());
  1225. BABYLON.KeyboardInfo = KeyboardInfo;
  1226. /**
  1227. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1228. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1229. */
  1230. var KeyboardInfoPre = /** @class */ (function (_super) {
  1231. __extends(KeyboardInfoPre, _super);
  1232. function KeyboardInfoPre(type, event) {
  1233. var _this = _super.call(this, type, event) || this;
  1234. _this.skipOnPointerObservable = false;
  1235. return _this;
  1236. }
  1237. return KeyboardInfoPre;
  1238. }(KeyboardInfo));
  1239. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1240. })(BABYLON || (BABYLON = {}));
  1241. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1242. var BABYLON;
  1243. (function (BABYLON) {
  1244. var PointerEventTypes = /** @class */ (function () {
  1245. function PointerEventTypes() {
  1246. }
  1247. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERDOWN;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERUP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERMOVE;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERWHEEL;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERPICK;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1283. get: function () {
  1284. return PointerEventTypes._POINTERTAP;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERDOUBLETAP;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. PointerEventTypes._POINTERDOWN = 0x01;
  1297. PointerEventTypes._POINTERUP = 0x02;
  1298. PointerEventTypes._POINTERMOVE = 0x04;
  1299. PointerEventTypes._POINTERWHEEL = 0x08;
  1300. PointerEventTypes._POINTERPICK = 0x10;
  1301. PointerEventTypes._POINTERTAP = 0x20;
  1302. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1303. return PointerEventTypes;
  1304. }());
  1305. BABYLON.PointerEventTypes = PointerEventTypes;
  1306. var PointerInfoBase = /** @class */ (function () {
  1307. function PointerInfoBase(type, event) {
  1308. this.type = type;
  1309. this.event = event;
  1310. }
  1311. return PointerInfoBase;
  1312. }());
  1313. BABYLON.PointerInfoBase = PointerInfoBase;
  1314. /**
  1315. * This class is used to store pointer related info for the onPrePointerObservable event.
  1316. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1317. */
  1318. var PointerInfoPre = /** @class */ (function (_super) {
  1319. __extends(PointerInfoPre, _super);
  1320. function PointerInfoPre(type, event, localX, localY) {
  1321. var _this = _super.call(this, type, event) || this;
  1322. _this.skipOnPointerObservable = false;
  1323. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1324. return _this;
  1325. }
  1326. return PointerInfoPre;
  1327. }(PointerInfoBase));
  1328. BABYLON.PointerInfoPre = PointerInfoPre;
  1329. /**
  1330. * This type contains all the data related to a pointer event in Babylon.js.
  1331. * 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.
  1332. */
  1333. var PointerInfo = /** @class */ (function (_super) {
  1334. __extends(PointerInfo, _super);
  1335. function PointerInfo(type, event, pickInfo) {
  1336. var _this = _super.call(this, type, event) || this;
  1337. _this.pickInfo = pickInfo;
  1338. return _this;
  1339. }
  1340. return PointerInfo;
  1341. }(PointerInfoBase));
  1342. BABYLON.PointerInfo = PointerInfo;
  1343. })(BABYLON || (BABYLON = {}));
  1344. //# sourceMappingURL=babylon.pointerEvents.js.map
  1345. var BABYLON;
  1346. (function (BABYLON) {
  1347. BABYLON.ToGammaSpace = 1 / 2.2;
  1348. BABYLON.ToLinearSpace = 2.2;
  1349. BABYLON.Epsilon = 0.001;
  1350. /**
  1351. * Class used to hold a RBG color
  1352. */
  1353. var Color3 = /** @class */ (function () {
  1354. /**
  1355. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1356. * @param r defines the red component (between 0 and 1, default is 0)
  1357. * @param g defines the green component (between 0 and 1, default is 0)
  1358. * @param b defines the blue component (between 0 and 1, default is 0)
  1359. */
  1360. function Color3(
  1361. /**
  1362. * Defines the red component (between 0 and 1, default is 0)
  1363. */
  1364. r,
  1365. /**
  1366. * Defines the green component (between 0 and 1, default is 0)
  1367. */
  1368. g,
  1369. /**
  1370. * Defines the blue component (between 0 and 1, default is 0)
  1371. */
  1372. b) {
  1373. if (r === void 0) { r = 0; }
  1374. if (g === void 0) { g = 0; }
  1375. if (b === void 0) { b = 0; }
  1376. this.r = r;
  1377. this.g = g;
  1378. this.b = b;
  1379. }
  1380. /**
  1381. * Creates a string with the Color3 current values
  1382. * @returns the string representation of the Color3 object
  1383. */
  1384. Color3.prototype.toString = function () {
  1385. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1386. };
  1387. /**
  1388. * Returns the string "Color3"
  1389. * @returns "Color3"
  1390. */
  1391. Color3.prototype.getClassName = function () {
  1392. return "Color3";
  1393. };
  1394. /**
  1395. * Compute the Color3 hash code
  1396. * @returns an unique number that can be used to hash Color3 objects
  1397. */
  1398. Color3.prototype.getHashCode = function () {
  1399. var hash = this.r || 0;
  1400. hash = (hash * 397) ^ (this.g || 0);
  1401. hash = (hash * 397) ^ (this.b || 0);
  1402. return hash;
  1403. };
  1404. // Operators
  1405. /**
  1406. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1407. * @param array defines the array where to store the r,g,b components
  1408. * @param index defines an optional index in the target array to define where to start storing values
  1409. * @returns the current Color3 object
  1410. */
  1411. Color3.prototype.toArray = function (array, index) {
  1412. if (index === undefined) {
  1413. index = 0;
  1414. }
  1415. array[index] = this.r;
  1416. array[index + 1] = this.g;
  1417. array[index + 2] = this.b;
  1418. return this;
  1419. };
  1420. /**
  1421. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1422. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1423. * @returns a new {BABYLON.Color4} object
  1424. */
  1425. Color3.prototype.toColor4 = function (alpha) {
  1426. if (alpha === void 0) { alpha = 1; }
  1427. return new Color4(this.r, this.g, this.b, alpha);
  1428. };
  1429. /**
  1430. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1431. * @returns the new array
  1432. */
  1433. Color3.prototype.asArray = function () {
  1434. var result = new Array();
  1435. this.toArray(result, 0);
  1436. return result;
  1437. };
  1438. /**
  1439. * Returns the luminance value
  1440. * @returns a float value
  1441. */
  1442. Color3.prototype.toLuminance = function () {
  1443. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1444. };
  1445. /**
  1446. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1447. * @param otherColor defines the second operand
  1448. * @returns the new Color3 object
  1449. */
  1450. Color3.prototype.multiply = function (otherColor) {
  1451. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1452. };
  1453. /**
  1454. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1455. * @param otherColor defines the second operand
  1456. * @param result defines the Color3 object where to store the result
  1457. * @returns the current Color3
  1458. */
  1459. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1460. result.r = this.r * otherColor.r;
  1461. result.g = this.g * otherColor.g;
  1462. result.b = this.b * otherColor.b;
  1463. return this;
  1464. };
  1465. /**
  1466. * Determines equality between Color3 objects
  1467. * @param otherColor defines the second operand
  1468. * @returns true if the rgb values are equal to the passed ones
  1469. */
  1470. Color3.prototype.equals = function (otherColor) {
  1471. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1472. };
  1473. /**
  1474. * Determines equality between the current Color3 object and a set of r,b,g values
  1475. * @param r defines the red component to check
  1476. * @param g defines the green component to check
  1477. * @param b defines the blue component to check
  1478. * @returns true if the rgb values are equal to the passed ones
  1479. */
  1480. Color3.prototype.equalsFloats = function (r, g, b) {
  1481. return this.r === r && this.g === g && this.b === b;
  1482. };
  1483. /**
  1484. * Multiplies in place each rgb value by scale
  1485. * @param scale defines the scaling factor
  1486. * @returns the updated Color3.
  1487. */
  1488. Color3.prototype.scale = function (scale) {
  1489. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1490. };
  1491. /**
  1492. * Multiplies the rgb values by scale and stores the result into "result"
  1493. * @param scale defines the scaling factor
  1494. * @param result defines the Color3 object where to store the result
  1495. * @returns the unmodified current Color3.
  1496. */
  1497. Color3.prototype.scaleToRef = function (scale, result) {
  1498. result.r = this.r * scale;
  1499. result.g = this.g * scale;
  1500. result.b = this.b * scale;
  1501. return this;
  1502. };
  1503. /**
  1504. * Clamps the rgb values by the min and max values and stores the result into "result"
  1505. * @param min defines minimum clamping value (default is 0)
  1506. * @param max defines maximum clamping value (default is 1)
  1507. * @param result defines color to store the result into
  1508. * @returns the original Color3
  1509. */
  1510. Color3.prototype.clampToRef = function (min, max, result) {
  1511. if (min === void 0) { min = 0; }
  1512. if (max === void 0) { max = 1; }
  1513. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1514. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1515. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1516. return this;
  1517. };
  1518. /**
  1519. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1520. * @param otherColor defines the second operand
  1521. * @returns the new Color3
  1522. */
  1523. Color3.prototype.add = function (otherColor) {
  1524. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1525. };
  1526. /**
  1527. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1528. * @param otherColor defines the second operand
  1529. * @param result defines Color3 object to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.addToRef = function (otherColor, result) {
  1533. result.r = this.r + otherColor.r;
  1534. result.g = this.g + otherColor.g;
  1535. result.b = this.b + otherColor.b;
  1536. return this;
  1537. };
  1538. /**
  1539. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1540. * @param otherColor defines the second operand
  1541. * @returns the new Color3
  1542. */
  1543. Color3.prototype.subtract = function (otherColor) {
  1544. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1545. };
  1546. /**
  1547. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1548. * @param otherColor defines the second operand
  1549. * @param result defines Color3 object to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.subtractToRef = function (otherColor, result) {
  1553. result.r = this.r - otherColor.r;
  1554. result.g = this.g - otherColor.g;
  1555. result.b = this.b - otherColor.b;
  1556. return this;
  1557. };
  1558. /**
  1559. * Copy the current object
  1560. * @returns a new Color3 copied the current one
  1561. */
  1562. Color3.prototype.clone = function () {
  1563. return new Color3(this.r, this.g, this.b);
  1564. };
  1565. /**
  1566. * Copies the rgb values from the source in the current Color3
  1567. * @param source defines the source Color3 object
  1568. * @returns the updated Color3 object
  1569. */
  1570. Color3.prototype.copyFrom = function (source) {
  1571. this.r = source.r;
  1572. this.g = source.g;
  1573. this.b = source.b;
  1574. return this;
  1575. };
  1576. /**
  1577. * Updates the Color3 rgb values from the passed floats
  1578. * @param r defines the red component to read from
  1579. * @param g defines the green component to read from
  1580. * @param b defines the blue component to read from
  1581. * @returns the current Color3 object
  1582. */
  1583. Color3.prototype.copyFromFloats = function (r, g, b) {
  1584. this.r = r;
  1585. this.g = g;
  1586. this.b = b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Updates the Color3 rgb values from the passed floats
  1591. * @param r defines the red component to read from
  1592. * @param g defines the green component to read from
  1593. * @param b defines the blue component to read from
  1594. * @returns the current Color3 object
  1595. */
  1596. Color3.prototype.set = function (r, g, b) {
  1597. return this.copyFromFloats(r, g, b);
  1598. };
  1599. /**
  1600. * Compute the Color3 hexadecimal code as a string
  1601. * @returns a string containing the hexadecimal representation of the Color3 object
  1602. */
  1603. Color3.prototype.toHexString = function () {
  1604. var intR = (this.r * 255) | 0;
  1605. var intG = (this.g * 255) | 0;
  1606. var intB = (this.b * 255) | 0;
  1607. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1608. };
  1609. /**
  1610. * Computes a new Color3 converted from the current one to linear space
  1611. * @returns a new Color3 object
  1612. */
  1613. Color3.prototype.toLinearSpace = function () {
  1614. var convertedColor = new Color3();
  1615. this.toLinearSpaceToRef(convertedColor);
  1616. return convertedColor;
  1617. };
  1618. /**
  1619. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1620. * @param convertedColor defines the Color3 object where to store the linear space version
  1621. * @returns the unmodified Color3
  1622. */
  1623. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1624. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1625. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1626. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1627. return this;
  1628. };
  1629. /**
  1630. * Computes a new Color3 converted from the current one to gamma space
  1631. * @returns a new Color3 object
  1632. */
  1633. Color3.prototype.toGammaSpace = function () {
  1634. var convertedColor = new Color3();
  1635. this.toGammaSpaceToRef(convertedColor);
  1636. return convertedColor;
  1637. };
  1638. /**
  1639. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1640. * @param convertedColor defines the Color3 object where to store the gamma space version
  1641. * @returns the unmodified Color3
  1642. */
  1643. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1644. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1645. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1646. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1647. return this;
  1648. };
  1649. // Statics
  1650. /**
  1651. * Creates a new Color3 from the string containing valid hexadecimal values
  1652. * @param hex defines a string containing valid hexadecimal values
  1653. * @returns a new Color3 object
  1654. */
  1655. Color3.FromHexString = function (hex) {
  1656. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1657. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1658. return new Color3(0, 0, 0);
  1659. }
  1660. var r = parseInt(hex.substring(1, 3), 16);
  1661. var g = parseInt(hex.substring(3, 5), 16);
  1662. var b = parseInt(hex.substring(5, 7), 16);
  1663. return Color3.FromInts(r, g, b);
  1664. };
  1665. /**
  1666. * Creates a new Vector3 from the starting index of the passed array
  1667. * @param array defines the source array
  1668. * @param offset defines an offset in the source array
  1669. * @returns a new Color3 object
  1670. */
  1671. Color3.FromArray = function (array, offset) {
  1672. if (offset === void 0) { offset = 0; }
  1673. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1674. };
  1675. /**
  1676. * Creates a new Color3 from integer values (< 256)
  1677. * @param r defines the red component to read from (value between 0 and 255)
  1678. * @param g defines the green component to read from (value between 0 and 255)
  1679. * @param b defines the blue component to read from (value between 0 and 255)
  1680. * @returns a new Color3 object
  1681. */
  1682. Color3.FromInts = function (r, g, b) {
  1683. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1684. };
  1685. /**
  1686. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1687. * @param start defines the start Color3 value
  1688. * @param end defines the end Color3 value
  1689. * @param amount defines the gradient value between start and end
  1690. * @returns a new Color3 object
  1691. */
  1692. Color3.Lerp = function (start, end, amount) {
  1693. var r = start.r + ((end.r - start.r) * amount);
  1694. var g = start.g + ((end.g - start.g) * amount);
  1695. var b = start.b + ((end.b - start.b) * amount);
  1696. return new Color3(r, g, b);
  1697. };
  1698. /**
  1699. * Returns a Color3 value containing a red color
  1700. * @returns a new Color3 object
  1701. */
  1702. Color3.Red = function () { return new Color3(1, 0, 0); };
  1703. /**
  1704. * Returns a Color3 value containing a green color
  1705. * @returns a new Color3 object
  1706. */
  1707. Color3.Green = function () { return new Color3(0, 1, 0); };
  1708. /**
  1709. * Returns a Color3 value containing a blue color
  1710. * @returns a new Color3 object
  1711. */
  1712. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1713. /**
  1714. * Returns a Color3 value containing a black color
  1715. * @returns a new Color3 object
  1716. */
  1717. Color3.Black = function () { return new Color3(0, 0, 0); };
  1718. /**
  1719. * Returns a Color3 value containing a white color
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.White = function () { return new Color3(1, 1, 1); };
  1723. /**
  1724. * Returns a Color3 value containing a purple color
  1725. * @returns a new Color3 object
  1726. */
  1727. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1728. /**
  1729. * Returns a Color3 value containing a magenta color
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1733. /**
  1734. * Returns a Color3 value containing a yellow color
  1735. * @returns a new Color3 object
  1736. */
  1737. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1738. /**
  1739. * Returns a Color3 value containing a gray color
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1743. /**
  1744. * Returns a Color3 value containing a teal color
  1745. * @returns a new Color3 object
  1746. */
  1747. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1748. /**
  1749. * Returns a Color3 value containing a random color
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1753. return Color3;
  1754. }());
  1755. BABYLON.Color3 = Color3;
  1756. /**
  1757. * Class used to hold a RBGA color
  1758. */
  1759. var Color4 = /** @class */ (function () {
  1760. /**
  1761. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1762. * @param r defines the red component (between 0 and 1, default is 0)
  1763. * @param g defines the green component (between 0 and 1, default is 0)
  1764. * @param b defines the blue component (between 0 and 1, default is 0)
  1765. * @param a defines the alpha component (between 0 and 1, default is 1)
  1766. */
  1767. function Color4(
  1768. /**
  1769. * Defines the red component (between 0 and 1, default is 0)
  1770. */
  1771. r,
  1772. /**
  1773. * Defines the green component (between 0 and 1, default is 0)
  1774. */
  1775. g,
  1776. /**
  1777. * Defines the blue component (between 0 and 1, default is 0)
  1778. */
  1779. b,
  1780. /**
  1781. * Defines the alpha component (between 0 and 1, default is 1)
  1782. */
  1783. a) {
  1784. if (r === void 0) { r = 0; }
  1785. if (g === void 0) { g = 0; }
  1786. if (b === void 0) { b = 0; }
  1787. if (a === void 0) { a = 1; }
  1788. this.r = r;
  1789. this.g = g;
  1790. this.b = b;
  1791. this.a = a;
  1792. }
  1793. // Operators
  1794. /**
  1795. * Adds in place the passed Color4 values to the current Color4 object
  1796. * @param right defines the second operand
  1797. * @returns the current updated Color4 object
  1798. */
  1799. Color4.prototype.addInPlace = function (right) {
  1800. this.r += right.r;
  1801. this.g += right.g;
  1802. this.b += right.b;
  1803. this.a += right.a;
  1804. return this;
  1805. };
  1806. /**
  1807. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1808. * @returns the new array
  1809. */
  1810. Color4.prototype.asArray = function () {
  1811. var result = new Array();
  1812. this.toArray(result, 0);
  1813. return result;
  1814. };
  1815. /**
  1816. * Stores from the starting index in the passed array the Color4 successive values
  1817. * @param array defines the array where to store the r,g,b components
  1818. * @param index defines an optional index in the target array to define where to start storing values
  1819. * @returns the current Color4 object
  1820. */
  1821. Color4.prototype.toArray = function (array, index) {
  1822. if (index === undefined) {
  1823. index = 0;
  1824. }
  1825. array[index] = this.r;
  1826. array[index + 1] = this.g;
  1827. array[index + 2] = this.b;
  1828. array[index + 3] = this.a;
  1829. return this;
  1830. };
  1831. /**
  1832. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1833. * @param right defines the second operand
  1834. * @returns a new Color4 object
  1835. */
  1836. Color4.prototype.add = function (right) {
  1837. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1838. };
  1839. /**
  1840. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1841. * @param right defines the second operand
  1842. * @returns a new Color4 object
  1843. */
  1844. Color4.prototype.subtract = function (right) {
  1845. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1846. };
  1847. /**
  1848. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1849. * @param right defines the second operand
  1850. * @param result defines the Color4 object where to store the result
  1851. * @returns the current Color4 object
  1852. */
  1853. Color4.prototype.subtractToRef = function (right, result) {
  1854. result.r = this.r - right.r;
  1855. result.g = this.g - right.g;
  1856. result.b = this.b - right.b;
  1857. result.a = this.a - right.a;
  1858. return this;
  1859. };
  1860. /**
  1861. * Creates a new Color4 with the current Color4 values multiplied by scale
  1862. * @param scale defines the scaling factor to apply
  1863. * @returns a new Color4 object
  1864. */
  1865. Color4.prototype.scale = function (scale) {
  1866. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1867. };
  1868. /**
  1869. * Multiplies the current Color4 values by scale and stores the result in "result"
  1870. * @param scale defines the scaling factor to apply
  1871. * @param result defines the Color4 object where to store the result
  1872. * @returns the current Color4.
  1873. */
  1874. Color4.prototype.scaleToRef = function (scale, result) {
  1875. result.r = this.r * scale;
  1876. result.g = this.g * scale;
  1877. result.b = this.b * scale;
  1878. result.a = this.a * scale;
  1879. return this;
  1880. };
  1881. /**
  1882. * Clamps the rgb values by the min and max values and stores the result into "result"
  1883. * @param min defines minimum clamping value (default is 0)
  1884. * @param max defines maximum clamping value (default is 1)
  1885. * @param result defines color to store the result into.
  1886. * @returns the cuurent Color4
  1887. */
  1888. Color4.prototype.clampToRef = function (min, max, result) {
  1889. if (min === void 0) { min = 0; }
  1890. if (max === void 0) { max = 1; }
  1891. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1892. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1893. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1894. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1895. return this;
  1896. };
  1897. /**
  1898. * Multipy an Color4 value by another and return a new Color4 object
  1899. * @param color defines the Color4 value to multiply by
  1900. * @returns a new Color4 object
  1901. */
  1902. Color4.prototype.multiply = function (color) {
  1903. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1904. };
  1905. /**
  1906. * Multipy a Color4 value by another and push the result in a reference value
  1907. * @param color defines the Color4 value to multiply by
  1908. * @param result defines the Color4 to fill the result in
  1909. * @returns the result Color4
  1910. */
  1911. Color4.prototype.multiplyToRef = function (color, result) {
  1912. result.r = this.r * color.r;
  1913. result.g = this.g * color.g;
  1914. result.b = this.b * color.b;
  1915. result.a = this.a * color.a;
  1916. return result;
  1917. };
  1918. /**
  1919. * Creates a string with the Color4 current values
  1920. * @returns the string representation of the Color4 object
  1921. */
  1922. Color4.prototype.toString = function () {
  1923. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1924. };
  1925. /**
  1926. * Returns the string "Color4"
  1927. * @returns "Color4"
  1928. */
  1929. Color4.prototype.getClassName = function () {
  1930. return "Color4";
  1931. };
  1932. /**
  1933. * Compute the Color4 hash code
  1934. * @returns an unique number that can be used to hash Color4 objects
  1935. */
  1936. Color4.prototype.getHashCode = function () {
  1937. var hash = this.r || 0;
  1938. hash = (hash * 397) ^ (this.g || 0);
  1939. hash = (hash * 397) ^ (this.b || 0);
  1940. hash = (hash * 397) ^ (this.a || 0);
  1941. return hash;
  1942. };
  1943. /**
  1944. * Creates a new Color4 copied from the current one
  1945. * @returns a new Color4 object
  1946. */
  1947. Color4.prototype.clone = function () {
  1948. return new Color4(this.r, this.g, this.b, this.a);
  1949. };
  1950. /**
  1951. * Copies the passed Color4 values into the current one
  1952. * @param source defines the source Color4 object
  1953. * @returns the current updated Color4 object
  1954. */
  1955. Color4.prototype.copyFrom = function (source) {
  1956. this.r = source.r;
  1957. this.g = source.g;
  1958. this.b = source.b;
  1959. this.a = source.a;
  1960. return this;
  1961. };
  1962. /**
  1963. * Copies the passed float values into the current one
  1964. * @param r defines the red component to read from
  1965. * @param g defines the green component to read from
  1966. * @param b defines the blue component to read from
  1967. * @param a defines the alpha component to read from
  1968. * @returns the current updated Color4 object
  1969. */
  1970. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1971. this.r = r;
  1972. this.g = g;
  1973. this.b = b;
  1974. this.a = a;
  1975. return this;
  1976. };
  1977. /**
  1978. * Copies the passed float values into the current one
  1979. * @param r defines the red component to read from
  1980. * @param g defines the green component to read from
  1981. * @param b defines the blue component to read from
  1982. * @param a defines the alpha component to read from
  1983. * @returns the current updated Color4 object
  1984. */
  1985. Color4.prototype.set = function (r, g, b, a) {
  1986. return this.copyFromFloats(r, g, b, a);
  1987. };
  1988. /**
  1989. * Compute the Color4 hexadecimal code as a string
  1990. * @returns a string containing the hexadecimal representation of the Color4 object
  1991. */
  1992. Color4.prototype.toHexString = function () {
  1993. var intR = (this.r * 255) | 0;
  1994. var intG = (this.g * 255) | 0;
  1995. var intB = (this.b * 255) | 0;
  1996. var intA = (this.a * 255) | 0;
  1997. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1998. };
  1999. /**
  2000. * Computes a new Color4 converted from the current one to linear space
  2001. * @returns a new Color4 object
  2002. */
  2003. Color4.prototype.toLinearSpace = function () {
  2004. var convertedColor = new Color4();
  2005. this.toLinearSpaceToRef(convertedColor);
  2006. return convertedColor;
  2007. };
  2008. /**
  2009. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2010. * @param convertedColor defines the Color4 object where to store the linear space version
  2011. * @returns the unmodified Color4
  2012. */
  2013. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2014. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2015. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2016. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2017. convertedColor.a = this.a;
  2018. return this;
  2019. };
  2020. /**
  2021. * Computes a new Color4 converted from the current one to gamma space
  2022. * @returns a new Color4 object
  2023. */
  2024. Color4.prototype.toGammaSpace = function () {
  2025. var convertedColor = new Color4();
  2026. this.toGammaSpaceToRef(convertedColor);
  2027. return convertedColor;
  2028. };
  2029. /**
  2030. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2031. * @param convertedColor defines the Color4 object where to store the gamma space version
  2032. * @returns the unmodified Color4
  2033. */
  2034. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2035. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2036. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2037. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2038. convertedColor.a = this.a;
  2039. return this;
  2040. };
  2041. // Statics
  2042. /**
  2043. * Creates a new Color4 from the string containing valid hexadecimal values
  2044. * @param hex defines a string containing valid hexadecimal values
  2045. * @returns a new Color4 object
  2046. */
  2047. Color4.FromHexString = function (hex) {
  2048. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2049. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2050. return new Color4(0.0, 0.0, 0.0, 0.0);
  2051. }
  2052. var r = parseInt(hex.substring(1, 3), 16);
  2053. var g = parseInt(hex.substring(3, 5), 16);
  2054. var b = parseInt(hex.substring(5, 7), 16);
  2055. var a = parseInt(hex.substring(7, 9), 16);
  2056. return Color4.FromInts(r, g, b, a);
  2057. };
  2058. /**
  2059. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2060. * @param left defines the start value
  2061. * @param right defines the end value
  2062. * @param amount defines the gradient factor
  2063. * @returns a new Color4 object
  2064. */
  2065. Color4.Lerp = function (left, right, amount) {
  2066. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2067. Color4.LerpToRef(left, right, amount, result);
  2068. return result;
  2069. };
  2070. /**
  2071. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2072. * @param left defines the start value
  2073. * @param right defines the end value
  2074. * @param amount defines the gradient factor
  2075. * @param result defines the Color4 object where to store data
  2076. */
  2077. Color4.LerpToRef = function (left, right, amount, result) {
  2078. result.r = left.r + (right.r - left.r) * amount;
  2079. result.g = left.g + (right.g - left.g) * amount;
  2080. result.b = left.b + (right.b - left.b) * amount;
  2081. result.a = left.a + (right.a - left.a) * amount;
  2082. };
  2083. /**
  2084. * Creates a new Color4 from the starting index element of the passed array
  2085. * @param array defines the source array to read from
  2086. * @param offset defines the offset in the source array
  2087. * @returns a new Color4 object
  2088. */
  2089. Color4.FromArray = function (array, offset) {
  2090. if (offset === void 0) { offset = 0; }
  2091. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2092. };
  2093. /**
  2094. * Creates a new Color3 from integer values (< 256)
  2095. * @param r defines the red component to read from (value between 0 and 255)
  2096. * @param g defines the green component to read from (value between 0 and 255)
  2097. * @param b defines the blue component to read from (value between 0 and 255)
  2098. * @param a defines the alpha component to read from (value between 0 and 255)
  2099. * @returns a new Color3 object
  2100. */
  2101. Color4.FromInts = function (r, g, b, a) {
  2102. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2103. };
  2104. /**
  2105. * Check the content of a given array and convert it to an array containing RGBA data
  2106. * If the original array was already containing count * 4 values then it is returned directly
  2107. * @param colors defines the array to check
  2108. * @param count defines the number of RGBA data to expect
  2109. * @returns an array containing count * 4 values (RGBA)
  2110. */
  2111. Color4.CheckColors4 = function (colors, count) {
  2112. // Check if color3 was used
  2113. if (colors.length === count * 3) {
  2114. var colors4 = [];
  2115. for (var index = 0; index < colors.length; index += 3) {
  2116. var newIndex = (index / 3) * 4;
  2117. colors4[newIndex] = colors[index];
  2118. colors4[newIndex + 1] = colors[index + 1];
  2119. colors4[newIndex + 2] = colors[index + 2];
  2120. colors4[newIndex + 3] = 1.0;
  2121. }
  2122. return colors4;
  2123. }
  2124. return colors;
  2125. };
  2126. return Color4;
  2127. }());
  2128. BABYLON.Color4 = Color4;
  2129. var Vector2 = /** @class */ (function () {
  2130. /**
  2131. * Creates a new Vector2 from the passed x and y coordinates.
  2132. */
  2133. function Vector2(x, y) {
  2134. this.x = x;
  2135. this.y = y;
  2136. }
  2137. /**
  2138. * Returns a string with the Vector2 coordinates.
  2139. */
  2140. Vector2.prototype.toString = function () {
  2141. return "{X: " + this.x + " Y:" + this.y + "}";
  2142. };
  2143. /**
  2144. * Returns the string "Vector2"
  2145. */
  2146. Vector2.prototype.getClassName = function () {
  2147. return "Vector2";
  2148. };
  2149. /**
  2150. * Returns the Vector2 hash code as a number.
  2151. */
  2152. Vector2.prototype.getHashCode = function () {
  2153. var hash = this.x || 0;
  2154. hash = (hash * 397) ^ (this.y || 0);
  2155. return hash;
  2156. };
  2157. // Operators
  2158. /**
  2159. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2160. * Returns the Vector2.
  2161. */
  2162. Vector2.prototype.toArray = function (array, index) {
  2163. if (index === void 0) { index = 0; }
  2164. array[index] = this.x;
  2165. array[index + 1] = this.y;
  2166. return this;
  2167. };
  2168. /**
  2169. * Returns a new array with 2 elements : the Vector2 coordinates.
  2170. */
  2171. Vector2.prototype.asArray = function () {
  2172. var result = new Array();
  2173. this.toArray(result, 0);
  2174. return result;
  2175. };
  2176. /**
  2177. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2178. * Returns the updated Vector2.
  2179. */
  2180. Vector2.prototype.copyFrom = function (source) {
  2181. this.x = source.x;
  2182. this.y = source.y;
  2183. return this;
  2184. };
  2185. /**
  2186. * Sets the Vector2 coordinates with the passed floats.
  2187. * Returns the updated Vector2.
  2188. */
  2189. Vector2.prototype.copyFromFloats = function (x, y) {
  2190. this.x = x;
  2191. this.y = y;
  2192. return this;
  2193. };
  2194. /**
  2195. * Sets the Vector2 coordinates with the passed floats.
  2196. * Returns the updated Vector2.
  2197. */
  2198. Vector2.prototype.set = function (x, y) {
  2199. return this.copyFromFloats(x, y);
  2200. };
  2201. /**
  2202. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2203. */
  2204. Vector2.prototype.add = function (otherVector) {
  2205. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2206. };
  2207. /**
  2208. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2209. * Returns the Vector2.
  2210. */
  2211. Vector2.prototype.addToRef = function (otherVector, result) {
  2212. result.x = this.x + otherVector.x;
  2213. result.y = this.y + otherVector.y;
  2214. return this;
  2215. };
  2216. /**
  2217. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2218. * Returns the updated Vector2.
  2219. */
  2220. Vector2.prototype.addInPlace = function (otherVector) {
  2221. this.x += otherVector.x;
  2222. this.y += otherVector.y;
  2223. return this;
  2224. };
  2225. /**
  2226. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2227. */
  2228. Vector2.prototype.addVector3 = function (otherVector) {
  2229. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2230. };
  2231. /**
  2232. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2233. */
  2234. Vector2.prototype.subtract = function (otherVector) {
  2235. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2236. };
  2237. /**
  2238. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2239. * Returns the Vector2.
  2240. */
  2241. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2242. result.x = this.x - otherVector.x;
  2243. result.y = this.y - otherVector.y;
  2244. return this;
  2245. };
  2246. /**
  2247. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2248. * Returns the updated Vector2.
  2249. */
  2250. Vector2.prototype.subtractInPlace = function (otherVector) {
  2251. this.x -= otherVector.x;
  2252. this.y -= otherVector.y;
  2253. return this;
  2254. };
  2255. /**
  2256. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2257. * Returns the updated Vector2.
  2258. */
  2259. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2260. this.x *= otherVector.x;
  2261. this.y *= otherVector.y;
  2262. return this;
  2263. };
  2264. /**
  2265. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2266. */
  2267. Vector2.prototype.multiply = function (otherVector) {
  2268. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2269. };
  2270. /**
  2271. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2272. * Returns the Vector2.
  2273. */
  2274. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2275. result.x = this.x * otherVector.x;
  2276. result.y = this.y * otherVector.y;
  2277. return this;
  2278. };
  2279. /**
  2280. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2281. */
  2282. Vector2.prototype.multiplyByFloats = function (x, y) {
  2283. return new Vector2(this.x * x, this.y * y);
  2284. };
  2285. /**
  2286. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2287. */
  2288. Vector2.prototype.divide = function (otherVector) {
  2289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2290. };
  2291. /**
  2292. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2293. * Returns the Vector2.
  2294. */
  2295. Vector2.prototype.divideToRef = function (otherVector, result) {
  2296. result.x = this.x / otherVector.x;
  2297. result.y = this.y / otherVector.y;
  2298. return this;
  2299. };
  2300. /**
  2301. * Divides the current Vector3 coordinates by the passed ones.
  2302. * Returns the updated Vector3.
  2303. */
  2304. Vector2.prototype.divideInPlace = function (otherVector) {
  2305. return this.divideToRef(otherVector, this);
  2306. };
  2307. /**
  2308. * Returns a new Vector2 with current Vector2 negated coordinates.
  2309. */
  2310. Vector2.prototype.negate = function () {
  2311. return new Vector2(-this.x, -this.y);
  2312. };
  2313. /**
  2314. * Multiply the Vector2 coordinates by scale.
  2315. * Returns the updated Vector2.
  2316. */
  2317. Vector2.prototype.scaleInPlace = function (scale) {
  2318. this.x *= scale;
  2319. this.y *= scale;
  2320. return this;
  2321. };
  2322. /**
  2323. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2324. */
  2325. Vector2.prototype.scale = function (scale) {
  2326. return new Vector2(this.x * scale, this.y * scale);
  2327. };
  2328. /**
  2329. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2330. */
  2331. Vector2.prototype.equals = function (otherVector) {
  2332. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2333. };
  2334. /**
  2335. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2336. */
  2337. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2338. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2339. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2340. };
  2341. // Properties
  2342. /**
  2343. * Returns the vector length (float).
  2344. */
  2345. Vector2.prototype.length = function () {
  2346. return Math.sqrt(this.x * this.x + this.y * this.y);
  2347. };
  2348. /**
  2349. * Returns the vector squared length (float);
  2350. */
  2351. Vector2.prototype.lengthSquared = function () {
  2352. return (this.x * this.x + this.y * this.y);
  2353. };
  2354. // Methods
  2355. /**
  2356. * Normalize the vector.
  2357. * Returns the updated Vector2.
  2358. */
  2359. Vector2.prototype.normalize = function () {
  2360. var len = this.length();
  2361. if (len === 0)
  2362. return this;
  2363. var num = 1.0 / len;
  2364. this.x *= num;
  2365. this.y *= num;
  2366. return this;
  2367. };
  2368. /**
  2369. * Returns a new Vector2 copied from the Vector2.
  2370. */
  2371. Vector2.prototype.clone = function () {
  2372. return new Vector2(this.x, this.y);
  2373. };
  2374. // Statics
  2375. /**
  2376. * Returns a new Vector2(0, 0)
  2377. */
  2378. Vector2.Zero = function () {
  2379. return new Vector2(0, 0);
  2380. };
  2381. /**
  2382. * Returns a new Vector2(1, 1)
  2383. */
  2384. Vector2.One = function () {
  2385. return new Vector2(1, 1);
  2386. };
  2387. /**
  2388. * Returns a new Vector2 set from the passed index element of the passed array.
  2389. */
  2390. Vector2.FromArray = function (array, offset) {
  2391. if (offset === void 0) { offset = 0; }
  2392. return new Vector2(array[offset], array[offset + 1]);
  2393. };
  2394. /**
  2395. * Sets "result" from the passed index element of the passed array.
  2396. */
  2397. Vector2.FromArrayToRef = function (array, offset, result) {
  2398. result.x = array[offset];
  2399. result.y = array[offset + 1];
  2400. };
  2401. /**
  2402. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2403. */
  2404. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2405. var squared = amount * amount;
  2406. var cubed = amount * squared;
  2407. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2408. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2409. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2410. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2411. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2412. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2413. return new Vector2(x, y);
  2414. };
  2415. /**
  2416. * 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".
  2417. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2418. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2419. */
  2420. Vector2.Clamp = function (value, min, max) {
  2421. var x = value.x;
  2422. x = (x > max.x) ? max.x : x;
  2423. x = (x < min.x) ? min.x : x;
  2424. var y = value.y;
  2425. y = (y > max.y) ? max.y : y;
  2426. y = (y < min.y) ? min.y : y;
  2427. return new Vector2(x, y);
  2428. };
  2429. /**
  2430. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2431. */
  2432. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2433. var squared = amount * amount;
  2434. var cubed = amount * squared;
  2435. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2436. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2437. var part3 = (cubed - (2.0 * squared)) + amount;
  2438. var part4 = cubed - squared;
  2439. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2440. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2441. return new Vector2(x, y);
  2442. };
  2443. /**
  2444. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2445. */
  2446. Vector2.Lerp = function (start, end, amount) {
  2447. var x = start.x + ((end.x - start.x) * amount);
  2448. var y = start.y + ((end.y - start.y) * amount);
  2449. return new Vector2(x, y);
  2450. };
  2451. /**
  2452. * Returns the dot product (float) of the vector "left" and the vector "right".
  2453. */
  2454. Vector2.Dot = function (left, right) {
  2455. return left.x * right.x + left.y * right.y;
  2456. };
  2457. /**
  2458. * Returns a new Vector2 equal to the normalized passed vector.
  2459. */
  2460. Vector2.Normalize = function (vector) {
  2461. var newVector = vector.clone();
  2462. newVector.normalize();
  2463. return newVector;
  2464. };
  2465. /**
  2466. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2467. */
  2468. Vector2.Minimize = function (left, right) {
  2469. var x = (left.x < right.x) ? left.x : right.x;
  2470. var y = (left.y < right.y) ? left.y : right.y;
  2471. return new Vector2(x, y);
  2472. };
  2473. /**
  2474. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2475. */
  2476. Vector2.Maximize = function (left, right) {
  2477. var x = (left.x > right.x) ? left.x : right.x;
  2478. var y = (left.y > right.y) ? left.y : right.y;
  2479. return new Vector2(x, y);
  2480. };
  2481. /**
  2482. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2483. */
  2484. Vector2.Transform = function (vector, transformation) {
  2485. var r = Vector2.Zero();
  2486. Vector2.TransformToRef(vector, transformation, r);
  2487. return r;
  2488. };
  2489. /**
  2490. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2491. */
  2492. Vector2.TransformToRef = function (vector, transformation, result) {
  2493. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2494. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2495. result.x = x;
  2496. result.y = y;
  2497. };
  2498. /**
  2499. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2500. */
  2501. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2502. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2503. var sign = a < 0 ? -1 : 1;
  2504. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2505. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2506. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2507. };
  2508. /**
  2509. * Returns the distance (float) between the vectors "value1" and "value2".
  2510. */
  2511. Vector2.Distance = function (value1, value2) {
  2512. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2513. };
  2514. /**
  2515. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2516. */
  2517. Vector2.DistanceSquared = function (value1, value2) {
  2518. var x = value1.x - value2.x;
  2519. var y = value1.y - value2.y;
  2520. return (x * x) + (y * y);
  2521. };
  2522. /**
  2523. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2524. */
  2525. Vector2.Center = function (value1, value2) {
  2526. var center = value1.add(value2);
  2527. center.scaleInPlace(0.5);
  2528. return center;
  2529. };
  2530. /**
  2531. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2532. */
  2533. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2534. var l2 = Vector2.DistanceSquared(segA, segB);
  2535. if (l2 === 0.0) {
  2536. return Vector2.Distance(p, segA);
  2537. }
  2538. var v = segB.subtract(segA);
  2539. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2540. var proj = segA.add(v.multiplyByFloats(t, t));
  2541. return Vector2.Distance(p, proj);
  2542. };
  2543. return Vector2;
  2544. }());
  2545. BABYLON.Vector2 = Vector2;
  2546. /**
  2547. * Classed used to store (x,y,z) vector representation
  2548. * A Vector3 is the main object used in 3D geometry
  2549. * It can represent etiher the coordinates of a point the space, either a direction
  2550. * Reminder: Babylon.js uses a left handed forward facing system
  2551. */
  2552. var Vector3 = /** @class */ (function () {
  2553. /**
  2554. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2555. * @param x defines the first coordinates (on X axis)
  2556. * @param y defines the second coordinates (on Y axis)
  2557. * @param z defines the third coordinates (on Z axis)
  2558. */
  2559. function Vector3(
  2560. /**
  2561. * Defines the first coordinates (on X axis)
  2562. */
  2563. x,
  2564. /**
  2565. * Defines the second coordinates (on Y axis)
  2566. */
  2567. y,
  2568. /**
  2569. * Defines the third coordinates (on Z axis)
  2570. */
  2571. z) {
  2572. this.x = x;
  2573. this.y = y;
  2574. this.z = z;
  2575. }
  2576. /**
  2577. * Creates a string representation of the Vector3
  2578. * @returns a string with the Vector3 coordinates.
  2579. */
  2580. Vector3.prototype.toString = function () {
  2581. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2582. };
  2583. /**
  2584. * Gets the class name
  2585. * @returns the string "Vector3"
  2586. */
  2587. Vector3.prototype.getClassName = function () {
  2588. return "Vector3";
  2589. };
  2590. /**
  2591. * Creates the Vector3 hash code
  2592. * @returns a number which tends to be unique between Vector3 instances
  2593. */
  2594. Vector3.prototype.getHashCode = function () {
  2595. var hash = this.x || 0;
  2596. hash = (hash * 397) ^ (this.y || 0);
  2597. hash = (hash * 397) ^ (this.z || 0);
  2598. return hash;
  2599. };
  2600. // Operators
  2601. /**
  2602. * Creates an array containing three elements : the coordinates of the Vector3
  2603. * @returns a new array of numbers
  2604. */
  2605. Vector3.prototype.asArray = function () {
  2606. var result = [];
  2607. this.toArray(result, 0);
  2608. return result;
  2609. };
  2610. /**
  2611. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2612. * @param array defines the destination array
  2613. * @param index defines the offset in the destination array
  2614. * @returns the current Vector3
  2615. */
  2616. Vector3.prototype.toArray = function (array, index) {
  2617. if (index === void 0) { index = 0; }
  2618. array[index] = this.x;
  2619. array[index + 1] = this.y;
  2620. array[index + 2] = this.z;
  2621. return this;
  2622. };
  2623. /**
  2624. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2625. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2626. */
  2627. Vector3.prototype.toQuaternion = function () {
  2628. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2629. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2630. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2631. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2632. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2633. var cosy = Math.cos(this.y * 0.5);
  2634. var siny = Math.sin(this.y * 0.5);
  2635. result.x = coszMinusx * siny;
  2636. result.y = -sinzMinusx * siny;
  2637. result.z = sinxPlusz * cosy;
  2638. result.w = cosxPlusz * cosy;
  2639. return result;
  2640. };
  2641. /**
  2642. * Adds the passed vector to the current Vector3
  2643. * @param otherVector defines the second operand
  2644. * @returns the current updated Vector3
  2645. */
  2646. Vector3.prototype.addInPlace = function (otherVector) {
  2647. this.x += otherVector.x;
  2648. this.y += otherVector.y;
  2649. this.z += otherVector.z;
  2650. return this;
  2651. };
  2652. /**
  2653. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2654. * @param otherVector defines the second operand
  2655. * @returns the resulting Vector3
  2656. */
  2657. Vector3.prototype.add = function (otherVector) {
  2658. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2659. };
  2660. /**
  2661. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2662. * @param otherVector defines the second operand
  2663. * @param result defines the Vector3 object where to store the result
  2664. * @returns the current Vector3
  2665. */
  2666. Vector3.prototype.addToRef = function (otherVector, result) {
  2667. result.x = this.x + otherVector.x;
  2668. result.y = this.y + otherVector.y;
  2669. result.z = this.z + otherVector.z;
  2670. return this;
  2671. };
  2672. /**
  2673. * Subtract the passed vector from the current Vector3
  2674. * @param otherVector defines the second operand
  2675. * @returns the current updated Vector3
  2676. */
  2677. Vector3.prototype.subtractInPlace = function (otherVector) {
  2678. this.x -= otherVector.x;
  2679. this.y -= otherVector.y;
  2680. this.z -= otherVector.z;
  2681. return this;
  2682. };
  2683. /**
  2684. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2685. * @param otherVector defines the second operand
  2686. * @returns the resulting Vector3
  2687. */
  2688. Vector3.prototype.subtract = function (otherVector) {
  2689. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2690. };
  2691. /**
  2692. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2693. * @param otherVector defines the second operand
  2694. * @param result defines the Vector3 object where to store the result
  2695. * @returns the current Vector3
  2696. */
  2697. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2698. result.x = this.x - otherVector.x;
  2699. result.y = this.y - otherVector.y;
  2700. result.z = this.z - otherVector.z;
  2701. return this;
  2702. };
  2703. /**
  2704. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2705. * @param x defines the x coordinate of the operand
  2706. * @param y defines the y coordinate of the operand
  2707. * @param z defines the z coordinate of the operand
  2708. * @returns the resulting Vector3
  2709. */
  2710. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2711. return new Vector3(this.x - x, this.y - y, this.z - z);
  2712. };
  2713. /**
  2714. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2715. * @param x defines the x coordinate of the operand
  2716. * @param y defines the y coordinate of the operand
  2717. * @param z defines the z coordinate of the operand
  2718. * @param result defines the Vector3 object where to store the result
  2719. * @returns the current Vector3
  2720. */
  2721. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2722. result.x = this.x - x;
  2723. result.y = this.y - y;
  2724. result.z = this.z - z;
  2725. return this;
  2726. };
  2727. /**
  2728. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2729. * @returns a new Vector3
  2730. */
  2731. Vector3.prototype.negate = function () {
  2732. return new Vector3(-this.x, -this.y, -this.z);
  2733. };
  2734. /**
  2735. * Multiplies the Vector3 coordinates by the float "scale"
  2736. * @param scale defines the multiplier factor
  2737. * @returns the current updated Vector3
  2738. */
  2739. Vector3.prototype.scaleInPlace = function (scale) {
  2740. this.x *= scale;
  2741. this.y *= scale;
  2742. this.z *= scale;
  2743. return this;
  2744. };
  2745. /**
  2746. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2747. * @param scale defines the multiplier factor
  2748. * @returns a new Vector3
  2749. */
  2750. Vector3.prototype.scale = function (scale) {
  2751. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2752. };
  2753. /**
  2754. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2755. * @param scale defines the multiplier factor
  2756. * @param result defines the Vector3 object where to store the result
  2757. * @returns the current Vector3
  2758. */
  2759. Vector3.prototype.scaleToRef = function (scale, result) {
  2760. result.x = this.x * scale;
  2761. result.y = this.y * scale;
  2762. result.z = this.z * scale;
  2763. return this;
  2764. };
  2765. /**
  2766. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2767. * @param otherVector defines the second operand
  2768. * @returns true if both vectors are equals
  2769. */
  2770. Vector3.prototype.equals = function (otherVector) {
  2771. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2772. };
  2773. /**
  2774. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2775. * @param otherVector defines the second operand
  2776. * @param epsilon defines the minimal distance to define values as equals
  2777. * @returns true if both vectors are distant less than epsilon
  2778. */
  2779. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2780. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2781. 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);
  2782. };
  2783. /**
  2784. * Returns true if the current Vector3 coordinates equals the passed floats
  2785. * @param x defines the x coordinate of the operand
  2786. * @param y defines the y coordinate of the operand
  2787. * @param z defines the z coordinate of the operand
  2788. * @returns true if both vectors are equals
  2789. */
  2790. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2791. return this.x === x && this.y === y && this.z === z;
  2792. };
  2793. /**
  2794. * Multiplies the current Vector3 coordinates by the passed ones
  2795. * @param otherVector defines the second operand
  2796. * @returns the current updated Vector3
  2797. */
  2798. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2799. this.x *= otherVector.x;
  2800. this.y *= otherVector.y;
  2801. this.z *= otherVector.z;
  2802. return this;
  2803. };
  2804. /**
  2805. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2806. * @param otherVector defines the second operand
  2807. * @returns the new Vector3
  2808. */
  2809. Vector3.prototype.multiply = function (otherVector) {
  2810. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2811. };
  2812. /**
  2813. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2814. * @param otherVector defines the second operand
  2815. * @param result defines the Vector3 object where to store the result
  2816. * @returns the current Vector3
  2817. */
  2818. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2819. result.x = this.x * otherVector.x;
  2820. result.y = this.y * otherVector.y;
  2821. result.z = this.z * otherVector.z;
  2822. return this;
  2823. };
  2824. /**
  2825. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by 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 the new Vector3
  2830. */
  2831. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2832. return new Vector3(this.x * x, this.y * y, this.z * z);
  2833. };
  2834. /**
  2835. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2836. * @param otherVector defines the second operand
  2837. * @returns the new Vector3
  2838. */
  2839. Vector3.prototype.divide = function (otherVector) {
  2840. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2841. };
  2842. /**
  2843. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2844. * @param otherVector defines the second operand
  2845. * @param result defines the Vector3 object where to store the result
  2846. * @returns the current Vector3
  2847. */
  2848. Vector3.prototype.divideToRef = function (otherVector, result) {
  2849. result.x = this.x / otherVector.x;
  2850. result.y = this.y / otherVector.y;
  2851. result.z = this.z / otherVector.z;
  2852. return this;
  2853. };
  2854. /**
  2855. * Divides the current Vector3 coordinates by the passed ones.
  2856. * @param otherVector defines the second operand
  2857. * @returns the current updated Vector3
  2858. */
  2859. Vector3.prototype.divideInPlace = function (otherVector) {
  2860. return this.divideToRef(otherVector, this);
  2861. };
  2862. /**
  2863. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2864. * @param other defines the second operand
  2865. * @returns the current updated Vector3
  2866. */
  2867. Vector3.prototype.minimizeInPlace = function (other) {
  2868. if (other.x < this.x)
  2869. this.x = other.x;
  2870. if (other.y < this.y)
  2871. this.y = other.y;
  2872. if (other.z < this.z)
  2873. this.z = other.z;
  2874. return this;
  2875. };
  2876. /**
  2877. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2878. * @param other defines the second operand
  2879. * @returns the current updated Vector3
  2880. */
  2881. Vector3.prototype.maximizeInPlace = function (other) {
  2882. if (other.x > this.x)
  2883. this.x = other.x;
  2884. if (other.y > this.y)
  2885. this.y = other.y;
  2886. if (other.z > this.z)
  2887. this.z = other.z;
  2888. return this;
  2889. };
  2890. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2891. /**
  2892. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2893. */
  2894. get: function () {
  2895. var absX = Math.abs(this.x);
  2896. var absY = Math.abs(this.y);
  2897. if (absX !== absY) {
  2898. return true;
  2899. }
  2900. var absZ = Math.abs(this.z);
  2901. if (absX !== absZ) {
  2902. return true;
  2903. }
  2904. if (absY !== absZ) {
  2905. return true;
  2906. }
  2907. return false;
  2908. },
  2909. enumerable: true,
  2910. configurable: true
  2911. });
  2912. // Properties
  2913. /**
  2914. * Gets the length of the Vector3
  2915. * @returns the length of the Vecto3
  2916. */
  2917. Vector3.prototype.length = function () {
  2918. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2919. };
  2920. /**
  2921. * Gets the squared length of the Vector3
  2922. * @returns squared length of the Vector3
  2923. */
  2924. Vector3.prototype.lengthSquared = function () {
  2925. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2926. };
  2927. /**
  2928. * Normalize the current Vector3.
  2929. * Please note that this is an in place operation.
  2930. * @returns the current updated Vector3
  2931. */
  2932. Vector3.prototype.normalize = function () {
  2933. var len = this.length();
  2934. if (len === 0 || len === 1.0)
  2935. return this;
  2936. var num = 1.0 / len;
  2937. this.x *= num;
  2938. this.y *= num;
  2939. this.z *= num;
  2940. return this;
  2941. };
  2942. /**
  2943. * Normalize the current Vector3 to a new vector
  2944. * @returns the new Vector3
  2945. */
  2946. Vector3.prototype.normalizeToNew = function () {
  2947. var normalized = new Vector3(0, 0, 0);
  2948. this.normalizeToRef(normalized);
  2949. return normalized;
  2950. };
  2951. /**
  2952. * Normalize the current Vector3 to the reference
  2953. * @param reference define the Vector3 to update
  2954. * @returns the updated Vector3
  2955. */
  2956. Vector3.prototype.normalizeToRef = function (reference) {
  2957. var len = this.length();
  2958. if (len === 0 || len === 1.0) {
  2959. reference.set(this.x, this.y, this.z);
  2960. return reference;
  2961. }
  2962. var scale = 1.0 / len;
  2963. this.scaleToRef(scale, reference);
  2964. return reference;
  2965. };
  2966. /**
  2967. * Creates a new Vector3 copied from the current Vector3
  2968. * @returns the new Vector3
  2969. */
  2970. Vector3.prototype.clone = function () {
  2971. return new Vector3(this.x, this.y, this.z);
  2972. };
  2973. /**
  2974. * Copies the passed vector coordinates to the current Vector3 ones
  2975. * @param source defines the source Vector3
  2976. * @returns the current updated Vector3
  2977. */
  2978. Vector3.prototype.copyFrom = function (source) {
  2979. this.x = source.x;
  2980. this.y = source.y;
  2981. this.z = source.z;
  2982. return this;
  2983. };
  2984. /**
  2985. * Copies the passed floats to the current Vector3 coordinates
  2986. * @param x defines the x coordinate of the operand
  2987. * @param y defines the y coordinate of the operand
  2988. * @param z defines the z coordinate of the operand
  2989. * @returns the current updated Vector3
  2990. */
  2991. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2992. this.x = x;
  2993. this.y = y;
  2994. this.z = z;
  2995. return this;
  2996. };
  2997. /**
  2998. * Copies the passed floats to the current Vector3 coordinates
  2999. * @param x defines the x coordinate of the operand
  3000. * @param y defines the y coordinate of the operand
  3001. * @param z defines the z coordinate of the operand
  3002. * @returns the current updated Vector3
  3003. */
  3004. Vector3.prototype.set = function (x, y, z) {
  3005. return this.copyFromFloats(x, y, z);
  3006. };
  3007. // Statics
  3008. /**
  3009. * Get the clip factor between two vectors
  3010. * @param vector0 defines the first operand
  3011. * @param vector1 defines the second operand
  3012. * @param axis defines the axis to use
  3013. * @param size defines the size along the axis
  3014. * @returns the clip factor
  3015. */
  3016. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3017. var d0 = Vector3.Dot(vector0, axis) - size;
  3018. var d1 = Vector3.Dot(vector1, axis) - size;
  3019. var s = d0 / (d0 - d1);
  3020. return s;
  3021. };
  3022. /**
  3023. * Get angle between two vectors
  3024. * @param vector0 angle between vector0 and vector1
  3025. * @param vector1 angle between vector0 and vector1
  3026. * @param normal direction of the normal
  3027. * @return the angle between vector0 and vector1
  3028. */
  3029. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3030. var v0 = vector0.clone().normalize();
  3031. var v1 = vector1.clone().normalize();
  3032. var dot = Vector3.Dot(v0, v1);
  3033. var n = Vector3.Cross(v0, v1);
  3034. if (Vector3.Dot(n, normal) > 0) {
  3035. return Math.acos(dot);
  3036. }
  3037. return -Math.acos(dot);
  3038. };
  3039. /**
  3040. * Returns a new Vector3 set from the index "offset" of the passed array
  3041. * @param array defines the source array
  3042. * @param offset defines the offset in the source array
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.FromArray = function (array, offset) {
  3046. if (!offset) {
  3047. offset = 0;
  3048. }
  3049. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3050. };
  3051. /**
  3052. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3053. * This function is deprecated. Use FromArray instead
  3054. * @param array defines the source array
  3055. * @param offset defines the offset in the source array
  3056. * @returns the new Vector3
  3057. */
  3058. Vector3.FromFloatArray = function (array, offset) {
  3059. return Vector3.FromArray(array, offset);
  3060. };
  3061. /**
  3062. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3063. * @param array defines the source array
  3064. * @param offset defines the offset in the source array
  3065. * @param result defines the Vector3 where to store the result
  3066. */
  3067. Vector3.FromArrayToRef = function (array, offset, result) {
  3068. result.x = array[offset];
  3069. result.y = array[offset + 1];
  3070. result.z = array[offset + 2];
  3071. };
  3072. /**
  3073. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3074. * This function is deprecated. Use FromArrayToRef instead.
  3075. * @param array defines the source array
  3076. * @param offset defines the offset in the source array
  3077. * @param result defines the Vector3 where to store the result
  3078. */
  3079. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3080. return Vector3.FromArrayToRef(array, offset, result);
  3081. };
  3082. /**
  3083. * Sets the passed vector "result" with the passed floats.
  3084. * @param x defines the x coordinate of the source
  3085. * @param y defines the y coordinate of the source
  3086. * @param z defines the z coordinate of the source
  3087. * @param result defines the Vector3 where to store the result
  3088. */
  3089. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3090. result.x = x;
  3091. result.y = y;
  3092. result.z = z;
  3093. };
  3094. /**
  3095. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3096. * @returns a new empty Vector3
  3097. */
  3098. Vector3.Zero = function () {
  3099. return new Vector3(0.0, 0.0, 0.0);
  3100. };
  3101. /**
  3102. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3103. * @returns a new unit Vector3
  3104. */
  3105. Vector3.One = function () {
  3106. return new Vector3(1.0, 1.0, 1.0);
  3107. };
  3108. /**
  3109. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3110. * @returns a new up Vector3
  3111. */
  3112. Vector3.Up = function () {
  3113. return new Vector3(0.0, 1.0, 0.0);
  3114. };
  3115. /**
  3116. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3117. * @returns a new forward Vector3
  3118. */
  3119. Vector3.Forward = function () {
  3120. return new Vector3(0.0, 0.0, 1.0);
  3121. };
  3122. /**
  3123. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3124. * @returns a new right Vector3
  3125. */
  3126. Vector3.Right = function () {
  3127. return new Vector3(1.0, 0.0, 0.0);
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3131. * @returns a new left Vector3
  3132. */
  3133. Vector3.Left = function () {
  3134. return new Vector3(-1.0, 0.0, 0.0);
  3135. };
  3136. /**
  3137. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3138. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3139. * @param vector defines the Vector3 to transform
  3140. * @param transformation defines the transformation matrix
  3141. * @returns the transformed Vector3
  3142. */
  3143. Vector3.TransformCoordinates = function (vector, transformation) {
  3144. var result = Vector3.Zero();
  3145. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3146. return result;
  3147. };
  3148. /**
  3149. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3150. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3151. * @param vector defines the Vector3 to transform
  3152. * @param transformation defines the transformation matrix
  3153. * @param result defines the Vector3 where to store the result
  3154. */
  3155. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3156. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3157. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3158. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3159. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3160. result.x = x / w;
  3161. result.y = y / w;
  3162. result.z = z / w;
  3163. };
  3164. /**
  3165. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3166. * This method computes tranformed coordinates only, not transformed direction vectors
  3167. * @param x define the x coordinate of the source vector
  3168. * @param y define the y coordinate of the source vector
  3169. * @param z define the z coordinate of the source vector
  3170. * @param transformation defines the transformation matrix
  3171. * @param result defines the Vector3 where to store the result
  3172. */
  3173. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3174. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3175. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3176. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3177. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3178. result.x = rx / rw;
  3179. result.y = ry / rw;
  3180. result.z = rz / rw;
  3181. };
  3182. /**
  3183. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3184. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3185. * @param vector defines the Vector3 to transform
  3186. * @param transformation defines the transformation matrix
  3187. * @returns the new Vector3
  3188. */
  3189. Vector3.TransformNormal = function (vector, transformation) {
  3190. var result = Vector3.Zero();
  3191. Vector3.TransformNormalToRef(vector, transformation, result);
  3192. return result;
  3193. };
  3194. /**
  3195. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3196. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3197. * @param vector defines the Vector3 to transform
  3198. * @param transformation defines the transformation matrix
  3199. * @param result defines the Vector3 where to store the result
  3200. */
  3201. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3202. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3203. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3204. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3205. result.x = x;
  3206. result.y = y;
  3207. result.z = z;
  3208. };
  3209. /**
  3210. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3211. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3212. * @param x define the x coordinate of the source vector
  3213. * @param y define the y coordinate of the source vector
  3214. * @param z define the z coordinate of the source vector
  3215. * @param transformation defines the transformation matrix
  3216. * @param result defines the Vector3 where to store the result
  3217. */
  3218. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3219. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3220. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3221. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3222. };
  3223. /**
  3224. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3225. * @param value1 defines the first control point
  3226. * @param value2 defines the second control point
  3227. * @param value3 defines the third control point
  3228. * @param value4 defines the fourth control point
  3229. * @param amount defines the amount on the spline to use
  3230. * @returns the new Vector3
  3231. */
  3232. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3233. var squared = amount * amount;
  3234. var cubed = amount * squared;
  3235. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3236. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3237. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3238. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3239. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3240. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3241. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3242. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3243. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3244. return new Vector3(x, y, z);
  3245. };
  3246. /**
  3247. * 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"
  3248. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3249. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3250. * @param value defines the current value
  3251. * @param min defines the lower range value
  3252. * @param max defines the upper range value
  3253. * @returns the new Vector3
  3254. */
  3255. Vector3.Clamp = function (value, min, max) {
  3256. var x = value.x;
  3257. x = (x > max.x) ? max.x : x;
  3258. x = (x < min.x) ? min.x : x;
  3259. var y = value.y;
  3260. y = (y > max.y) ? max.y : y;
  3261. y = (y < min.y) ? min.y : y;
  3262. var z = value.z;
  3263. z = (z > max.z) ? max.z : z;
  3264. z = (z < min.z) ? min.z : z;
  3265. return new Vector3(x, y, z);
  3266. };
  3267. /**
  3268. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3269. * @param value1 defines the first control point
  3270. * @param tangent1 defines the first tangent vector
  3271. * @param value2 defines the second control point
  3272. * @param tangent2 defines the second tangent vector
  3273. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3274. * @returns the new Vector3
  3275. */
  3276. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3277. var squared = amount * amount;
  3278. var cubed = amount * squared;
  3279. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3280. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3281. var part3 = (cubed - (2.0 * squared)) + amount;
  3282. var part4 = cubed - squared;
  3283. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3284. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3285. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3286. return new Vector3(x, y, z);
  3287. };
  3288. /**
  3289. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3290. * @param start defines the start value
  3291. * @param end defines the end value
  3292. * @param amount max defines amount between both (between 0 and 1)
  3293. * @returns the new Vector3
  3294. */
  3295. Vector3.Lerp = function (start, end, amount) {
  3296. var result = new Vector3(0, 0, 0);
  3297. Vector3.LerpToRef(start, end, amount, result);
  3298. return result;
  3299. };
  3300. /**
  3301. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3302. * @param start defines the start value
  3303. * @param end defines the end value
  3304. * @param amount max defines amount between both (between 0 and 1)
  3305. * @param result defines the Vector3 where to store the result
  3306. */
  3307. Vector3.LerpToRef = function (start, end, amount, result) {
  3308. result.x = start.x + ((end.x - start.x) * amount);
  3309. result.y = start.y + ((end.y - start.y) * amount);
  3310. result.z = start.z + ((end.z - start.z) * amount);
  3311. };
  3312. /**
  3313. * Returns the dot product (float) between the vectors "left" and "right"
  3314. * @param left defines the left operand
  3315. * @param right defines the right operand
  3316. * @returns the dot product
  3317. */
  3318. Vector3.Dot = function (left, right) {
  3319. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3320. };
  3321. /**
  3322. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3323. * The cross product is then orthogonal to both "left" and "right"
  3324. * @param left defines the left operand
  3325. * @param right defines the right operand
  3326. * @returns the cross product
  3327. */
  3328. Vector3.Cross = function (left, right) {
  3329. var result = Vector3.Zero();
  3330. Vector3.CrossToRef(left, right, result);
  3331. return result;
  3332. };
  3333. /**
  3334. * Sets the passed vector "result" with the cross product of "left" and "right"
  3335. * The cross product is then orthogonal to both "left" and "right"
  3336. * @param left defines the left operand
  3337. * @param right defines the right operand
  3338. * @param result defines the Vector3 where to store the result
  3339. */
  3340. Vector3.CrossToRef = function (left, right, result) {
  3341. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3342. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3343. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3344. result.copyFrom(MathTmp.Vector3[0]);
  3345. };
  3346. /**
  3347. * Returns a new Vector3 as the normalization of the passed vector
  3348. * @param vector defines the Vector3 to normalize
  3349. * @returns the new Vector3
  3350. */
  3351. Vector3.Normalize = function (vector) {
  3352. var result = Vector3.Zero();
  3353. Vector3.NormalizeToRef(vector, result);
  3354. return result;
  3355. };
  3356. /**
  3357. * Sets the passed vector "result" with the normalization of the passed first vector
  3358. * @param vector defines the Vector3 to normalize
  3359. * @param result defines the Vector3 where to store the result
  3360. */
  3361. Vector3.NormalizeToRef = function (vector, result) {
  3362. result.copyFrom(vector);
  3363. result.normalize();
  3364. };
  3365. /**
  3366. * Project a Vector3 onto screen space
  3367. * @param vector defines the Vector3 to project
  3368. * @param world defines the world matrix to use
  3369. * @param transform defines the transform (view x projection) matrix to use
  3370. * @param viewport defines the screen viewport to use
  3371. * @returns the new Vector3
  3372. */
  3373. Vector3.Project = function (vector, world, transform, viewport) {
  3374. var cw = viewport.width;
  3375. var ch = viewport.height;
  3376. var cx = viewport.x;
  3377. var cy = viewport.y;
  3378. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3379. 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);
  3380. var matrix = MathTmp.Matrix[0];
  3381. world.multiplyToRef(transform, matrix);
  3382. matrix.multiplyToRef(viewportMatrix, matrix);
  3383. return Vector3.TransformCoordinates(vector, matrix);
  3384. };
  3385. /**
  3386. * Unproject from screen space to object space
  3387. * @param source defines the screen space Vector3 to use
  3388. * @param viewportWidth defines the current width of the viewport
  3389. * @param viewportHeight defines the current height of the viewport
  3390. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3391. * @param transform defines the transform (view x projection) matrix to use
  3392. * @returns the new Vector3
  3393. */
  3394. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3395. var matrix = MathTmp.Matrix[0];
  3396. world.multiplyToRef(transform, matrix);
  3397. matrix.invert();
  3398. source.x = source.x / viewportWidth * 2 - 1;
  3399. source.y = -(source.y / viewportHeight * 2 - 1);
  3400. var vector = Vector3.TransformCoordinates(source, matrix);
  3401. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3402. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3403. vector = vector.scale(1.0 / num);
  3404. }
  3405. return vector;
  3406. };
  3407. /**
  3408. * Unproject from screen space to object space
  3409. * @param source defines the screen space Vector3 to use
  3410. * @param viewportWidth defines the current width of the viewport
  3411. * @param viewportHeight defines the current height of the viewport
  3412. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3413. * @param view defines the view matrix to use
  3414. * @param projection defines the projection matrix to use
  3415. * @returns the new Vector3
  3416. */
  3417. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3418. var result = Vector3.Zero();
  3419. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3420. return result;
  3421. };
  3422. /**
  3423. * Unproject from screen space to object space
  3424. * @param source defines the screen space Vector3 to use
  3425. * @param viewportWidth defines the current width of the viewport
  3426. * @param viewportHeight defines the current height of the viewport
  3427. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3428. * @param view defines the view matrix to use
  3429. * @param projection defines the projection matrix to use
  3430. * @param result defines the Vector3 where to store the result
  3431. */
  3432. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3433. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3434. };
  3435. /**
  3436. * Unproject from screen space to object space
  3437. * @param sourceX defines the screen space x coordinate to use
  3438. * @param sourceY defines the screen space y coordinate to use
  3439. * @param sourceZ defines the screen space z coordinate to use
  3440. * @param viewportWidth defines the current width of the viewport
  3441. * @param viewportHeight defines the current height of the viewport
  3442. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3443. * @param view defines the view matrix to use
  3444. * @param projection defines the projection matrix to use
  3445. * @param result defines the Vector3 where to store the result
  3446. */
  3447. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3448. var matrix = MathTmp.Matrix[0];
  3449. world.multiplyToRef(view, matrix);
  3450. matrix.multiplyToRef(projection, matrix);
  3451. matrix.invert();
  3452. var screenSource = MathTmp.Vector3[0];
  3453. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3454. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3455. screenSource.z = 2 * sourceZ - 1.0;
  3456. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3457. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3458. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3459. result.scaleInPlace(1.0 / num);
  3460. }
  3461. };
  3462. /**
  3463. * Gets the minimal coordinate values between two Vector3
  3464. * @param left defines the first operand
  3465. * @param right defines the second operand
  3466. * @returns the new Vector3
  3467. */
  3468. Vector3.Minimize = function (left, right) {
  3469. var min = left.clone();
  3470. min.minimizeInPlace(right);
  3471. return min;
  3472. };
  3473. /**
  3474. * Gets the maximal coordinate values between two Vector3
  3475. * @param left defines the first operand
  3476. * @param right defines the second operand
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Maximize = function (left, right) {
  3480. var max = left.clone();
  3481. max.maximizeInPlace(right);
  3482. return max;
  3483. };
  3484. /**
  3485. * Returns the distance between the vectors "value1" and "value2"
  3486. * @param value1 defines the first operand
  3487. * @param value2 defines the second operand
  3488. * @returns the distance
  3489. */
  3490. Vector3.Distance = function (value1, value2) {
  3491. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3492. };
  3493. /**
  3494. * Returns the squared distance between the vectors "value1" and "value2"
  3495. * @param value1 defines the first operand
  3496. * @param value2 defines the second operand
  3497. * @returns the squared distance
  3498. */
  3499. Vector3.DistanceSquared = function (value1, value2) {
  3500. var x = value1.x - value2.x;
  3501. var y = value1.y - value2.y;
  3502. var z = value1.z - value2.z;
  3503. return (x * x) + (y * y) + (z * z);
  3504. };
  3505. /**
  3506. * Returns a new Vector3 located at the center between "value1" and "value2"
  3507. * @param value1 defines the first operand
  3508. * @param value2 defines the second operand
  3509. * @returns the new Vector3
  3510. */
  3511. Vector3.Center = function (value1, value2) {
  3512. var center = value1.add(value2);
  3513. center.scaleInPlace(0.5);
  3514. return center;
  3515. };
  3516. /**
  3517. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3518. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3519. * to something in order to rotate it from its local system to the given target system
  3520. * Note: axis1, axis2 and axis3 are normalized during this operation
  3521. * @param axis1 defines the first axis
  3522. * @param axis2 defines the second axis
  3523. * @param axis3 defines the third axis
  3524. * @returns a new Vector3
  3525. */
  3526. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3527. var rotation = Vector3.Zero();
  3528. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3529. return rotation;
  3530. };
  3531. /**
  3532. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3533. * @param axis1 defines the first axis
  3534. * @param axis2 defines the second axis
  3535. * @param axis3 defines the third axis
  3536. * @param ref defines the Vector3 where to store the result
  3537. */
  3538. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3539. var quat = MathTmp.Quaternion[0];
  3540. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3541. quat.toEulerAnglesToRef(ref);
  3542. };
  3543. return Vector3;
  3544. }());
  3545. BABYLON.Vector3 = Vector3;
  3546. //Vector4 class created for EulerAngle class conversion to Quaternion
  3547. var Vector4 = /** @class */ (function () {
  3548. /**
  3549. * Creates a Vector4 object from the passed floats.
  3550. */
  3551. function Vector4(x, y, z, w) {
  3552. this.x = x;
  3553. this.y = y;
  3554. this.z = z;
  3555. this.w = w;
  3556. }
  3557. /**
  3558. * Returns the string with the Vector4 coordinates.
  3559. */
  3560. Vector4.prototype.toString = function () {
  3561. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3562. };
  3563. /**
  3564. * Returns the string "Vector4".
  3565. */
  3566. Vector4.prototype.getClassName = function () {
  3567. return "Vector4";
  3568. };
  3569. /**
  3570. * Returns the Vector4 hash code.
  3571. */
  3572. Vector4.prototype.getHashCode = function () {
  3573. var hash = this.x || 0;
  3574. hash = (hash * 397) ^ (this.y || 0);
  3575. hash = (hash * 397) ^ (this.z || 0);
  3576. hash = (hash * 397) ^ (this.w || 0);
  3577. return hash;
  3578. };
  3579. // Operators
  3580. /**
  3581. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3582. */
  3583. Vector4.prototype.asArray = function () {
  3584. var result = new Array();
  3585. this.toArray(result, 0);
  3586. return result;
  3587. };
  3588. /**
  3589. * Populates the passed array from the passed index with the Vector4 coordinates.
  3590. * Returns the Vector4.
  3591. */
  3592. Vector4.prototype.toArray = function (array, index) {
  3593. if (index === undefined) {
  3594. index = 0;
  3595. }
  3596. array[index] = this.x;
  3597. array[index + 1] = this.y;
  3598. array[index + 2] = this.z;
  3599. array[index + 3] = this.w;
  3600. return this;
  3601. };
  3602. /**
  3603. * Adds the passed vector to the current Vector4.
  3604. * Returns the updated Vector4.
  3605. */
  3606. Vector4.prototype.addInPlace = function (otherVector) {
  3607. this.x += otherVector.x;
  3608. this.y += otherVector.y;
  3609. this.z += otherVector.z;
  3610. this.w += otherVector.w;
  3611. return this;
  3612. };
  3613. /**
  3614. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3615. */
  3616. Vector4.prototype.add = function (otherVector) {
  3617. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3618. };
  3619. /**
  3620. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3621. * Returns the current Vector4.
  3622. */
  3623. Vector4.prototype.addToRef = function (otherVector, result) {
  3624. result.x = this.x + otherVector.x;
  3625. result.y = this.y + otherVector.y;
  3626. result.z = this.z + otherVector.z;
  3627. result.w = this.w + otherVector.w;
  3628. return this;
  3629. };
  3630. /**
  3631. * Subtract in place the passed vector from the current Vector4.
  3632. * Returns the updated Vector4.
  3633. */
  3634. Vector4.prototype.subtractInPlace = function (otherVector) {
  3635. this.x -= otherVector.x;
  3636. this.y -= otherVector.y;
  3637. this.z -= otherVector.z;
  3638. this.w -= otherVector.w;
  3639. return this;
  3640. };
  3641. /**
  3642. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3643. */
  3644. Vector4.prototype.subtract = function (otherVector) {
  3645. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3646. };
  3647. /**
  3648. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3649. * Returns the current Vector4.
  3650. */
  3651. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3652. result.x = this.x - otherVector.x;
  3653. result.y = this.y - otherVector.y;
  3654. result.z = this.z - otherVector.z;
  3655. result.w = this.w - otherVector.w;
  3656. return this;
  3657. };
  3658. /**
  3659. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3660. */
  3661. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3662. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3663. };
  3664. /**
  3665. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3666. * Returns the current Vector4.
  3667. */
  3668. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3669. result.x = this.x - x;
  3670. result.y = this.y - y;
  3671. result.z = this.z - z;
  3672. result.w = this.w - w;
  3673. return this;
  3674. };
  3675. /**
  3676. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3677. */
  3678. Vector4.prototype.negate = function () {
  3679. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3680. };
  3681. /**
  3682. * Multiplies the current Vector4 coordinates by scale (float).
  3683. * Returns the updated Vector4.
  3684. */
  3685. Vector4.prototype.scaleInPlace = function (scale) {
  3686. this.x *= scale;
  3687. this.y *= scale;
  3688. this.z *= scale;
  3689. this.w *= scale;
  3690. return this;
  3691. };
  3692. /**
  3693. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3694. */
  3695. Vector4.prototype.scale = function (scale) {
  3696. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3697. };
  3698. /**
  3699. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3700. * Returns the current Vector4.
  3701. */
  3702. Vector4.prototype.scaleToRef = function (scale, result) {
  3703. result.x = this.x * scale;
  3704. result.y = this.y * scale;
  3705. result.z = this.z * scale;
  3706. result.w = this.w * scale;
  3707. return this;
  3708. };
  3709. /**
  3710. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3711. */
  3712. Vector4.prototype.equals = function (otherVector) {
  3713. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3714. };
  3715. /**
  3716. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3717. */
  3718. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3719. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3720. return otherVector
  3721. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3722. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3723. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3724. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3725. };
  3726. /**
  3727. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3728. */
  3729. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3730. return this.x === x && this.y === y && this.z === z && this.w === w;
  3731. };
  3732. /**
  3733. * Multiplies in place the current Vector4 by the passed one.
  3734. * Returns the updated Vector4.
  3735. */
  3736. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3737. this.x *= otherVector.x;
  3738. this.y *= otherVector.y;
  3739. this.z *= otherVector.z;
  3740. this.w *= otherVector.w;
  3741. return this;
  3742. };
  3743. /**
  3744. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3745. */
  3746. Vector4.prototype.multiply = function (otherVector) {
  3747. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3748. };
  3749. /**
  3750. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3751. * Returns the current Vector4.
  3752. */
  3753. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3754. result.x = this.x * otherVector.x;
  3755. result.y = this.y * otherVector.y;
  3756. result.z = this.z * otherVector.z;
  3757. result.w = this.w * otherVector.w;
  3758. return this;
  3759. };
  3760. /**
  3761. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3764. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3765. };
  3766. /**
  3767. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3768. */
  3769. Vector4.prototype.divide = function (otherVector) {
  3770. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3771. };
  3772. /**
  3773. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3774. * Returns the current Vector4.
  3775. */
  3776. Vector4.prototype.divideToRef = function (otherVector, result) {
  3777. result.x = this.x / otherVector.x;
  3778. result.y = this.y / otherVector.y;
  3779. result.z = this.z / otherVector.z;
  3780. result.w = this.w / otherVector.w;
  3781. return this;
  3782. };
  3783. /**
  3784. * Divides the current Vector3 coordinates by the passed ones.
  3785. * @returns the updated Vector3.
  3786. */
  3787. Vector4.prototype.divideInPlace = function (otherVector) {
  3788. return this.divideToRef(otherVector, this);
  3789. };
  3790. /**
  3791. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3792. * @param other defines the second operand
  3793. * @returns the current updated Vector4
  3794. */
  3795. Vector4.prototype.minimizeInPlace = function (other) {
  3796. if (other.x < this.x)
  3797. this.x = other.x;
  3798. if (other.y < this.y)
  3799. this.y = other.y;
  3800. if (other.z < this.z)
  3801. this.z = other.z;
  3802. if (other.w < this.w)
  3803. this.w = other.w;
  3804. return this;
  3805. };
  3806. /**
  3807. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3808. * @param other defines the second operand
  3809. * @returns the current updated Vector4
  3810. */
  3811. Vector4.prototype.maximizeInPlace = function (other) {
  3812. if (other.x > this.x)
  3813. this.x = other.x;
  3814. if (other.y > this.y)
  3815. this.y = other.y;
  3816. if (other.z > this.z)
  3817. this.z = other.z;
  3818. if (other.w > this.w)
  3819. this.w = other.w;
  3820. return this;
  3821. };
  3822. // Properties
  3823. /**
  3824. * Returns the Vector4 length (float).
  3825. */
  3826. Vector4.prototype.length = function () {
  3827. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3828. };
  3829. /**
  3830. * Returns the Vector4 squared length (float).
  3831. */
  3832. Vector4.prototype.lengthSquared = function () {
  3833. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3834. };
  3835. // Methods
  3836. /**
  3837. * Normalizes in place the Vector4.
  3838. * Returns the updated Vector4.
  3839. */
  3840. Vector4.prototype.normalize = function () {
  3841. var len = this.length();
  3842. if (len === 0)
  3843. return this;
  3844. var num = 1.0 / len;
  3845. this.x *= num;
  3846. this.y *= num;
  3847. this.z *= num;
  3848. this.w *= num;
  3849. return this;
  3850. };
  3851. /**
  3852. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3853. */
  3854. Vector4.prototype.toVector3 = function () {
  3855. return new Vector3(this.x, this.y, this.z);
  3856. };
  3857. /**
  3858. * Returns a new Vector4 copied from the current one.
  3859. */
  3860. Vector4.prototype.clone = function () {
  3861. return new Vector4(this.x, this.y, this.z, this.w);
  3862. };
  3863. /**
  3864. * Updates the current Vector4 with the passed one coordinates.
  3865. * Returns the updated Vector4.
  3866. */
  3867. Vector4.prototype.copyFrom = function (source) {
  3868. this.x = source.x;
  3869. this.y = source.y;
  3870. this.z = source.z;
  3871. this.w = source.w;
  3872. return this;
  3873. };
  3874. /**
  3875. * Updates the current Vector4 coordinates with the passed floats.
  3876. * Returns the updated Vector4.
  3877. */
  3878. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3879. this.x = x;
  3880. this.y = y;
  3881. this.z = z;
  3882. this.w = w;
  3883. return this;
  3884. };
  3885. /**
  3886. * Updates the current Vector4 coordinates with the passed floats.
  3887. * Returns the updated Vector4.
  3888. */
  3889. Vector4.prototype.set = function (x, y, z, w) {
  3890. return this.copyFromFloats(x, y, z, w);
  3891. };
  3892. // Statics
  3893. /**
  3894. * Returns a new Vector4 set from the starting index of the passed array.
  3895. */
  3896. Vector4.FromArray = function (array, offset) {
  3897. if (!offset) {
  3898. offset = 0;
  3899. }
  3900. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3901. };
  3902. /**
  3903. * Updates the passed vector "result" from the starting index of the passed array.
  3904. */
  3905. Vector4.FromArrayToRef = function (array, offset, result) {
  3906. result.x = array[offset];
  3907. result.y = array[offset + 1];
  3908. result.z = array[offset + 2];
  3909. result.w = array[offset + 3];
  3910. };
  3911. /**
  3912. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3913. */
  3914. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3915. Vector4.FromArrayToRef(array, offset, result);
  3916. };
  3917. /**
  3918. * Updates the passed vector "result" coordinates from the passed floats.
  3919. */
  3920. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3921. result.x = x;
  3922. result.y = y;
  3923. result.z = z;
  3924. result.w = w;
  3925. };
  3926. /**
  3927. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3928. */
  3929. Vector4.Zero = function () {
  3930. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3931. };
  3932. /**
  3933. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3934. */
  3935. Vector4.One = function () {
  3936. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3937. };
  3938. /**
  3939. * Returns a new normalized Vector4 from the passed one.
  3940. */
  3941. Vector4.Normalize = function (vector) {
  3942. var result = Vector4.Zero();
  3943. Vector4.NormalizeToRef(vector, result);
  3944. return result;
  3945. };
  3946. /**
  3947. * Updates the passed vector "result" from the normalization of the passed one.
  3948. */
  3949. Vector4.NormalizeToRef = function (vector, result) {
  3950. result.copyFrom(vector);
  3951. result.normalize();
  3952. };
  3953. Vector4.Minimize = function (left, right) {
  3954. var min = left.clone();
  3955. min.minimizeInPlace(right);
  3956. return min;
  3957. };
  3958. Vector4.Maximize = function (left, right) {
  3959. var max = left.clone();
  3960. max.maximizeInPlace(right);
  3961. return max;
  3962. };
  3963. /**
  3964. * Returns the distance (float) between the vectors "value1" and "value2".
  3965. */
  3966. Vector4.Distance = function (value1, value2) {
  3967. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3968. };
  3969. /**
  3970. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3971. */
  3972. Vector4.DistanceSquared = function (value1, value2) {
  3973. var x = value1.x - value2.x;
  3974. var y = value1.y - value2.y;
  3975. var z = value1.z - value2.z;
  3976. var w = value1.w - value2.w;
  3977. return (x * x) + (y * y) + (z * z) + (w * w);
  3978. };
  3979. /**
  3980. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3981. */
  3982. Vector4.Center = function (value1, value2) {
  3983. var center = value1.add(value2);
  3984. center.scaleInPlace(0.5);
  3985. return center;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3989. * This methods computes transformed normalized direction vectors only.
  3990. */
  3991. Vector4.TransformNormal = function (vector, transformation) {
  3992. var result = Vector4.Zero();
  3993. Vector4.TransformNormalToRef(vector, transformation, result);
  3994. return result;
  3995. };
  3996. /**
  3997. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3998. * This methods computes transformed normalized direction vectors only.
  3999. */
  4000. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4001. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4002. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4003. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4004. result.x = x;
  4005. result.y = y;
  4006. result.z = z;
  4007. result.w = vector.w;
  4008. };
  4009. /**
  4010. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4011. * This methods computes transformed normalized direction vectors only.
  4012. */
  4013. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4014. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4015. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4016. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4017. result.w = w;
  4018. };
  4019. return Vector4;
  4020. }());
  4021. BABYLON.Vector4 = Vector4;
  4022. var Size = /** @class */ (function () {
  4023. /**
  4024. * Creates a Size object from the passed width and height (floats).
  4025. */
  4026. function Size(width, height) {
  4027. this.width = width;
  4028. this.height = height;
  4029. }
  4030. // Returns a string with the Size width and height.
  4031. Size.prototype.toString = function () {
  4032. return "{W: " + this.width + ", H: " + this.height + "}";
  4033. };
  4034. /**
  4035. * Returns the string "Size"
  4036. */
  4037. Size.prototype.getClassName = function () {
  4038. return "Size";
  4039. };
  4040. /**
  4041. * Returns the Size hash code.
  4042. */
  4043. Size.prototype.getHashCode = function () {
  4044. var hash = this.width || 0;
  4045. hash = (hash * 397) ^ (this.height || 0);
  4046. return hash;
  4047. };
  4048. /**
  4049. * Updates the current size from the passed one.
  4050. * Returns the updated Size.
  4051. */
  4052. Size.prototype.copyFrom = function (src) {
  4053. this.width = src.width;
  4054. this.height = src.height;
  4055. };
  4056. /**
  4057. * Updates in place the current Size from the passed floats.
  4058. * Returns the updated Size.
  4059. */
  4060. Size.prototype.copyFromFloats = function (width, height) {
  4061. this.width = width;
  4062. this.height = height;
  4063. return this;
  4064. };
  4065. /**
  4066. * Updates in place the current Size from the passed floats.
  4067. * Returns the updated Size.
  4068. */
  4069. Size.prototype.set = function (width, height) {
  4070. return this.copyFromFloats(width, height);
  4071. };
  4072. /**
  4073. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4074. */
  4075. Size.prototype.multiplyByFloats = function (w, h) {
  4076. return new Size(this.width * w, this.height * h);
  4077. };
  4078. /**
  4079. * Returns a new Size copied from the passed one.
  4080. */
  4081. Size.prototype.clone = function () {
  4082. return new Size(this.width, this.height);
  4083. };
  4084. /**
  4085. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4086. */
  4087. Size.prototype.equals = function (other) {
  4088. if (!other) {
  4089. return false;
  4090. }
  4091. return (this.width === other.width) && (this.height === other.height);
  4092. };
  4093. Object.defineProperty(Size.prototype, "surface", {
  4094. /**
  4095. * Returns the surface of the Size : width * height (float).
  4096. */
  4097. get: function () {
  4098. return this.width * this.height;
  4099. },
  4100. enumerable: true,
  4101. configurable: true
  4102. });
  4103. /**
  4104. * Returns a new Size set to (0.0, 0.0)
  4105. */
  4106. Size.Zero = function () {
  4107. return new Size(0.0, 0.0);
  4108. };
  4109. /**
  4110. * Returns a new Size set as the addition result of the current Size and the passed one.
  4111. */
  4112. Size.prototype.add = function (otherSize) {
  4113. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4114. return r;
  4115. };
  4116. /**
  4117. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4118. */
  4119. Size.prototype.subtract = function (otherSize) {
  4120. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4121. return r;
  4122. };
  4123. /**
  4124. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4125. */
  4126. Size.Lerp = function (start, end, amount) {
  4127. var w = start.width + ((end.width - start.width) * amount);
  4128. var h = start.height + ((end.height - start.height) * amount);
  4129. return new Size(w, h);
  4130. };
  4131. return Size;
  4132. }());
  4133. BABYLON.Size = Size;
  4134. var Quaternion = /** @class */ (function () {
  4135. /**
  4136. * Creates a new Quaternion from the passed floats.
  4137. */
  4138. function Quaternion(x, y, z, w) {
  4139. if (x === void 0) { x = 0.0; }
  4140. if (y === void 0) { y = 0.0; }
  4141. if (z === void 0) { z = 0.0; }
  4142. if (w === void 0) { w = 1.0; }
  4143. this.x = x;
  4144. this.y = y;
  4145. this.z = z;
  4146. this.w = w;
  4147. }
  4148. /**
  4149. * Returns a string with the Quaternion coordinates.
  4150. */
  4151. Quaternion.prototype.toString = function () {
  4152. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4153. };
  4154. /**
  4155. * Returns the string "Quaternion".
  4156. */
  4157. Quaternion.prototype.getClassName = function () {
  4158. return "Quaternion";
  4159. };
  4160. /**
  4161. * Returns the Quaternion hash code.
  4162. */
  4163. Quaternion.prototype.getHashCode = function () {
  4164. var hash = this.x || 0;
  4165. hash = (hash * 397) ^ (this.y || 0);
  4166. hash = (hash * 397) ^ (this.z || 0);
  4167. hash = (hash * 397) ^ (this.w || 0);
  4168. return hash;
  4169. };
  4170. /**
  4171. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4172. */
  4173. Quaternion.prototype.asArray = function () {
  4174. return [this.x, this.y, this.z, this.w];
  4175. };
  4176. /**
  4177. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4178. */
  4179. Quaternion.prototype.equals = function (otherQuaternion) {
  4180. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4181. };
  4182. /**
  4183. * Returns a new Quaternion copied from the current one.
  4184. */
  4185. Quaternion.prototype.clone = function () {
  4186. return new Quaternion(this.x, this.y, this.z, this.w);
  4187. };
  4188. /**
  4189. * Updates the current Quaternion from the passed one coordinates.
  4190. * Returns the updated Quaterion.
  4191. */
  4192. Quaternion.prototype.copyFrom = function (other) {
  4193. this.x = other.x;
  4194. this.y = other.y;
  4195. this.z = other.z;
  4196. this.w = other.w;
  4197. return this;
  4198. };
  4199. /**
  4200. * Updates the current Quaternion from the passed float coordinates.
  4201. * Returns the updated Quaterion.
  4202. */
  4203. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4204. this.x = x;
  4205. this.y = y;
  4206. this.z = z;
  4207. this.w = w;
  4208. return this;
  4209. };
  4210. /**
  4211. * Updates the current Quaternion from the passed float coordinates.
  4212. * Returns the updated Quaterion.
  4213. */
  4214. Quaternion.prototype.set = function (x, y, z, w) {
  4215. return this.copyFromFloats(x, y, z, w);
  4216. };
  4217. /**
  4218. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4219. */
  4220. Quaternion.prototype.add = function (other) {
  4221. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4222. };
  4223. /**
  4224. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4225. */
  4226. Quaternion.prototype.subtract = function (other) {
  4227. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4228. };
  4229. /**
  4230. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4231. */
  4232. Quaternion.prototype.scale = function (value) {
  4233. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4234. };
  4235. /**
  4236. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4237. */
  4238. Quaternion.prototype.multiply = function (q1) {
  4239. var result = new Quaternion(0, 0, 0, 1.0);
  4240. this.multiplyToRef(q1, result);
  4241. return result;
  4242. };
  4243. /**
  4244. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4245. * Returns the current Quaternion.
  4246. */
  4247. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4248. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4249. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4250. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4251. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4252. result.copyFromFloats(x, y, z, w);
  4253. return this;
  4254. };
  4255. /**
  4256. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4257. * Returns the updated Quaternion.
  4258. */
  4259. Quaternion.prototype.multiplyInPlace = function (q1) {
  4260. this.multiplyToRef(q1, this);
  4261. return this;
  4262. };
  4263. /**
  4264. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4265. * Returns the current Quaternion.
  4266. */
  4267. Quaternion.prototype.conjugateToRef = function (ref) {
  4268. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4269. return this;
  4270. };
  4271. /**
  4272. * Conjugates in place the current Quaternion.
  4273. * Returns the updated Quaternion.
  4274. */
  4275. Quaternion.prototype.conjugateInPlace = function () {
  4276. this.x *= -1;
  4277. this.y *= -1;
  4278. this.z *= -1;
  4279. return this;
  4280. };
  4281. /**
  4282. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4283. */
  4284. Quaternion.prototype.conjugate = function () {
  4285. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4286. return result;
  4287. };
  4288. /**
  4289. * Returns the Quaternion length (float).
  4290. */
  4291. Quaternion.prototype.length = function () {
  4292. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4293. };
  4294. /**
  4295. * Normalize in place the current Quaternion.
  4296. * Returns the updated Quaternion.
  4297. */
  4298. Quaternion.prototype.normalize = function () {
  4299. var length = 1.0 / this.length();
  4300. this.x *= length;
  4301. this.y *= length;
  4302. this.z *= length;
  4303. this.w *= length;
  4304. return this;
  4305. };
  4306. /**
  4307. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4308. */
  4309. Quaternion.prototype.toEulerAngles = function (order) {
  4310. if (order === void 0) { order = "YZX"; }
  4311. var result = Vector3.Zero();
  4312. this.toEulerAnglesToRef(result, order);
  4313. return result;
  4314. };
  4315. /**
  4316. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4317. * Returns the current Quaternion.
  4318. */
  4319. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4320. if (order === void 0) { order = "YZX"; }
  4321. var qz = this.z;
  4322. var qx = this.x;
  4323. var qy = this.y;
  4324. var qw = this.w;
  4325. var sqw = qw * qw;
  4326. var sqz = qz * qz;
  4327. var sqx = qx * qx;
  4328. var sqy = qy * qy;
  4329. var zAxisY = qy * qz - qx * qw;
  4330. var limit = .4999999;
  4331. if (zAxisY < -limit) {
  4332. result.y = 2 * Math.atan2(qy, qw);
  4333. result.x = Math.PI / 2;
  4334. result.z = 0;
  4335. }
  4336. else if (zAxisY > limit) {
  4337. result.y = 2 * Math.atan2(qy, qw);
  4338. result.x = -Math.PI / 2;
  4339. result.z = 0;
  4340. }
  4341. else {
  4342. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4343. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4344. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4345. }
  4346. return this;
  4347. };
  4348. /**
  4349. * Updates the passed rotation matrix with the current Quaternion values.
  4350. * Returns the current Quaternion.
  4351. */
  4352. Quaternion.prototype.toRotationMatrix = function (result) {
  4353. var xx = this.x * this.x;
  4354. var yy = this.y * this.y;
  4355. var zz = this.z * this.z;
  4356. var xy = this.x * this.y;
  4357. var zw = this.z * this.w;
  4358. var zx = this.z * this.x;
  4359. var yw = this.y * this.w;
  4360. var yz = this.y * this.z;
  4361. var xw = this.x * this.w;
  4362. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4363. result.m[1] = 2.0 * (xy + zw);
  4364. result.m[2] = 2.0 * (zx - yw);
  4365. result.m[3] = 0;
  4366. result.m[4] = 2.0 * (xy - zw);
  4367. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4368. result.m[6] = 2.0 * (yz + xw);
  4369. result.m[7] = 0;
  4370. result.m[8] = 2.0 * (zx + yw);
  4371. result.m[9] = 2.0 * (yz - xw);
  4372. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4373. result.m[11] = 0;
  4374. result.m[12] = 0;
  4375. result.m[13] = 0;
  4376. result.m[14] = 0;
  4377. result.m[15] = 1.0;
  4378. result._markAsUpdated();
  4379. return this;
  4380. };
  4381. /**
  4382. * Updates the current Quaternion from the passed rotation matrix values.
  4383. * Returns the updated Quaternion.
  4384. */
  4385. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4386. Quaternion.FromRotationMatrixToRef(matrix, this);
  4387. return this;
  4388. };
  4389. // Statics
  4390. /**
  4391. * Returns a new Quaternion set from the passed rotation matrix values.
  4392. */
  4393. Quaternion.FromRotationMatrix = function (matrix) {
  4394. var result = new Quaternion();
  4395. Quaternion.FromRotationMatrixToRef(matrix, result);
  4396. return result;
  4397. };
  4398. /**
  4399. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4400. */
  4401. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4402. var data = matrix.m;
  4403. var m11 = data[0], m12 = data[4], m13 = data[8];
  4404. var m21 = data[1], m22 = data[5], m23 = data[9];
  4405. var m31 = data[2], m32 = data[6], m33 = data[10];
  4406. var trace = m11 + m22 + m33;
  4407. var s;
  4408. if (trace > 0) {
  4409. s = 0.5 / Math.sqrt(trace + 1.0);
  4410. result.w = 0.25 / s;
  4411. result.x = (m32 - m23) * s;
  4412. result.y = (m13 - m31) * s;
  4413. result.z = (m21 - m12) * s;
  4414. }
  4415. else if (m11 > m22 && m11 > m33) {
  4416. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4417. result.w = (m32 - m23) / s;
  4418. result.x = 0.25 * s;
  4419. result.y = (m12 + m21) / s;
  4420. result.z = (m13 + m31) / s;
  4421. }
  4422. else if (m22 > m33) {
  4423. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4424. result.w = (m13 - m31) / s;
  4425. result.x = (m12 + m21) / s;
  4426. result.y = 0.25 * s;
  4427. result.z = (m23 + m32) / s;
  4428. }
  4429. else {
  4430. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4431. result.w = (m21 - m12) / s;
  4432. result.x = (m13 + m31) / s;
  4433. result.y = (m23 + m32) / s;
  4434. result.z = 0.25 * s;
  4435. }
  4436. };
  4437. /**
  4438. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4439. */
  4440. Quaternion.Zero = function () {
  4441. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4442. };
  4443. /**
  4444. * Returns a new Quaternion as the inverted current Quaternion.
  4445. */
  4446. Quaternion.Inverse = function (q) {
  4447. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4448. };
  4449. /**
  4450. * Returns the identity Quaternion.
  4451. */
  4452. Quaternion.Identity = function () {
  4453. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4454. };
  4455. Quaternion.IsIdentity = function (quaternion) {
  4456. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4457. };
  4458. /**
  4459. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4460. */
  4461. Quaternion.RotationAxis = function (axis, angle) {
  4462. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4463. };
  4464. /**
  4465. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4466. */
  4467. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4468. var sin = Math.sin(angle / 2);
  4469. axis.normalize();
  4470. result.w = Math.cos(angle / 2);
  4471. result.x = axis.x * sin;
  4472. result.y = axis.y * sin;
  4473. result.z = axis.z * sin;
  4474. return result;
  4475. };
  4476. /**
  4477. * Retuns a new Quaternion set from the starting index of the passed array.
  4478. */
  4479. Quaternion.FromArray = function (array, offset) {
  4480. if (!offset) {
  4481. offset = 0;
  4482. }
  4483. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4484. };
  4485. /**
  4486. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4487. */
  4488. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4489. var q = new Quaternion();
  4490. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4491. return q;
  4492. };
  4493. /**
  4494. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4495. */
  4496. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4497. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4498. var halfRoll = roll * 0.5;
  4499. var halfPitch = pitch * 0.5;
  4500. var halfYaw = yaw * 0.5;
  4501. var sinRoll = Math.sin(halfRoll);
  4502. var cosRoll = Math.cos(halfRoll);
  4503. var sinPitch = Math.sin(halfPitch);
  4504. var cosPitch = Math.cos(halfPitch);
  4505. var sinYaw = Math.sin(halfYaw);
  4506. var cosYaw = Math.cos(halfYaw);
  4507. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4508. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4509. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4510. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4511. };
  4512. /**
  4513. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4514. */
  4515. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4516. var result = new Quaternion();
  4517. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4518. return result;
  4519. };
  4520. /**
  4521. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4522. */
  4523. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4524. // Produces a quaternion from Euler angles in the z-x-z orientation
  4525. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4526. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4527. var halfBeta = beta * 0.5;
  4528. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4529. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4530. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4531. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4532. };
  4533. /**
  4534. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4535. * cf to Vector3.RotationFromAxis() documentation.
  4536. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4537. */
  4538. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4539. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4540. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4541. return quat;
  4542. };
  4543. /**
  4544. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4545. * cf to Vector3.RotationFromAxis() documentation.
  4546. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4547. */
  4548. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4549. var rotMat = MathTmp.Matrix[0];
  4550. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4551. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4552. };
  4553. Quaternion.Slerp = function (left, right, amount) {
  4554. var result = Quaternion.Identity();
  4555. Quaternion.SlerpToRef(left, right, amount, result);
  4556. return result;
  4557. };
  4558. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4559. var num2;
  4560. var num3;
  4561. var num = amount;
  4562. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4563. var flag = false;
  4564. if (num4 < 0) {
  4565. flag = true;
  4566. num4 = -num4;
  4567. }
  4568. if (num4 > 0.999999) {
  4569. num3 = 1 - num;
  4570. num2 = flag ? -num : num;
  4571. }
  4572. else {
  4573. var num5 = Math.acos(num4);
  4574. var num6 = (1.0 / Math.sin(num5));
  4575. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4576. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4577. }
  4578. result.x = (num3 * left.x) + (num2 * right.x);
  4579. result.y = (num3 * left.y) + (num2 * right.y);
  4580. result.z = (num3 * left.z) + (num2 * right.z);
  4581. result.w = (num3 * left.w) + (num2 * right.w);
  4582. };
  4583. /**
  4584. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4585. */
  4586. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4587. var squared = amount * amount;
  4588. var cubed = amount * squared;
  4589. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4590. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4591. var part3 = (cubed - (2.0 * squared)) + amount;
  4592. var part4 = cubed - squared;
  4593. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4594. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4595. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4596. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4597. return new Quaternion(x, y, z, w);
  4598. };
  4599. return Quaternion;
  4600. }());
  4601. BABYLON.Quaternion = Quaternion;
  4602. var Matrix = /** @class */ (function () {
  4603. function Matrix() {
  4604. this._isIdentity = false;
  4605. this._isIdentityDirty = true;
  4606. this.m = new Float32Array(16);
  4607. this._markAsUpdated();
  4608. }
  4609. Matrix.prototype._markAsUpdated = function () {
  4610. this.updateFlag = Matrix._updateFlagSeed++;
  4611. this._isIdentityDirty = true;
  4612. };
  4613. // Properties
  4614. /**
  4615. * Boolean : True is the matrix is the identity matrix
  4616. */
  4617. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4618. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4619. if (this._isIdentityDirty) {
  4620. this._isIdentityDirty = false;
  4621. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4622. this._isIdentity = false;
  4623. }
  4624. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4625. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4626. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4627. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4628. this._isIdentity = false;
  4629. }
  4630. else {
  4631. this._isIdentity = true;
  4632. }
  4633. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4634. this._isIdentity = false;
  4635. }
  4636. }
  4637. return this._isIdentity;
  4638. };
  4639. /**
  4640. * Returns the matrix determinant (float).
  4641. */
  4642. Matrix.prototype.determinant = function () {
  4643. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4644. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4645. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4646. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4647. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4648. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4649. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4650. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4651. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4652. };
  4653. // Methods
  4654. /**
  4655. * Returns the matrix underlying array.
  4656. */
  4657. Matrix.prototype.toArray = function () {
  4658. return this.m;
  4659. };
  4660. /**
  4661. * Returns the matrix underlying array.
  4662. */
  4663. Matrix.prototype.asArray = function () {
  4664. return this.toArray();
  4665. };
  4666. /**
  4667. * Inverts in place the Matrix.
  4668. * Returns the Matrix inverted.
  4669. */
  4670. Matrix.prototype.invert = function () {
  4671. this.invertToRef(this);
  4672. return this;
  4673. };
  4674. /**
  4675. * Sets all the matrix elements to zero.
  4676. * Returns the Matrix.
  4677. */
  4678. Matrix.prototype.reset = function () {
  4679. for (var index = 0; index < 16; index++) {
  4680. this.m[index] = 0.0;
  4681. }
  4682. this._markAsUpdated();
  4683. return this;
  4684. };
  4685. /**
  4686. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4687. */
  4688. Matrix.prototype.add = function (other) {
  4689. var result = new Matrix();
  4690. this.addToRef(other, result);
  4691. return result;
  4692. };
  4693. /**
  4694. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4695. * Returns the Matrix.
  4696. */
  4697. Matrix.prototype.addToRef = function (other, result) {
  4698. for (var index = 0; index < 16; index++) {
  4699. result.m[index] = this.m[index] + other.m[index];
  4700. }
  4701. result._markAsUpdated();
  4702. return this;
  4703. };
  4704. /**
  4705. * Adds in place the passed matrix to the current Matrix.
  4706. * Returns the updated Matrix.
  4707. */
  4708. Matrix.prototype.addToSelf = function (other) {
  4709. for (var index = 0; index < 16; index++) {
  4710. this.m[index] += other.m[index];
  4711. }
  4712. this._markAsUpdated();
  4713. return this;
  4714. };
  4715. /**
  4716. * Sets the passed matrix with the current inverted Matrix.
  4717. * Returns the unmodified current Matrix.
  4718. */
  4719. Matrix.prototype.invertToRef = function (other) {
  4720. var l1 = this.m[0];
  4721. var l2 = this.m[1];
  4722. var l3 = this.m[2];
  4723. var l4 = this.m[3];
  4724. var l5 = this.m[4];
  4725. var l6 = this.m[5];
  4726. var l7 = this.m[6];
  4727. var l8 = this.m[7];
  4728. var l9 = this.m[8];
  4729. var l10 = this.m[9];
  4730. var l11 = this.m[10];
  4731. var l12 = this.m[11];
  4732. var l13 = this.m[12];
  4733. var l14 = this.m[13];
  4734. var l15 = this.m[14];
  4735. var l16 = this.m[15];
  4736. var l17 = (l11 * l16) - (l12 * l15);
  4737. var l18 = (l10 * l16) - (l12 * l14);
  4738. var l19 = (l10 * l15) - (l11 * l14);
  4739. var l20 = (l9 * l16) - (l12 * l13);
  4740. var l21 = (l9 * l15) - (l11 * l13);
  4741. var l22 = (l9 * l14) - (l10 * l13);
  4742. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4743. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4744. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4745. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4746. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4747. var l28 = (l7 * l16) - (l8 * l15);
  4748. var l29 = (l6 * l16) - (l8 * l14);
  4749. var l30 = (l6 * l15) - (l7 * l14);
  4750. var l31 = (l5 * l16) - (l8 * l13);
  4751. var l32 = (l5 * l15) - (l7 * l13);
  4752. var l33 = (l5 * l14) - (l6 * l13);
  4753. var l34 = (l7 * l12) - (l8 * l11);
  4754. var l35 = (l6 * l12) - (l8 * l10);
  4755. var l36 = (l6 * l11) - (l7 * l10);
  4756. var l37 = (l5 * l12) - (l8 * l9);
  4757. var l38 = (l5 * l11) - (l7 * l9);
  4758. var l39 = (l5 * l10) - (l6 * l9);
  4759. other.m[0] = l23 * l27;
  4760. other.m[4] = l24 * l27;
  4761. other.m[8] = l25 * l27;
  4762. other.m[12] = l26 * l27;
  4763. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4764. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4765. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4766. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4767. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4768. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4769. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4770. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4771. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4772. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4773. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4774. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4775. other._markAsUpdated();
  4776. return this;
  4777. };
  4778. /**
  4779. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4780. * Returns the updated Matrix.
  4781. */
  4782. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4783. this.m[12] = x;
  4784. this.m[13] = y;
  4785. this.m[14] = z;
  4786. this._markAsUpdated();
  4787. return this;
  4788. };
  4789. /**
  4790. * Inserts the translation vector in the current Matrix.
  4791. * Returns the updated Matrix.
  4792. */
  4793. Matrix.prototype.setTranslation = function (vector3) {
  4794. this.m[12] = vector3.x;
  4795. this.m[13] = vector3.y;
  4796. this.m[14] = vector3.z;
  4797. this._markAsUpdated();
  4798. return this;
  4799. };
  4800. /**
  4801. * Returns a new Vector3 as the extracted translation from the Matrix.
  4802. */
  4803. Matrix.prototype.getTranslation = function () {
  4804. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4805. };
  4806. /**
  4807. * Fill a Vector3 with the extracted translation from the Matrix.
  4808. */
  4809. Matrix.prototype.getTranslationToRef = function (result) {
  4810. result.x = this.m[12];
  4811. result.y = this.m[13];
  4812. result.z = this.m[14];
  4813. return this;
  4814. };
  4815. /**
  4816. * Remove rotation and scaling part from the Matrix.
  4817. * Returns the updated Matrix.
  4818. */
  4819. Matrix.prototype.removeRotationAndScaling = function () {
  4820. this.setRowFromFloats(0, 1, 0, 0, 0);
  4821. this.setRowFromFloats(1, 0, 1, 0, 0);
  4822. this.setRowFromFloats(2, 0, 0, 1, 0);
  4823. return this;
  4824. };
  4825. /**
  4826. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4827. */
  4828. Matrix.prototype.multiply = function (other) {
  4829. var result = new Matrix();
  4830. this.multiplyToRef(other, result);
  4831. return result;
  4832. };
  4833. /**
  4834. * Updates the current Matrix from the passed one values.
  4835. * Returns the updated Matrix.
  4836. */
  4837. Matrix.prototype.copyFrom = function (other) {
  4838. for (var index = 0; index < 16; index++) {
  4839. this.m[index] = other.m[index];
  4840. }
  4841. this._markAsUpdated();
  4842. return this;
  4843. };
  4844. /**
  4845. * Populates the passed array from the starting index with the Matrix values.
  4846. * Returns the Matrix.
  4847. */
  4848. Matrix.prototype.copyToArray = function (array, offset) {
  4849. if (offset === void 0) { offset = 0; }
  4850. for (var index = 0; index < 16; index++) {
  4851. array[offset + index] = this.m[index];
  4852. }
  4853. return this;
  4854. };
  4855. /**
  4856. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4857. */
  4858. Matrix.prototype.multiplyToRef = function (other, result) {
  4859. this.multiplyToArray(other, result.m, 0);
  4860. result._markAsUpdated();
  4861. return this;
  4862. };
  4863. /**
  4864. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4865. */
  4866. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4867. var tm0 = this.m[0];
  4868. var tm1 = this.m[1];
  4869. var tm2 = this.m[2];
  4870. var tm3 = this.m[3];
  4871. var tm4 = this.m[4];
  4872. var tm5 = this.m[5];
  4873. var tm6 = this.m[6];
  4874. var tm7 = this.m[7];
  4875. var tm8 = this.m[8];
  4876. var tm9 = this.m[9];
  4877. var tm10 = this.m[10];
  4878. var tm11 = this.m[11];
  4879. var tm12 = this.m[12];
  4880. var tm13 = this.m[13];
  4881. var tm14 = this.m[14];
  4882. var tm15 = this.m[15];
  4883. var om0 = other.m[0];
  4884. var om1 = other.m[1];
  4885. var om2 = other.m[2];
  4886. var om3 = other.m[3];
  4887. var om4 = other.m[4];
  4888. var om5 = other.m[5];
  4889. var om6 = other.m[6];
  4890. var om7 = other.m[7];
  4891. var om8 = other.m[8];
  4892. var om9 = other.m[9];
  4893. var om10 = other.m[10];
  4894. var om11 = other.m[11];
  4895. var om12 = other.m[12];
  4896. var om13 = other.m[13];
  4897. var om14 = other.m[14];
  4898. var om15 = other.m[15];
  4899. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4900. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4901. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4902. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4903. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4904. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4905. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4906. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4907. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4908. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4909. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4910. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4911. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4912. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4913. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4914. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4915. return this;
  4916. };
  4917. /**
  4918. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4919. */
  4920. Matrix.prototype.equals = function (value) {
  4921. return value &&
  4922. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4923. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4924. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4925. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4926. };
  4927. /**
  4928. * Returns a new Matrix from the current Matrix.
  4929. */
  4930. Matrix.prototype.clone = function () {
  4931. 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]);
  4932. };
  4933. /**
  4934. * Returns the string "Matrix"
  4935. */
  4936. Matrix.prototype.getClassName = function () {
  4937. return "Matrix";
  4938. };
  4939. /**
  4940. * Returns the Matrix hash code.
  4941. */
  4942. Matrix.prototype.getHashCode = function () {
  4943. var hash = this.m[0] || 0;
  4944. for (var i = 1; i < 16; i++) {
  4945. hash = (hash * 397) ^ (this.m[i] || 0);
  4946. }
  4947. return hash;
  4948. };
  4949. /**
  4950. * Decomposes the current Matrix into :
  4951. * - a scale vector3 passed as a reference to update,
  4952. * - a rotation quaternion passed as a reference to update,
  4953. * - a translation vector3 passed as a reference to update.
  4954. * Returns the true if operation was successful.
  4955. */
  4956. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4957. translation.x = this.m[12];
  4958. translation.y = this.m[13];
  4959. translation.z = this.m[14];
  4960. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4961. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4962. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4963. if (this.determinant() <= 0) {
  4964. scale.y *= -1;
  4965. }
  4966. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4967. rotation.x = 0;
  4968. rotation.y = 0;
  4969. rotation.z = 0;
  4970. rotation.w = 1;
  4971. return false;
  4972. }
  4973. 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]);
  4974. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4975. return true;
  4976. };
  4977. /**
  4978. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4979. * @param ref matrix to store the result
  4980. */
  4981. Matrix.prototype.toNormalMatrix = function (ref) {
  4982. this.invertToRef(ref);
  4983. ref.transpose();
  4984. var m = ref.m;
  4985. 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);
  4986. };
  4987. /**
  4988. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4989. */
  4990. Matrix.prototype.getRotationMatrix = function () {
  4991. var result = Matrix.Identity();
  4992. this.getRotationMatrixToRef(result);
  4993. return result;
  4994. };
  4995. /**
  4996. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4997. * Returns the current Matrix.
  4998. */
  4999. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5000. var m = this.m;
  5001. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5002. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5003. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5004. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5005. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5006. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5007. 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);
  5008. return this;
  5009. };
  5010. // Statics
  5011. /**
  5012. * Returns a new Matrix set from the starting index of the passed array.
  5013. */
  5014. Matrix.FromArray = function (array, offset) {
  5015. var result = new Matrix();
  5016. if (!offset) {
  5017. offset = 0;
  5018. }
  5019. Matrix.FromArrayToRef(array, offset, result);
  5020. return result;
  5021. };
  5022. /**
  5023. * Sets the passed "result" matrix from the starting index of the passed array.
  5024. */
  5025. Matrix.FromArrayToRef = function (array, offset, result) {
  5026. for (var index = 0; index < 16; index++) {
  5027. result.m[index] = array[index + offset];
  5028. }
  5029. result._markAsUpdated();
  5030. };
  5031. /**
  5032. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5033. */
  5034. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5035. for (var index = 0; index < 16; index++) {
  5036. result.m[index] = array[index + offset] * scale;
  5037. }
  5038. result._markAsUpdated();
  5039. };
  5040. /**
  5041. * Sets the passed matrix "result" with the 16 passed floats.
  5042. */
  5043. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5044. result.m[0] = initialM11;
  5045. result.m[1] = initialM12;
  5046. result.m[2] = initialM13;
  5047. result.m[3] = initialM14;
  5048. result.m[4] = initialM21;
  5049. result.m[5] = initialM22;
  5050. result.m[6] = initialM23;
  5051. result.m[7] = initialM24;
  5052. result.m[8] = initialM31;
  5053. result.m[9] = initialM32;
  5054. result.m[10] = initialM33;
  5055. result.m[11] = initialM34;
  5056. result.m[12] = initialM41;
  5057. result.m[13] = initialM42;
  5058. result.m[14] = initialM43;
  5059. result.m[15] = initialM44;
  5060. result._markAsUpdated();
  5061. };
  5062. /**
  5063. * Returns the index-th row of the current matrix as a new Vector4.
  5064. */
  5065. Matrix.prototype.getRow = function (index) {
  5066. if (index < 0 || index > 3) {
  5067. return null;
  5068. }
  5069. var i = index * 4;
  5070. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5071. };
  5072. /**
  5073. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5074. * Returns the updated Matrix.
  5075. */
  5076. Matrix.prototype.setRow = function (index, row) {
  5077. if (index < 0 || index > 3) {
  5078. return this;
  5079. }
  5080. var i = index * 4;
  5081. this.m[i + 0] = row.x;
  5082. this.m[i + 1] = row.y;
  5083. this.m[i + 2] = row.z;
  5084. this.m[i + 3] = row.w;
  5085. this._markAsUpdated();
  5086. return this;
  5087. };
  5088. /**
  5089. * Compute the transpose of the matrix.
  5090. * Returns a new Matrix.
  5091. */
  5092. Matrix.prototype.transpose = function () {
  5093. return Matrix.Transpose(this);
  5094. };
  5095. /**
  5096. * Compute the transpose of the matrix.
  5097. * Returns the current matrix.
  5098. */
  5099. Matrix.prototype.transposeToRef = function (result) {
  5100. Matrix.TransposeToRef(this, result);
  5101. return this;
  5102. };
  5103. /**
  5104. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5105. * Returns the updated Matrix.
  5106. */
  5107. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5108. if (index < 0 || index > 3) {
  5109. return this;
  5110. }
  5111. var i = index * 4;
  5112. this.m[i + 0] = x;
  5113. this.m[i + 1] = y;
  5114. this.m[i + 2] = z;
  5115. this.m[i + 3] = w;
  5116. this._markAsUpdated();
  5117. return this;
  5118. };
  5119. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5120. /**
  5121. * Static identity matrix to be used as readonly matrix
  5122. * Must not be updated.
  5123. */
  5124. get: function () {
  5125. return Matrix._identityReadOnly;
  5126. },
  5127. enumerable: true,
  5128. configurable: true
  5129. });
  5130. /**
  5131. * Returns a new Matrix set from the 16 passed floats.
  5132. */
  5133. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5134. var result = new Matrix();
  5135. result.m[0] = initialM11;
  5136. result.m[1] = initialM12;
  5137. result.m[2] = initialM13;
  5138. result.m[3] = initialM14;
  5139. result.m[4] = initialM21;
  5140. result.m[5] = initialM22;
  5141. result.m[6] = initialM23;
  5142. result.m[7] = initialM24;
  5143. result.m[8] = initialM31;
  5144. result.m[9] = initialM32;
  5145. result.m[10] = initialM33;
  5146. result.m[11] = initialM34;
  5147. result.m[12] = initialM41;
  5148. result.m[13] = initialM42;
  5149. result.m[14] = initialM43;
  5150. result.m[15] = initialM44;
  5151. return result;
  5152. };
  5153. /**
  5154. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5155. */
  5156. Matrix.Compose = function (scale, rotation, translation) {
  5157. var result = Matrix.Identity();
  5158. Matrix.ComposeToRef(scale, rotation, translation, result);
  5159. return result;
  5160. };
  5161. /**
  5162. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5163. */
  5164. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5165. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5166. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5167. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5168. result.setTranslation(translation);
  5169. };
  5170. /**
  5171. * Returns a new indentity Matrix.
  5172. */
  5173. Matrix.Identity = function () {
  5174. 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);
  5175. };
  5176. /**
  5177. * Sets the passed "result" as an identity matrix.
  5178. */
  5179. Matrix.IdentityToRef = function (result) {
  5180. 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);
  5181. };
  5182. /**
  5183. * Returns a new zero Matrix.
  5184. */
  5185. Matrix.Zero = function () {
  5186. 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);
  5187. };
  5188. /**
  5189. * Returns a new rotation matrix for "angle" radians around the X axis.
  5190. */
  5191. Matrix.RotationX = function (angle) {
  5192. var result = new Matrix();
  5193. Matrix.RotationXToRef(angle, result);
  5194. return result;
  5195. };
  5196. /**
  5197. * Returns a new Matrix as the passed inverted one.
  5198. */
  5199. Matrix.Invert = function (source) {
  5200. var result = new Matrix();
  5201. source.invertToRef(result);
  5202. return result;
  5203. };
  5204. /**
  5205. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5206. */
  5207. Matrix.RotationXToRef = function (angle, result) {
  5208. var s = Math.sin(angle);
  5209. var c = Math.cos(angle);
  5210. result.m[0] = 1.0;
  5211. result.m[15] = 1.0;
  5212. result.m[5] = c;
  5213. result.m[10] = c;
  5214. result.m[9] = -s;
  5215. result.m[6] = s;
  5216. result.m[1] = 0.0;
  5217. result.m[2] = 0.0;
  5218. result.m[3] = 0.0;
  5219. result.m[4] = 0.0;
  5220. result.m[7] = 0.0;
  5221. result.m[8] = 0.0;
  5222. result.m[11] = 0.0;
  5223. result.m[12] = 0.0;
  5224. result.m[13] = 0.0;
  5225. result.m[14] = 0.0;
  5226. result._markAsUpdated();
  5227. };
  5228. /**
  5229. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5230. */
  5231. Matrix.RotationY = function (angle) {
  5232. var result = new Matrix();
  5233. Matrix.RotationYToRef(angle, result);
  5234. return result;
  5235. };
  5236. /**
  5237. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5238. */
  5239. Matrix.RotationYToRef = function (angle, result) {
  5240. var s = Math.sin(angle);
  5241. var c = Math.cos(angle);
  5242. result.m[5] = 1.0;
  5243. result.m[15] = 1.0;
  5244. result.m[0] = c;
  5245. result.m[2] = -s;
  5246. result.m[8] = s;
  5247. result.m[10] = c;
  5248. result.m[1] = 0.0;
  5249. result.m[3] = 0.0;
  5250. result.m[4] = 0.0;
  5251. result.m[6] = 0.0;
  5252. result.m[7] = 0.0;
  5253. result.m[9] = 0.0;
  5254. result.m[11] = 0.0;
  5255. result.m[12] = 0.0;
  5256. result.m[13] = 0.0;
  5257. result.m[14] = 0.0;
  5258. result._markAsUpdated();
  5259. };
  5260. /**
  5261. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5262. */
  5263. Matrix.RotationZ = function (angle) {
  5264. var result = new Matrix();
  5265. Matrix.RotationZToRef(angle, result);
  5266. return result;
  5267. };
  5268. /**
  5269. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5270. */
  5271. Matrix.RotationZToRef = function (angle, result) {
  5272. var s = Math.sin(angle);
  5273. var c = Math.cos(angle);
  5274. result.m[10] = 1.0;
  5275. result.m[15] = 1.0;
  5276. result.m[0] = c;
  5277. result.m[1] = s;
  5278. result.m[4] = -s;
  5279. result.m[5] = c;
  5280. result.m[2] = 0.0;
  5281. result.m[3] = 0.0;
  5282. result.m[6] = 0.0;
  5283. result.m[7] = 0.0;
  5284. result.m[8] = 0.0;
  5285. result.m[9] = 0.0;
  5286. result.m[11] = 0.0;
  5287. result.m[12] = 0.0;
  5288. result.m[13] = 0.0;
  5289. result.m[14] = 0.0;
  5290. result._markAsUpdated();
  5291. };
  5292. /**
  5293. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5294. */
  5295. Matrix.RotationAxis = function (axis, angle) {
  5296. var result = Matrix.Zero();
  5297. Matrix.RotationAxisToRef(axis, angle, result);
  5298. return result;
  5299. };
  5300. /**
  5301. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5302. */
  5303. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5304. var s = Math.sin(-angle);
  5305. var c = Math.cos(-angle);
  5306. var c1 = 1 - c;
  5307. axis.normalize();
  5308. result.m[0] = (axis.x * axis.x) * c1 + c;
  5309. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5310. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5311. result.m[3] = 0.0;
  5312. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5313. result.m[5] = (axis.y * axis.y) * c1 + c;
  5314. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5315. result.m[7] = 0.0;
  5316. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5317. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5318. result.m[10] = (axis.z * axis.z) * c1 + c;
  5319. result.m[11] = 0.0;
  5320. result.m[15] = 1.0;
  5321. result._markAsUpdated();
  5322. };
  5323. /**
  5324. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5325. */
  5326. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5327. var result = new Matrix();
  5328. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5329. return result;
  5330. };
  5331. /**
  5332. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5333. */
  5334. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5335. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5336. this._tempQuaternion.toRotationMatrix(result);
  5337. };
  5338. /**
  5339. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5340. */
  5341. Matrix.Scaling = function (x, y, z) {
  5342. var result = Matrix.Zero();
  5343. Matrix.ScalingToRef(x, y, z, result);
  5344. return result;
  5345. };
  5346. /**
  5347. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5348. */
  5349. Matrix.ScalingToRef = function (x, y, z, result) {
  5350. result.m[0] = x;
  5351. result.m[1] = 0.0;
  5352. result.m[2] = 0.0;
  5353. result.m[3] = 0.0;
  5354. result.m[4] = 0.0;
  5355. result.m[5] = y;
  5356. result.m[6] = 0.0;
  5357. result.m[7] = 0.0;
  5358. result.m[8] = 0.0;
  5359. result.m[9] = 0.0;
  5360. result.m[10] = z;
  5361. result.m[11] = 0.0;
  5362. result.m[12] = 0.0;
  5363. result.m[13] = 0.0;
  5364. result.m[14] = 0.0;
  5365. result.m[15] = 1.0;
  5366. result._markAsUpdated();
  5367. };
  5368. /**
  5369. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5370. */
  5371. Matrix.Translation = function (x, y, z) {
  5372. var result = Matrix.Identity();
  5373. Matrix.TranslationToRef(x, y, z, result);
  5374. return result;
  5375. };
  5376. /**
  5377. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5378. */
  5379. Matrix.TranslationToRef = function (x, y, z, result) {
  5380. 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);
  5381. };
  5382. /**
  5383. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5384. */
  5385. Matrix.Lerp = function (startValue, endValue, gradient) {
  5386. var result = Matrix.Zero();
  5387. for (var index = 0; index < 16; index++) {
  5388. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5389. }
  5390. result._markAsUpdated();
  5391. return result;
  5392. };
  5393. /**
  5394. * Returns a new Matrix whose values are computed by :
  5395. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5396. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5397. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5398. */
  5399. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5400. var startScale = new Vector3(0, 0, 0);
  5401. var startRotation = new Quaternion();
  5402. var startTranslation = new Vector3(0, 0, 0);
  5403. startValue.decompose(startScale, startRotation, startTranslation);
  5404. var endScale = new Vector3(0, 0, 0);
  5405. var endRotation = new Quaternion();
  5406. var endTranslation = new Vector3(0, 0, 0);
  5407. endValue.decompose(endScale, endRotation, endTranslation);
  5408. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5409. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5410. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5411. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5412. };
  5413. /**
  5414. * 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".
  5415. * This methods works for a Left-Handed system.
  5416. */
  5417. Matrix.LookAtLH = function (eye, target, up) {
  5418. var result = Matrix.Zero();
  5419. Matrix.LookAtLHToRef(eye, target, up, result);
  5420. return result;
  5421. };
  5422. /**
  5423. * 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".
  5424. * This methods works for a Left-Handed system.
  5425. */
  5426. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5427. // Z axis
  5428. target.subtractToRef(eye, this._zAxis);
  5429. this._zAxis.normalize();
  5430. // X axis
  5431. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5432. if (this._xAxis.lengthSquared() === 0) {
  5433. this._xAxis.x = 1.0;
  5434. }
  5435. else {
  5436. this._xAxis.normalize();
  5437. }
  5438. // Y axis
  5439. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5440. this._yAxis.normalize();
  5441. // Eye angles
  5442. var ex = -Vector3.Dot(this._xAxis, eye);
  5443. var ey = -Vector3.Dot(this._yAxis, eye);
  5444. var ez = -Vector3.Dot(this._zAxis, eye);
  5445. 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);
  5446. };
  5447. /**
  5448. * 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".
  5449. * This methods works for a Right-Handed system.
  5450. */
  5451. Matrix.LookAtRH = function (eye, target, up) {
  5452. var result = Matrix.Zero();
  5453. Matrix.LookAtRHToRef(eye, target, up, result);
  5454. return result;
  5455. };
  5456. /**
  5457. * 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".
  5458. * This methods works for a Left-Handed system.
  5459. */
  5460. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5461. // Z axis
  5462. eye.subtractToRef(target, this._zAxis);
  5463. this._zAxis.normalize();
  5464. // X axis
  5465. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5466. if (this._xAxis.lengthSquared() === 0) {
  5467. this._xAxis.x = 1.0;
  5468. }
  5469. else {
  5470. this._xAxis.normalize();
  5471. }
  5472. // Y axis
  5473. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5474. this._yAxis.normalize();
  5475. // Eye angles
  5476. var ex = -Vector3.Dot(this._xAxis, eye);
  5477. var ey = -Vector3.Dot(this._yAxis, eye);
  5478. var ez = -Vector3.Dot(this._zAxis, eye);
  5479. 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);
  5480. };
  5481. /**
  5482. * 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.
  5483. */
  5484. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5485. var matrix = Matrix.Zero();
  5486. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5487. return matrix;
  5488. };
  5489. /**
  5490. * 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.
  5491. */
  5492. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5493. var n = znear;
  5494. var f = zfar;
  5495. var a = 2.0 / width;
  5496. var b = 2.0 / height;
  5497. var c = 2.0 / (f - n);
  5498. var d = -(f + n) / (f - n);
  5499. 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);
  5500. };
  5501. /**
  5502. * 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.
  5503. */
  5504. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5505. var matrix = Matrix.Zero();
  5506. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5507. return matrix;
  5508. };
  5509. /**
  5510. * 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.
  5511. */
  5512. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5513. var n = znear;
  5514. var f = zfar;
  5515. var a = 2.0 / (right - left);
  5516. var b = 2.0 / (top - bottom);
  5517. var c = 2.0 / (f - n);
  5518. var d = -(f + n) / (f - n);
  5519. var i0 = (left + right) / (left - right);
  5520. var i1 = (top + bottom) / (bottom - top);
  5521. 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);
  5522. };
  5523. /**
  5524. * 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.
  5525. */
  5526. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5527. var matrix = Matrix.Zero();
  5528. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5529. return matrix;
  5530. };
  5531. /**
  5532. * 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.
  5533. */
  5534. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5535. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5536. result.m[10] *= -1.0;
  5537. };
  5538. /**
  5539. * 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.
  5540. */
  5541. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5542. var matrix = Matrix.Zero();
  5543. var n = znear;
  5544. var f = zfar;
  5545. var a = 2.0 * n / width;
  5546. var b = 2.0 * n / height;
  5547. var c = (f + n) / (f - n);
  5548. var d = -2.0 * f * n / (f - n);
  5549. 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);
  5550. return matrix;
  5551. };
  5552. /**
  5553. * 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.
  5554. */
  5555. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5556. var matrix = Matrix.Zero();
  5557. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5558. return matrix;
  5559. };
  5560. /**
  5561. * 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.
  5562. */
  5563. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5564. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5565. var n = znear;
  5566. var f = zfar;
  5567. var t = 1.0 / (Math.tan(fov * 0.5));
  5568. var a = isVerticalFovFixed ? (t / aspect) : t;
  5569. var b = isVerticalFovFixed ? t : (t * aspect);
  5570. var c = (f + n) / (f - n);
  5571. var d = -2.0 * f * n / (f - n);
  5572. 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);
  5573. };
  5574. /**
  5575. * 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.
  5576. */
  5577. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5578. var matrix = Matrix.Zero();
  5579. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5580. return matrix;
  5581. };
  5582. /**
  5583. * 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.
  5584. */
  5585. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5586. //alternatively this could be expressed as:
  5587. // m = PerspectiveFovLHToRef
  5588. // m[10] *= -1.0;
  5589. // m[11] *= -1.0;
  5590. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5591. var n = znear;
  5592. var f = zfar;
  5593. var t = 1.0 / (Math.tan(fov * 0.5));
  5594. var a = isVerticalFovFixed ? (t / aspect) : t;
  5595. var b = isVerticalFovFixed ? t : (t * aspect);
  5596. var c = -(f + n) / (f - n);
  5597. var d = -2 * f * n / (f - n);
  5598. 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);
  5599. };
  5600. /**
  5601. * 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.
  5602. */
  5603. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5604. if (rightHanded === void 0) { rightHanded = false; }
  5605. var rightHandedFactor = rightHanded ? -1 : 1;
  5606. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5607. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5608. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5609. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5610. var xScale = 2.0 / (leftTan + rightTan);
  5611. var yScale = 2.0 / (upTan + downTan);
  5612. result.m[0] = xScale;
  5613. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5614. result.m[5] = yScale;
  5615. result.m[6] = result.m[7] = 0.0;
  5616. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5617. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5618. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5619. result.m[10] = -zfar / (znear - zfar);
  5620. result.m[11] = 1.0 * rightHandedFactor;
  5621. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5622. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5623. // result.m[14] = (znear * zfar) / (znear - zfar);
  5624. result._markAsUpdated();
  5625. };
  5626. /**
  5627. * Returns the final transformation matrix : world * view * projection * viewport
  5628. */
  5629. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5630. var cw = viewport.width;
  5631. var ch = viewport.height;
  5632. var cx = viewport.x;
  5633. var cy = viewport.y;
  5634. 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);
  5635. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5636. };
  5637. /**
  5638. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5639. */
  5640. Matrix.GetAsMatrix2x2 = function (matrix) {
  5641. return new Float32Array([
  5642. matrix.m[0], matrix.m[1],
  5643. matrix.m[4], matrix.m[5]
  5644. ]);
  5645. };
  5646. /**
  5647. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5648. */
  5649. Matrix.GetAsMatrix3x3 = function (matrix) {
  5650. return new Float32Array([
  5651. matrix.m[0], matrix.m[1], matrix.m[2],
  5652. matrix.m[4], matrix.m[5], matrix.m[6],
  5653. matrix.m[8], matrix.m[9], matrix.m[10]
  5654. ]);
  5655. };
  5656. /**
  5657. * Compute the transpose of the passed Matrix.
  5658. * Returns a new Matrix.
  5659. */
  5660. Matrix.Transpose = function (matrix) {
  5661. var result = new Matrix();
  5662. Matrix.TransposeToRef(matrix, result);
  5663. return result;
  5664. };
  5665. /**
  5666. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5667. */
  5668. Matrix.TransposeToRef = function (matrix, result) {
  5669. result.m[0] = matrix.m[0];
  5670. result.m[1] = matrix.m[4];
  5671. result.m[2] = matrix.m[8];
  5672. result.m[3] = matrix.m[12];
  5673. result.m[4] = matrix.m[1];
  5674. result.m[5] = matrix.m[5];
  5675. result.m[6] = matrix.m[9];
  5676. result.m[7] = matrix.m[13];
  5677. result.m[8] = matrix.m[2];
  5678. result.m[9] = matrix.m[6];
  5679. result.m[10] = matrix.m[10];
  5680. result.m[11] = matrix.m[14];
  5681. result.m[12] = matrix.m[3];
  5682. result.m[13] = matrix.m[7];
  5683. result.m[14] = matrix.m[11];
  5684. result.m[15] = matrix.m[15];
  5685. };
  5686. /**
  5687. * Returns a new Matrix as the reflection matrix across the passed plane.
  5688. */
  5689. Matrix.Reflection = function (plane) {
  5690. var matrix = new Matrix();
  5691. Matrix.ReflectionToRef(plane, matrix);
  5692. return matrix;
  5693. };
  5694. /**
  5695. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5696. */
  5697. Matrix.ReflectionToRef = function (plane, result) {
  5698. plane.normalize();
  5699. var x = plane.normal.x;
  5700. var y = plane.normal.y;
  5701. var z = plane.normal.z;
  5702. var temp = -2 * x;
  5703. var temp2 = -2 * y;
  5704. var temp3 = -2 * z;
  5705. result.m[0] = (temp * x) + 1;
  5706. result.m[1] = temp2 * x;
  5707. result.m[2] = temp3 * x;
  5708. result.m[3] = 0.0;
  5709. result.m[4] = temp * y;
  5710. result.m[5] = (temp2 * y) + 1;
  5711. result.m[6] = temp3 * y;
  5712. result.m[7] = 0.0;
  5713. result.m[8] = temp * z;
  5714. result.m[9] = temp2 * z;
  5715. result.m[10] = (temp3 * z) + 1;
  5716. result.m[11] = 0.0;
  5717. result.m[12] = temp * plane.d;
  5718. result.m[13] = temp2 * plane.d;
  5719. result.m[14] = temp3 * plane.d;
  5720. result.m[15] = 1.0;
  5721. result._markAsUpdated();
  5722. };
  5723. /**
  5724. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5725. */
  5726. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5727. result.m[0] = xaxis.x;
  5728. result.m[1] = xaxis.y;
  5729. result.m[2] = xaxis.z;
  5730. result.m[3] = 0.0;
  5731. result.m[4] = yaxis.x;
  5732. result.m[5] = yaxis.y;
  5733. result.m[6] = yaxis.z;
  5734. result.m[7] = 0.0;
  5735. result.m[8] = zaxis.x;
  5736. result.m[9] = zaxis.y;
  5737. result.m[10] = zaxis.z;
  5738. result.m[11] = 0.0;
  5739. result.m[12] = 0.0;
  5740. result.m[13] = 0.0;
  5741. result.m[14] = 0.0;
  5742. result.m[15] = 1.0;
  5743. result._markAsUpdated();
  5744. };
  5745. /**
  5746. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5747. */
  5748. Matrix.FromQuaternionToRef = function (quat, result) {
  5749. var xx = quat.x * quat.x;
  5750. var yy = quat.y * quat.y;
  5751. var zz = quat.z * quat.z;
  5752. var xy = quat.x * quat.y;
  5753. var zw = quat.z * quat.w;
  5754. var zx = quat.z * quat.x;
  5755. var yw = quat.y * quat.w;
  5756. var yz = quat.y * quat.z;
  5757. var xw = quat.x * quat.w;
  5758. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5759. result.m[1] = 2.0 * (xy + zw);
  5760. result.m[2] = 2.0 * (zx - yw);
  5761. result.m[3] = 0.0;
  5762. result.m[4] = 2.0 * (xy - zw);
  5763. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5764. result.m[6] = 2.0 * (yz + xw);
  5765. result.m[7] = 0.0;
  5766. result.m[8] = 2.0 * (zx + yw);
  5767. result.m[9] = 2.0 * (yz - xw);
  5768. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5769. result.m[11] = 0.0;
  5770. result.m[12] = 0.0;
  5771. result.m[13] = 0.0;
  5772. result.m[14] = 0.0;
  5773. result.m[15] = 1.0;
  5774. result._markAsUpdated();
  5775. };
  5776. Matrix._tempQuaternion = new Quaternion();
  5777. Matrix._xAxis = Vector3.Zero();
  5778. Matrix._yAxis = Vector3.Zero();
  5779. Matrix._zAxis = Vector3.Zero();
  5780. Matrix._updateFlagSeed = 0;
  5781. Matrix._identityReadOnly = Matrix.Identity();
  5782. return Matrix;
  5783. }());
  5784. BABYLON.Matrix = Matrix;
  5785. var Plane = /** @class */ (function () {
  5786. /**
  5787. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5788. */
  5789. function Plane(a, b, c, d) {
  5790. this.normal = new Vector3(a, b, c);
  5791. this.d = d;
  5792. }
  5793. /**
  5794. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5795. */
  5796. Plane.prototype.asArray = function () {
  5797. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5798. };
  5799. // Methods
  5800. /**
  5801. * Returns a new plane copied from the current Plane.
  5802. */
  5803. Plane.prototype.clone = function () {
  5804. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5805. };
  5806. /**
  5807. * Returns the string "Plane".
  5808. */
  5809. Plane.prototype.getClassName = function () {
  5810. return "Plane";
  5811. };
  5812. /**
  5813. * Returns the Plane hash code.
  5814. */
  5815. Plane.prototype.getHashCode = function () {
  5816. var hash = this.normal.getHashCode();
  5817. hash = (hash * 397) ^ (this.d || 0);
  5818. return hash;
  5819. };
  5820. /**
  5821. * Normalize the current Plane in place.
  5822. * Returns the updated Plane.
  5823. */
  5824. Plane.prototype.normalize = function () {
  5825. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5826. var magnitude = 0.0;
  5827. if (norm !== 0) {
  5828. magnitude = 1.0 / norm;
  5829. }
  5830. this.normal.x *= magnitude;
  5831. this.normal.y *= magnitude;
  5832. this.normal.z *= magnitude;
  5833. this.d *= magnitude;
  5834. return this;
  5835. };
  5836. /**
  5837. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5838. */
  5839. Plane.prototype.transform = function (transformation) {
  5840. var transposedMatrix = Matrix.Transpose(transformation);
  5841. var x = this.normal.x;
  5842. var y = this.normal.y;
  5843. var z = this.normal.z;
  5844. var d = this.d;
  5845. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5846. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5847. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5848. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5849. return new Plane(normalX, normalY, normalZ, finalD);
  5850. };
  5851. /**
  5852. * Returns the dot product (float) of the point coordinates and the plane normal.
  5853. */
  5854. Plane.prototype.dotCoordinate = function (point) {
  5855. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5856. };
  5857. /**
  5858. * Updates the current Plane from the plane defined by the three passed points.
  5859. * Returns the updated Plane.
  5860. */
  5861. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5862. var x1 = point2.x - point1.x;
  5863. var y1 = point2.y - point1.y;
  5864. var z1 = point2.z - point1.z;
  5865. var x2 = point3.x - point1.x;
  5866. var y2 = point3.y - point1.y;
  5867. var z2 = point3.z - point1.z;
  5868. var yz = (y1 * z2) - (z1 * y2);
  5869. var xz = (z1 * x2) - (x1 * z2);
  5870. var xy = (x1 * y2) - (y1 * x2);
  5871. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5872. var invPyth;
  5873. if (pyth !== 0) {
  5874. invPyth = 1.0 / pyth;
  5875. }
  5876. else {
  5877. invPyth = 0.0;
  5878. }
  5879. this.normal.x = yz * invPyth;
  5880. this.normal.y = xz * invPyth;
  5881. this.normal.z = xy * invPyth;
  5882. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5883. return this;
  5884. };
  5885. /**
  5886. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5887. */
  5888. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5889. var dot = Vector3.Dot(this.normal, direction);
  5890. return (dot <= epsilon);
  5891. };
  5892. /**
  5893. * Returns the signed distance (float) from the passed point to the Plane.
  5894. */
  5895. Plane.prototype.signedDistanceTo = function (point) {
  5896. return Vector3.Dot(point, this.normal) + this.d;
  5897. };
  5898. // Statics
  5899. /**
  5900. * Returns a new Plane from the passed array.
  5901. */
  5902. Plane.FromArray = function (array) {
  5903. return new Plane(array[0], array[1], array[2], array[3]);
  5904. };
  5905. /**
  5906. * Returns a new Plane defined by the three passed points.
  5907. */
  5908. Plane.FromPoints = function (point1, point2, point3) {
  5909. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5910. result.copyFromPoints(point1, point2, point3);
  5911. return result;
  5912. };
  5913. /**
  5914. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5915. * Note : the vector "normal" is updated because normalized.
  5916. */
  5917. Plane.FromPositionAndNormal = function (origin, normal) {
  5918. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5919. normal.normalize();
  5920. result.normal = normal;
  5921. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5922. return result;
  5923. };
  5924. /**
  5925. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5926. */
  5927. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5928. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5929. return Vector3.Dot(point, normal) + d;
  5930. };
  5931. return Plane;
  5932. }());
  5933. BABYLON.Plane = Plane;
  5934. var Viewport = /** @class */ (function () {
  5935. /**
  5936. * Creates a Viewport object located at (x, y) and sized (width, height).
  5937. */
  5938. function Viewport(x, y, width, height) {
  5939. this.x = x;
  5940. this.y = y;
  5941. this.width = width;
  5942. this.height = height;
  5943. }
  5944. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5945. if (renderWidthOrEngine.getRenderWidth) {
  5946. var engine = renderWidthOrEngine;
  5947. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5948. }
  5949. var renderWidth = renderWidthOrEngine;
  5950. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5951. };
  5952. /**
  5953. * Returns a new Viewport copied from the current one.
  5954. */
  5955. Viewport.prototype.clone = function () {
  5956. return new Viewport(this.x, this.y, this.width, this.height);
  5957. };
  5958. return Viewport;
  5959. }());
  5960. BABYLON.Viewport = Viewport;
  5961. var Frustum = /** @class */ (function () {
  5962. function Frustum() {
  5963. }
  5964. /**
  5965. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5966. */
  5967. Frustum.GetPlanes = function (transform) {
  5968. var frustumPlanes = [];
  5969. for (var index = 0; index < 6; index++) {
  5970. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5971. }
  5972. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5973. return frustumPlanes;
  5974. };
  5975. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5976. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5977. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5978. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5979. frustumPlane.d = transform.m[15] + transform.m[14];
  5980. frustumPlane.normalize();
  5981. };
  5982. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5983. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5984. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5985. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5986. frustumPlane.d = transform.m[15] - transform.m[14];
  5987. frustumPlane.normalize();
  5988. };
  5989. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5990. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5991. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5992. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5993. frustumPlane.d = transform.m[15] + transform.m[12];
  5994. frustumPlane.normalize();
  5995. };
  5996. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5997. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5998. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5999. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6000. frustumPlane.d = transform.m[15] - transform.m[12];
  6001. frustumPlane.normalize();
  6002. };
  6003. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6004. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6005. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6006. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6007. frustumPlane.d = transform.m[15] - transform.m[13];
  6008. frustumPlane.normalize();
  6009. };
  6010. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6011. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6012. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6013. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6014. frustumPlane.d = transform.m[15] + transform.m[13];
  6015. frustumPlane.normalize();
  6016. };
  6017. /**
  6018. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6019. */
  6020. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6021. // Near
  6022. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6023. // Far
  6024. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6025. // Left
  6026. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6027. // Right
  6028. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6029. // Top
  6030. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6031. // Bottom
  6032. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6033. };
  6034. return Frustum;
  6035. }());
  6036. BABYLON.Frustum = Frustum;
  6037. var Space;
  6038. (function (Space) {
  6039. Space[Space["LOCAL"] = 0] = "LOCAL";
  6040. Space[Space["WORLD"] = 1] = "WORLD";
  6041. Space[Space["BONE"] = 2] = "BONE";
  6042. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6043. var Axis = /** @class */ (function () {
  6044. function Axis() {
  6045. }
  6046. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6047. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6048. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6049. return Axis;
  6050. }());
  6051. BABYLON.Axis = Axis;
  6052. ;
  6053. var BezierCurve = /** @class */ (function () {
  6054. function BezierCurve() {
  6055. }
  6056. /**
  6057. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6058. */
  6059. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6060. // Extract X (which is equal to time here)
  6061. var f0 = 1 - 3 * x2 + 3 * x1;
  6062. var f1 = 3 * x2 - 6 * x1;
  6063. var f2 = 3 * x1;
  6064. var refinedT = t;
  6065. for (var i = 0; i < 5; i++) {
  6066. var refinedT2 = refinedT * refinedT;
  6067. var refinedT3 = refinedT2 * refinedT;
  6068. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6069. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6070. refinedT -= (x - t) * slope;
  6071. refinedT = Math.min(1, Math.max(0, refinedT));
  6072. }
  6073. // Resolve cubic bezier for the given x
  6074. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6075. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6076. Math.pow(refinedT, 3);
  6077. };
  6078. return BezierCurve;
  6079. }());
  6080. BABYLON.BezierCurve = BezierCurve;
  6081. var Orientation;
  6082. (function (Orientation) {
  6083. Orientation[Orientation["CW"] = 0] = "CW";
  6084. Orientation[Orientation["CCW"] = 1] = "CCW";
  6085. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6086. var Angle = /** @class */ (function () {
  6087. /**
  6088. * Creates an Angle object of "radians" radians (float).
  6089. */
  6090. function Angle(radians) {
  6091. var _this = this;
  6092. /**
  6093. * Returns the Angle value in degrees (float).
  6094. */
  6095. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6096. /**
  6097. * Returns the Angle value in radians (float).
  6098. */
  6099. this.radians = function () { return _this._radians; };
  6100. this._radians = radians;
  6101. if (this._radians < 0.0)
  6102. this._radians += (2.0 * Math.PI);
  6103. }
  6104. /**
  6105. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6106. */
  6107. Angle.BetweenTwoPoints = function (a, b) {
  6108. var delta = b.subtract(a);
  6109. var theta = Math.atan2(delta.y, delta.x);
  6110. return new Angle(theta);
  6111. };
  6112. /**
  6113. * Returns a new Angle object from the passed float in radians.
  6114. */
  6115. Angle.FromRadians = function (radians) {
  6116. return new Angle(radians);
  6117. };
  6118. /**
  6119. * Returns a new Angle object from the passed float in degrees.
  6120. */
  6121. Angle.FromDegrees = function (degrees) {
  6122. return new Angle(degrees * Math.PI / 180.0);
  6123. };
  6124. return Angle;
  6125. }());
  6126. BABYLON.Angle = Angle;
  6127. var Arc2 = /** @class */ (function () {
  6128. /**
  6129. * Creates an Arc object from the three passed points : start, middle and end.
  6130. */
  6131. function Arc2(startPoint, midPoint, endPoint) {
  6132. this.startPoint = startPoint;
  6133. this.midPoint = midPoint;
  6134. this.endPoint = endPoint;
  6135. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6136. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6137. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6138. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6139. 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);
  6140. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6141. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6142. var a1 = this.startAngle.degrees();
  6143. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6144. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6145. // angles correction
  6146. if (a2 - a1 > +180.0)
  6147. a2 -= 360.0;
  6148. if (a2 - a1 < -180.0)
  6149. a2 += 360.0;
  6150. if (a3 - a2 > +180.0)
  6151. a3 -= 360.0;
  6152. if (a3 - a2 < -180.0)
  6153. a3 += 360.0;
  6154. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6155. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6156. }
  6157. return Arc2;
  6158. }());
  6159. BABYLON.Arc2 = Arc2;
  6160. var Path2 = /** @class */ (function () {
  6161. /**
  6162. * Creates a Path2 object from the starting 2D coordinates x and y.
  6163. */
  6164. function Path2(x, y) {
  6165. this._points = new Array();
  6166. this._length = 0.0;
  6167. this.closed = false;
  6168. this._points.push(new Vector2(x, y));
  6169. }
  6170. /**
  6171. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6172. * Returns the updated Path2.
  6173. */
  6174. Path2.prototype.addLineTo = function (x, y) {
  6175. if (this.closed) {
  6176. //Tools.Error("cannot add lines to closed paths");
  6177. return this;
  6178. }
  6179. var newPoint = new Vector2(x, y);
  6180. var previousPoint = this._points[this._points.length - 1];
  6181. this._points.push(newPoint);
  6182. this._length += newPoint.subtract(previousPoint).length();
  6183. return this;
  6184. };
  6185. /**
  6186. * 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.
  6187. * Returns the updated Path2.
  6188. */
  6189. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6190. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6191. if (this.closed) {
  6192. //Tools.Error("cannot add arcs to closed paths");
  6193. return this;
  6194. }
  6195. var startPoint = this._points[this._points.length - 1];
  6196. var midPoint = new Vector2(midX, midY);
  6197. var endPoint = new Vector2(endX, endY);
  6198. var arc = new Arc2(startPoint, midPoint, endPoint);
  6199. var increment = arc.angle.radians() / numberOfSegments;
  6200. if (arc.orientation === Orientation.CW)
  6201. increment *= -1;
  6202. var currentAngle = arc.startAngle.radians() + increment;
  6203. for (var i = 0; i < numberOfSegments; i++) {
  6204. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6205. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6206. this.addLineTo(x, y);
  6207. currentAngle += increment;
  6208. }
  6209. return this;
  6210. };
  6211. /**
  6212. * Closes the Path2.
  6213. * Returns the Path2.
  6214. */
  6215. Path2.prototype.close = function () {
  6216. this.closed = true;
  6217. return this;
  6218. };
  6219. /**
  6220. * Returns the Path2 total length (float).
  6221. */
  6222. Path2.prototype.length = function () {
  6223. var result = this._length;
  6224. if (!this.closed) {
  6225. var lastPoint = this._points[this._points.length - 1];
  6226. var firstPoint = this._points[0];
  6227. result += (firstPoint.subtract(lastPoint).length());
  6228. }
  6229. return result;
  6230. };
  6231. /**
  6232. * Returns the Path2 internal array of points.
  6233. */
  6234. Path2.prototype.getPoints = function () {
  6235. return this._points;
  6236. };
  6237. /**
  6238. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6239. */
  6240. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6241. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6242. //Tools.Error("normalized length position should be between 0 and 1.");
  6243. return Vector2.Zero();
  6244. }
  6245. var lengthPosition = normalizedLengthPosition * this.length();
  6246. var previousOffset = 0;
  6247. for (var i = 0; i < this._points.length; i++) {
  6248. var j = (i + 1) % this._points.length;
  6249. var a = this._points[i];
  6250. var b = this._points[j];
  6251. var bToA = b.subtract(a);
  6252. var nextOffset = (bToA.length() + previousOffset);
  6253. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6254. var dir = bToA.normalize();
  6255. var localOffset = lengthPosition - previousOffset;
  6256. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6257. }
  6258. previousOffset = nextOffset;
  6259. }
  6260. //Tools.Error("internal error");
  6261. return Vector2.Zero();
  6262. };
  6263. /**
  6264. * Returns a new Path2 starting at the coordinates (x, y).
  6265. */
  6266. Path2.StartingAt = function (x, y) {
  6267. return new Path2(x, y);
  6268. };
  6269. return Path2;
  6270. }());
  6271. BABYLON.Path2 = Path2;
  6272. var Path3D = /** @class */ (function () {
  6273. /**
  6274. * new Path3D(path, normal, raw)
  6275. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6276. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6277. * path : an array of Vector3, the curve axis of the Path3D
  6278. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6279. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6280. */
  6281. function Path3D(path, firstNormal, raw) {
  6282. if (firstNormal === void 0) { firstNormal = null; }
  6283. this.path = path;
  6284. this._curve = new Array();
  6285. this._distances = new Array();
  6286. this._tangents = new Array();
  6287. this._normals = new Array();
  6288. this._binormals = new Array();
  6289. for (var p = 0; p < path.length; p++) {
  6290. this._curve[p] = path[p].clone(); // hard copy
  6291. }
  6292. this._raw = raw || false;
  6293. this._compute(firstNormal);
  6294. }
  6295. /**
  6296. * Returns the Path3D array of successive Vector3 designing its curve.
  6297. */
  6298. Path3D.prototype.getCurve = function () {
  6299. return this._curve;
  6300. };
  6301. /**
  6302. * Returns an array populated with tangent vectors on each Path3D curve point.
  6303. */
  6304. Path3D.prototype.getTangents = function () {
  6305. return this._tangents;
  6306. };
  6307. /**
  6308. * Returns an array populated with normal vectors on each Path3D curve point.
  6309. */
  6310. Path3D.prototype.getNormals = function () {
  6311. return this._normals;
  6312. };
  6313. /**
  6314. * Returns an array populated with binormal vectors on each Path3D curve point.
  6315. */
  6316. Path3D.prototype.getBinormals = function () {
  6317. return this._binormals;
  6318. };
  6319. /**
  6320. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6321. */
  6322. Path3D.prototype.getDistances = function () {
  6323. return this._distances;
  6324. };
  6325. /**
  6326. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6327. * Returns the same object updated.
  6328. */
  6329. Path3D.prototype.update = function (path, firstNormal) {
  6330. if (firstNormal === void 0) { firstNormal = null; }
  6331. for (var p = 0; p < path.length; p++) {
  6332. this._curve[p].x = path[p].x;
  6333. this._curve[p].y = path[p].y;
  6334. this._curve[p].z = path[p].z;
  6335. }
  6336. this._compute(firstNormal);
  6337. return this;
  6338. };
  6339. // private function compute() : computes tangents, normals and binormals
  6340. Path3D.prototype._compute = function (firstNormal) {
  6341. var l = this._curve.length;
  6342. // first and last tangents
  6343. this._tangents[0] = this._getFirstNonNullVector(0);
  6344. if (!this._raw) {
  6345. this._tangents[0].normalize();
  6346. }
  6347. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6348. if (!this._raw) {
  6349. this._tangents[l - 1].normalize();
  6350. }
  6351. // normals and binormals at first point : arbitrary vector with _normalVector()
  6352. var tg0 = this._tangents[0];
  6353. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6354. this._normals[0] = pp0;
  6355. if (!this._raw) {
  6356. this._normals[0].normalize();
  6357. }
  6358. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6359. if (!this._raw) {
  6360. this._binormals[0].normalize();
  6361. }
  6362. this._distances[0] = 0.0;
  6363. // normals and binormals : next points
  6364. var prev; // previous vector (segment)
  6365. var cur; // current vector (segment)
  6366. var curTang; // current tangent
  6367. // previous normal
  6368. var prevBinor; // previous binormal
  6369. for (var i = 1; i < l; i++) {
  6370. // tangents
  6371. prev = this._getLastNonNullVector(i);
  6372. if (i < l - 1) {
  6373. cur = this._getFirstNonNullVector(i);
  6374. this._tangents[i] = prev.add(cur);
  6375. this._tangents[i].normalize();
  6376. }
  6377. this._distances[i] = this._distances[i - 1] + prev.length();
  6378. // normals and binormals
  6379. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6380. curTang = this._tangents[i];
  6381. prevBinor = this._binormals[i - 1];
  6382. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6383. if (!this._raw) {
  6384. this._normals[i].normalize();
  6385. }
  6386. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6387. if (!this._raw) {
  6388. this._binormals[i].normalize();
  6389. }
  6390. }
  6391. };
  6392. // private function getFirstNonNullVector(index)
  6393. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6394. Path3D.prototype._getFirstNonNullVector = function (index) {
  6395. var i = 1;
  6396. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6397. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6398. i++;
  6399. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6400. }
  6401. return nNVector;
  6402. };
  6403. // private function getLastNonNullVector(index)
  6404. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6405. Path3D.prototype._getLastNonNullVector = function (index) {
  6406. var i = 1;
  6407. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6408. while (nLVector.length() === 0 && index > i + 1) {
  6409. i++;
  6410. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6411. }
  6412. return nLVector;
  6413. };
  6414. // private function normalVector(v0, vt, va) :
  6415. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6416. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6417. Path3D.prototype._normalVector = function (v0, vt, va) {
  6418. var normal0;
  6419. var tgl = vt.length();
  6420. if (tgl === 0.0) {
  6421. tgl = 1.0;
  6422. }
  6423. if (va === undefined || va === null) {
  6424. var point;
  6425. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6426. point = new Vector3(0.0, -1.0, 0.0);
  6427. }
  6428. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6429. point = new Vector3(1.0, 0.0, 0.0);
  6430. }
  6431. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6432. point = new Vector3(0.0, 0.0, 1.0);
  6433. }
  6434. else {
  6435. point = Vector3.Zero();
  6436. }
  6437. normal0 = Vector3.Cross(vt, point);
  6438. }
  6439. else {
  6440. normal0 = Vector3.Cross(vt, va);
  6441. Vector3.CrossToRef(normal0, vt, normal0);
  6442. }
  6443. normal0.normalize();
  6444. return normal0;
  6445. };
  6446. return Path3D;
  6447. }());
  6448. BABYLON.Path3D = Path3D;
  6449. var Curve3 = /** @class */ (function () {
  6450. /**
  6451. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6452. * A Curve3 is designed from a series of successive Vector3.
  6453. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6454. */
  6455. function Curve3(points) {
  6456. this._length = 0.0;
  6457. this._points = points;
  6458. this._length = this._computeLength(points);
  6459. }
  6460. /**
  6461. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6462. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6463. * @param v1 (Vector3) the control point
  6464. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6465. * @param nbPoints (integer) the wanted number of points in the curve
  6466. */
  6467. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6468. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6469. var bez = new Array();
  6470. var equation = function (t, val0, val1, val2) {
  6471. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6472. return res;
  6473. };
  6474. for (var i = 0; i <= nbPoints; i++) {
  6475. 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)));
  6476. }
  6477. return new Curve3(bez);
  6478. };
  6479. /**
  6480. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6481. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6482. * @param v1 (Vector3) the first control point
  6483. * @param v2 (Vector3) the second control point
  6484. * @param v3 (Vector3) the end point of the Cubic Bezier
  6485. * @param nbPoints (integer) the wanted number of points in the curve
  6486. */
  6487. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6488. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6489. var bez = new Array();
  6490. var equation = function (t, val0, val1, val2, val3) {
  6491. 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;
  6492. return res;
  6493. };
  6494. for (var i = 0; i <= nbPoints; i++) {
  6495. 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)));
  6496. }
  6497. return new Curve3(bez);
  6498. };
  6499. /**
  6500. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6501. * @param p1 (Vector3) the origin point of the Hermite Spline
  6502. * @param t1 (Vector3) the tangent vector at the origin point
  6503. * @param p2 (Vector3) the end point of the Hermite Spline
  6504. * @param t2 (Vector3) the tangent vector at the end point
  6505. * @param nbPoints (integer) the wanted number of points in the curve
  6506. */
  6507. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6508. var hermite = new Array();
  6509. var step = 1.0 / nbPoints;
  6510. for (var i = 0; i <= nbPoints; i++) {
  6511. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6512. }
  6513. return new Curve3(hermite);
  6514. };
  6515. /**
  6516. * Returns a Curve3 object along a CatmullRom Spline curve :
  6517. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6518. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6519. */
  6520. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6521. var totalPoints = new Array();
  6522. totalPoints.push(points[0].clone());
  6523. Array.prototype.push.apply(totalPoints, points);
  6524. totalPoints.push(points[points.length - 1].clone());
  6525. var catmullRom = new Array();
  6526. var step = 1.0 / nbPoints;
  6527. var amount = 0.0;
  6528. for (var i = 0; i < totalPoints.length - 3; i++) {
  6529. amount = 0;
  6530. for (var c = 0; c < nbPoints; c++) {
  6531. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6532. amount += step;
  6533. }
  6534. }
  6535. i--;
  6536. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6537. return new Curve3(catmullRom);
  6538. };
  6539. /**
  6540. * Returns the Curve3 stored array of successive Vector3
  6541. */
  6542. Curve3.prototype.getPoints = function () {
  6543. return this._points;
  6544. };
  6545. /**
  6546. * Returns the computed length (float) of the curve.
  6547. */
  6548. Curve3.prototype.length = function () {
  6549. return this._length;
  6550. };
  6551. /**
  6552. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6553. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6554. * curveA and curveB keep unchanged.
  6555. */
  6556. Curve3.prototype.continue = function (curve) {
  6557. var lastPoint = this._points[this._points.length - 1];
  6558. var continuedPoints = this._points.slice();
  6559. var curvePoints = curve.getPoints();
  6560. for (var i = 1; i < curvePoints.length; i++) {
  6561. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6562. }
  6563. var continuedCurve = new Curve3(continuedPoints);
  6564. return continuedCurve;
  6565. };
  6566. Curve3.prototype._computeLength = function (path) {
  6567. var l = 0;
  6568. for (var i = 1; i < path.length; i++) {
  6569. l += (path[i].subtract(path[i - 1])).length();
  6570. }
  6571. return l;
  6572. };
  6573. return Curve3;
  6574. }());
  6575. BABYLON.Curve3 = Curve3;
  6576. // Vertex formats
  6577. var PositionNormalVertex = /** @class */ (function () {
  6578. function PositionNormalVertex(position, normal) {
  6579. if (position === void 0) { position = Vector3.Zero(); }
  6580. if (normal === void 0) { normal = Vector3.Up(); }
  6581. this.position = position;
  6582. this.normal = normal;
  6583. }
  6584. PositionNormalVertex.prototype.clone = function () {
  6585. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6586. };
  6587. return PositionNormalVertex;
  6588. }());
  6589. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6590. var PositionNormalTextureVertex = /** @class */ (function () {
  6591. function PositionNormalTextureVertex(position, normal, uv) {
  6592. if (position === void 0) { position = Vector3.Zero(); }
  6593. if (normal === void 0) { normal = Vector3.Up(); }
  6594. if (uv === void 0) { uv = Vector2.Zero(); }
  6595. this.position = position;
  6596. this.normal = normal;
  6597. this.uv = uv;
  6598. }
  6599. PositionNormalTextureVertex.prototype.clone = function () {
  6600. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6601. };
  6602. return PositionNormalTextureVertex;
  6603. }());
  6604. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6605. // Temporary pre-allocated objects for engine internal use
  6606. // usage in any internal function :
  6607. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6608. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6609. var Tmp = /** @class */ (function () {
  6610. function Tmp() {
  6611. }
  6612. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6613. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6614. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6615. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6616. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6617. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6618. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6619. Matrix.Zero(), Matrix.Zero(),
  6620. Matrix.Zero(), Matrix.Zero(),
  6621. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6622. return Tmp;
  6623. }());
  6624. BABYLON.Tmp = Tmp;
  6625. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6626. var MathTmp = /** @class */ (function () {
  6627. function MathTmp() {
  6628. }
  6629. MathTmp.Vector3 = [Vector3.Zero()];
  6630. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6631. MathTmp.Quaternion = [Quaternion.Zero()];
  6632. return MathTmp;
  6633. }());
  6634. })(BABYLON || (BABYLON = {}));
  6635. //# sourceMappingURL=babylon.math.js.map
  6636. var BABYLON;
  6637. (function (BABYLON) {
  6638. var Scalar = /** @class */ (function () {
  6639. function Scalar() {
  6640. }
  6641. /**
  6642. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6643. */
  6644. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6645. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6646. var num = a - b;
  6647. return -epsilon <= num && num <= epsilon;
  6648. };
  6649. /**
  6650. * Returns a string : the upper case translation of the number i to hexadecimal.
  6651. */
  6652. Scalar.ToHex = function (i) {
  6653. var str = i.toString(16);
  6654. if (i <= 15) {
  6655. return ("0" + str).toUpperCase();
  6656. }
  6657. return str.toUpperCase();
  6658. };
  6659. /**
  6660. * Returns -1 if value is negative and +1 is value is positive.
  6661. * Returns the value itself if it's equal to zero.
  6662. */
  6663. Scalar.Sign = function (value) {
  6664. value = +value; // convert to a number
  6665. if (value === 0 || isNaN(value))
  6666. return value;
  6667. return value > 0 ? 1 : -1;
  6668. };
  6669. /**
  6670. * Returns the value itself if it's between min and max.
  6671. * Returns min if the value is lower than min.
  6672. * Returns max if the value is greater than max.
  6673. */
  6674. Scalar.Clamp = function (value, min, max) {
  6675. if (min === void 0) { min = 0; }
  6676. if (max === void 0) { max = 1; }
  6677. return Math.min(max, Math.max(min, value));
  6678. };
  6679. /**
  6680. * Returns the log2 of value.
  6681. */
  6682. Scalar.Log2 = function (value) {
  6683. return Math.log(value) * Math.LOG2E;
  6684. };
  6685. /**
  6686. * Loops the value, so that it is never larger than length and never smaller than 0.
  6687. *
  6688. * This is similar to the modulo operator but it works with floating point numbers.
  6689. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6690. * With t = 5 and length = 2.5, the result would be 0.0.
  6691. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6692. */
  6693. Scalar.Repeat = function (value, length) {
  6694. return value - Math.floor(value / length) * length;
  6695. };
  6696. /**
  6697. * Normalize the value between 0.0 and 1.0 using min and max values
  6698. */
  6699. Scalar.Normalize = function (value, min, max) {
  6700. return (value - min) / (max - min);
  6701. };
  6702. /**
  6703. * Denormalize the value from 0.0 and 1.0 using min and max values
  6704. */
  6705. Scalar.Denormalize = function (normalized, min, max) {
  6706. return (normalized * (max - min) + min);
  6707. };
  6708. /**
  6709. * Calculates the shortest difference between two given angles given in degrees.
  6710. */
  6711. Scalar.DeltaAngle = function (current, target) {
  6712. var num = Scalar.Repeat(target - current, 360.0);
  6713. if (num > 180.0) {
  6714. num -= 360.0;
  6715. }
  6716. return num;
  6717. };
  6718. /**
  6719. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6720. *
  6721. * The returned value will move back and forth between 0 and length
  6722. */
  6723. Scalar.PingPong = function (tx, length) {
  6724. var t = Scalar.Repeat(tx, length * 2.0);
  6725. return length - Math.abs(t - length);
  6726. };
  6727. /**
  6728. * Interpolates between min and max with smoothing at the limits.
  6729. *
  6730. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6731. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6732. */
  6733. Scalar.SmoothStep = function (from, to, tx) {
  6734. var t = Scalar.Clamp(tx);
  6735. t = -2.0 * t * t * t + 3.0 * t * t;
  6736. return to * t + from * (1.0 - t);
  6737. };
  6738. /**
  6739. * Moves a value current towards target.
  6740. *
  6741. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6742. * Negative values of maxDelta pushes the value away from target.
  6743. */
  6744. Scalar.MoveTowards = function (current, target, maxDelta) {
  6745. var result = 0;
  6746. if (Math.abs(target - current) <= maxDelta) {
  6747. result = target;
  6748. }
  6749. else {
  6750. result = current + Scalar.Sign(target - current) * maxDelta;
  6751. }
  6752. return result;
  6753. };
  6754. /**
  6755. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6756. *
  6757. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6758. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6759. */
  6760. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6761. var num = Scalar.DeltaAngle(current, target);
  6762. var result = 0;
  6763. if (-maxDelta < num && num < maxDelta) {
  6764. result = target;
  6765. }
  6766. else {
  6767. target = current + num;
  6768. result = Scalar.MoveTowards(current, target, maxDelta);
  6769. }
  6770. return result;
  6771. };
  6772. /**
  6773. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6774. */
  6775. Scalar.Lerp = function (start, end, amount) {
  6776. return start + ((end - start) * amount);
  6777. };
  6778. /**
  6779. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6780. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6781. */
  6782. Scalar.LerpAngle = function (start, end, amount) {
  6783. var num = Scalar.Repeat(end - start, 360.0);
  6784. if (num > 180.0) {
  6785. num -= 360.0;
  6786. }
  6787. return start + num * Scalar.Clamp(amount);
  6788. };
  6789. /**
  6790. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6791. */
  6792. Scalar.InverseLerp = function (a, b, value) {
  6793. var result = 0;
  6794. if (a != b) {
  6795. result = Scalar.Clamp((value - a) / (b - a));
  6796. }
  6797. else {
  6798. result = 0.0;
  6799. }
  6800. return result;
  6801. };
  6802. /**
  6803. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6804. */
  6805. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6806. var squared = amount * amount;
  6807. var cubed = amount * squared;
  6808. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6809. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6810. var part3 = (cubed - (2.0 * squared)) + amount;
  6811. var part4 = cubed - squared;
  6812. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6813. };
  6814. /**
  6815. * Returns a random float number between and min and max values
  6816. */
  6817. Scalar.RandomRange = function (min, max) {
  6818. if (min === max)
  6819. return min;
  6820. return ((Math.random() * (max - min)) + min);
  6821. };
  6822. /**
  6823. * This function returns percentage of a number in a given range.
  6824. *
  6825. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6826. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6827. */
  6828. Scalar.RangeToPercent = function (number, min, max) {
  6829. return ((number - min) / (max - min));
  6830. };
  6831. /**
  6832. * This function returns number that corresponds to the percentage in a given range.
  6833. *
  6834. * PercentToRange(0.34,0,100) will return 34.
  6835. */
  6836. Scalar.PercentToRange = function (percent, min, max) {
  6837. return ((max - min) * percent + min);
  6838. };
  6839. /**
  6840. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6841. * @param angle The angle to normalize in radian.
  6842. * @return The converted angle.
  6843. */
  6844. Scalar.NormalizeRadians = function (angle) {
  6845. // More precise but slower version kept for reference.
  6846. // angle = angle % Tools.TwoPi;
  6847. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6848. //if (angle > Math.PI) {
  6849. // angle -= Tools.TwoPi;
  6850. //}
  6851. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6852. return angle;
  6853. };
  6854. /**
  6855. * Two pi constants convenient for computation.
  6856. */
  6857. Scalar.TwoPi = Math.PI * 2;
  6858. return Scalar;
  6859. }());
  6860. BABYLON.Scalar = Scalar;
  6861. })(BABYLON || (BABYLON = {}));
  6862. //# sourceMappingURL=babylon.math.scalar.js.map
  6863. //# sourceMappingURL=babylon.mixins.js.map
  6864. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6865. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6866. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6867. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6868. //# sourceMappingURL=babylon.webgl2.js.map
  6869. var BABYLON;
  6870. (function (BABYLON) {
  6871. var __decoratorInitialStore = {};
  6872. var __mergedStore = {};
  6873. var _copySource = function (creationFunction, source, instanciate) {
  6874. var destination = creationFunction();
  6875. // Tags
  6876. if (BABYLON.Tags) {
  6877. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6878. }
  6879. var classStore = getMergedStore(destination);
  6880. // Properties
  6881. for (var property in classStore) {
  6882. var propertyDescriptor = classStore[property];
  6883. var sourceProperty = source[property];
  6884. var propertyType = propertyDescriptor.type;
  6885. if (sourceProperty !== undefined && sourceProperty !== null) {
  6886. switch (propertyType) {
  6887. case 0: // Value
  6888. case 6:// Mesh reference
  6889. destination[property] = sourceProperty;
  6890. break;
  6891. case 1:// Texture
  6892. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6893. break;
  6894. case 2: // Color3
  6895. case 3: // FresnelParameters
  6896. case 4: // Vector2
  6897. case 5: // Vector3
  6898. case 7: // Color Curves
  6899. case 10:// Quaternion
  6900. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6901. break;
  6902. }
  6903. }
  6904. }
  6905. return destination;
  6906. };
  6907. function getDirectStore(target) {
  6908. var classKey = target.getClassName();
  6909. if (!__decoratorInitialStore[classKey]) {
  6910. __decoratorInitialStore[classKey] = {};
  6911. }
  6912. return __decoratorInitialStore[classKey];
  6913. }
  6914. /**
  6915. * Return the list of properties flagged as serializable
  6916. * @param target: host object
  6917. */
  6918. function getMergedStore(target) {
  6919. var classKey = target.getClassName();
  6920. if (__mergedStore[classKey]) {
  6921. return __mergedStore[classKey];
  6922. }
  6923. __mergedStore[classKey] = {};
  6924. var store = __mergedStore[classKey];
  6925. var currentTarget = target;
  6926. var currentKey = classKey;
  6927. while (currentKey) {
  6928. var initialStore = __decoratorInitialStore[currentKey];
  6929. for (var property in initialStore) {
  6930. store[property] = initialStore[property];
  6931. }
  6932. var parent_1 = void 0;
  6933. var done = false;
  6934. do {
  6935. parent_1 = Object.getPrototypeOf(currentTarget);
  6936. if (!parent_1.getClassName) {
  6937. done = true;
  6938. break;
  6939. }
  6940. if (parent_1.getClassName() !== currentKey) {
  6941. break;
  6942. }
  6943. currentTarget = parent_1;
  6944. } while (parent_1);
  6945. if (done) {
  6946. break;
  6947. }
  6948. currentKey = parent_1.getClassName();
  6949. currentTarget = parent_1;
  6950. }
  6951. return store;
  6952. }
  6953. function generateSerializableMember(type, sourceName) {
  6954. return function (target, propertyKey) {
  6955. var classStore = getDirectStore(target);
  6956. if (!classStore[propertyKey]) {
  6957. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6958. }
  6959. };
  6960. }
  6961. function generateExpandMember(setCallback, targetKey) {
  6962. if (targetKey === void 0) { targetKey = null; }
  6963. return function (target, propertyKey) {
  6964. var key = targetKey || ("_" + propertyKey);
  6965. Object.defineProperty(target, propertyKey, {
  6966. get: function () {
  6967. return this[key];
  6968. },
  6969. set: function (value) {
  6970. if (this[key] === value) {
  6971. return;
  6972. }
  6973. this[key] = value;
  6974. target[setCallback].apply(this);
  6975. },
  6976. enumerable: true,
  6977. configurable: true
  6978. });
  6979. };
  6980. }
  6981. function expandToProperty(callback, targetKey) {
  6982. if (targetKey === void 0) { targetKey = null; }
  6983. return generateExpandMember(callback, targetKey);
  6984. }
  6985. BABYLON.expandToProperty = expandToProperty;
  6986. function serialize(sourceName) {
  6987. return generateSerializableMember(0, sourceName); // value member
  6988. }
  6989. BABYLON.serialize = serialize;
  6990. function serializeAsTexture(sourceName) {
  6991. return generateSerializableMember(1, sourceName); // texture member
  6992. }
  6993. BABYLON.serializeAsTexture = serializeAsTexture;
  6994. function serializeAsColor3(sourceName) {
  6995. return generateSerializableMember(2, sourceName); // color3 member
  6996. }
  6997. BABYLON.serializeAsColor3 = serializeAsColor3;
  6998. function serializeAsFresnelParameters(sourceName) {
  6999. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7000. }
  7001. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7002. function serializeAsVector2(sourceName) {
  7003. return generateSerializableMember(4, sourceName); // vector2 member
  7004. }
  7005. BABYLON.serializeAsVector2 = serializeAsVector2;
  7006. function serializeAsVector3(sourceName) {
  7007. return generateSerializableMember(5, sourceName); // vector3 member
  7008. }
  7009. BABYLON.serializeAsVector3 = serializeAsVector3;
  7010. function serializeAsMeshReference(sourceName) {
  7011. return generateSerializableMember(6, sourceName); // mesh reference member
  7012. }
  7013. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7014. function serializeAsColorCurves(sourceName) {
  7015. return generateSerializableMember(7, sourceName); // color curves
  7016. }
  7017. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7018. function serializeAsColor4(sourceName) {
  7019. return generateSerializableMember(8, sourceName); // color 4
  7020. }
  7021. BABYLON.serializeAsColor4 = serializeAsColor4;
  7022. function serializeAsImageProcessingConfiguration(sourceName) {
  7023. return generateSerializableMember(9, sourceName); // image processing
  7024. }
  7025. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7026. function serializeAsQuaternion(sourceName) {
  7027. return generateSerializableMember(10, sourceName); // quaternion member
  7028. }
  7029. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7030. var SerializationHelper = /** @class */ (function () {
  7031. function SerializationHelper() {
  7032. }
  7033. SerializationHelper.Serialize = function (entity, serializationObject) {
  7034. if (!serializationObject) {
  7035. serializationObject = {};
  7036. }
  7037. // Tags
  7038. if (BABYLON.Tags) {
  7039. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7040. }
  7041. var serializedProperties = getMergedStore(entity);
  7042. // Properties
  7043. for (var property in serializedProperties) {
  7044. var propertyDescriptor = serializedProperties[property];
  7045. var targetPropertyName = propertyDescriptor.sourceName || property;
  7046. var propertyType = propertyDescriptor.type;
  7047. var sourceProperty = entity[property];
  7048. if (sourceProperty !== undefined && sourceProperty !== null) {
  7049. switch (propertyType) {
  7050. case 0:// Value
  7051. serializationObject[targetPropertyName] = sourceProperty;
  7052. break;
  7053. case 1:// Texture
  7054. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7055. break;
  7056. case 2:// Color3
  7057. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7058. break;
  7059. case 3:// FresnelParameters
  7060. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7061. break;
  7062. case 4:// Vector2
  7063. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7064. break;
  7065. case 5:// Vector3
  7066. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7067. break;
  7068. case 6:// Mesh reference
  7069. serializationObject[targetPropertyName] = sourceProperty.id;
  7070. break;
  7071. case 7:// Color Curves
  7072. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7073. break;
  7074. case 8:// Color 4
  7075. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7076. break;
  7077. case 9:// Image Processing
  7078. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7079. break;
  7080. }
  7081. }
  7082. }
  7083. return serializationObject;
  7084. };
  7085. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7086. if (rootUrl === void 0) { rootUrl = null; }
  7087. var destination = creationFunction();
  7088. if (!rootUrl) {
  7089. rootUrl = "";
  7090. }
  7091. // Tags
  7092. if (BABYLON.Tags) {
  7093. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7094. }
  7095. var classStore = getMergedStore(destination);
  7096. // Properties
  7097. for (var property in classStore) {
  7098. var propertyDescriptor = classStore[property];
  7099. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7100. var propertyType = propertyDescriptor.type;
  7101. if (sourceProperty !== undefined && sourceProperty !== null) {
  7102. var dest = destination;
  7103. switch (propertyType) {
  7104. case 0:// Value
  7105. dest[property] = sourceProperty;
  7106. break;
  7107. case 1:// Texture
  7108. if (scene) {
  7109. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7110. }
  7111. break;
  7112. case 2:// Color3
  7113. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7114. break;
  7115. case 3:// FresnelParameters
  7116. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7117. break;
  7118. case 4:// Vector2
  7119. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7120. break;
  7121. case 5:// Vector3
  7122. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7123. break;
  7124. case 6:// Mesh reference
  7125. if (scene) {
  7126. dest[property] = scene.getLastMeshByID(sourceProperty);
  7127. }
  7128. break;
  7129. case 7:// Color Curves
  7130. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7131. break;
  7132. case 8:// Color 4
  7133. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7134. break;
  7135. case 9:// Image Processing
  7136. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7137. break;
  7138. }
  7139. }
  7140. }
  7141. return destination;
  7142. };
  7143. SerializationHelper.Clone = function (creationFunction, source) {
  7144. return _copySource(creationFunction, source, false);
  7145. };
  7146. SerializationHelper.Instanciate = function (creationFunction, source) {
  7147. return _copySource(creationFunction, source, true);
  7148. };
  7149. return SerializationHelper;
  7150. }());
  7151. BABYLON.SerializationHelper = SerializationHelper;
  7152. })(BABYLON || (BABYLON = {}));
  7153. //# sourceMappingURL=babylon.decorators.js.map
  7154. var BABYLON;
  7155. (function (BABYLON) {
  7156. /**
  7157. * Wrapper class for promise with external resolve and reject.
  7158. */
  7159. var Deferred = /** @class */ (function () {
  7160. /**
  7161. * Constructor for this deferred object.
  7162. */
  7163. function Deferred() {
  7164. var _this = this;
  7165. this.promise = new Promise(function (resolve, reject) {
  7166. _this._resolve = resolve;
  7167. _this._reject = reject;
  7168. });
  7169. }
  7170. Object.defineProperty(Deferred.prototype, "resolve", {
  7171. /**
  7172. * The resolve method of the promise associated with this deferred object.
  7173. */
  7174. get: function () {
  7175. return this._resolve;
  7176. },
  7177. enumerable: true,
  7178. configurable: true
  7179. });
  7180. Object.defineProperty(Deferred.prototype, "reject", {
  7181. /**
  7182. * The reject method of the promise associated with this deferred object.
  7183. */
  7184. get: function () {
  7185. return this._reject;
  7186. },
  7187. enumerable: true,
  7188. configurable: true
  7189. });
  7190. return Deferred;
  7191. }());
  7192. BABYLON.Deferred = Deferred;
  7193. })(BABYLON || (BABYLON = {}));
  7194. //# sourceMappingURL=babylon.deferred.js.map
  7195. var BABYLON;
  7196. (function (BABYLON) {
  7197. /**
  7198. * A class serves as a medium between the observable and its observers
  7199. */
  7200. var EventState = /** @class */ (function () {
  7201. /**
  7202. * Create a new EventState
  7203. * @param mask defines the mask associated with this state
  7204. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7205. * @param target defines the original target of the state
  7206. * @param currentTarget defines the current target of the state
  7207. */
  7208. function EventState(mask, skipNextObservers, target, currentTarget) {
  7209. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7210. this.initalize(mask, skipNextObservers, target, currentTarget);
  7211. }
  7212. /**
  7213. * Initialize the current event state
  7214. * @param mask defines the mask associated with this state
  7215. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7216. * @param target defines the original target of the state
  7217. * @param currentTarget defines the current target of the state
  7218. * @returns the current event state
  7219. */
  7220. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7221. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7222. this.mask = mask;
  7223. this.skipNextObservers = skipNextObservers;
  7224. this.target = target;
  7225. this.currentTarget = currentTarget;
  7226. return this;
  7227. };
  7228. return EventState;
  7229. }());
  7230. BABYLON.EventState = EventState;
  7231. /**
  7232. * Represent an Observer registered to a given Observable object.
  7233. */
  7234. var Observer = /** @class */ (function () {
  7235. /**
  7236. * Creates a new observer
  7237. * @param callback defines the callback to call when the observer is notified
  7238. * @param mask defines the mask of the observer (used to filter notifications)
  7239. * @param scope defines the current scope used to restore the JS context
  7240. */
  7241. function Observer(
  7242. /**
  7243. * Defines the callback to call when the observer is notified
  7244. */
  7245. callback,
  7246. /**
  7247. * Defines the mask of the observer (used to filter notifications)
  7248. */
  7249. mask,
  7250. /**
  7251. * Defines the current scope used to restore the JS context
  7252. */
  7253. scope) {
  7254. if (scope === void 0) { scope = null; }
  7255. this.callback = callback;
  7256. this.mask = mask;
  7257. this.scope = scope;
  7258. /** @ignore */
  7259. this._willBeUnregistered = false;
  7260. /**
  7261. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7262. */
  7263. this.unregisterOnNextCall = false;
  7264. }
  7265. return Observer;
  7266. }());
  7267. BABYLON.Observer = Observer;
  7268. /**
  7269. * Represent a list of observers registered to multiple Observables object.
  7270. */
  7271. var MultiObserver = /** @class */ (function () {
  7272. function MultiObserver() {
  7273. }
  7274. /**
  7275. * Release associated resources
  7276. */
  7277. MultiObserver.prototype.dispose = function () {
  7278. if (this._observers && this._observables) {
  7279. for (var index = 0; index < this._observers.length; index++) {
  7280. this._observables[index].remove(this._observers[index]);
  7281. }
  7282. }
  7283. this._observers = null;
  7284. this._observables = null;
  7285. };
  7286. /**
  7287. * Raise a callback when one of the observable will notify
  7288. * @param observables defines a list of observables to watch
  7289. * @param callback defines the callback to call on notification
  7290. * @param mask defines the mask used to filter notifications
  7291. * @param scope defines the current scope used to restore the JS context
  7292. * @returns the new MultiObserver
  7293. */
  7294. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7295. if (mask === void 0) { mask = -1; }
  7296. if (scope === void 0) { scope = null; }
  7297. var result = new MultiObserver();
  7298. result._observers = new Array();
  7299. result._observables = observables;
  7300. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7301. var observable = observables_1[_i];
  7302. var observer = observable.add(callback, mask, false, scope);
  7303. if (observer) {
  7304. result._observers.push(observer);
  7305. }
  7306. }
  7307. return result;
  7308. };
  7309. return MultiObserver;
  7310. }());
  7311. BABYLON.MultiObserver = MultiObserver;
  7312. /**
  7313. * The Observable class is a simple implementation of the Observable pattern.
  7314. * 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.
  7315. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7316. * 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).
  7317. * 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.
  7318. */
  7319. var Observable = /** @class */ (function () {
  7320. /**
  7321. * Creates a new observable
  7322. * @param onObserverAdded defines a callback to call when a new observer is added
  7323. */
  7324. function Observable(onObserverAdded) {
  7325. this._observers = new Array();
  7326. this._eventState = new EventState(0);
  7327. if (onObserverAdded) {
  7328. this._onObserverAdded = onObserverAdded;
  7329. }
  7330. }
  7331. /**
  7332. * Create a new Observer with the specified callback
  7333. * @param callback the callback that will be executed for that Observer
  7334. * @param mask the mask used to filter observers
  7335. * @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.
  7336. * @param scope optional scope for the callback to be called from
  7337. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7338. * @returns the new observer created for the callback
  7339. */
  7340. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7341. if (mask === void 0) { mask = -1; }
  7342. if (insertFirst === void 0) { insertFirst = false; }
  7343. if (scope === void 0) { scope = null; }
  7344. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7345. if (!callback) {
  7346. return null;
  7347. }
  7348. var observer = new Observer(callback, mask, scope);
  7349. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7350. if (insertFirst) {
  7351. this._observers.unshift(observer);
  7352. }
  7353. else {
  7354. this._observers.push(observer);
  7355. }
  7356. if (this._onObserverAdded) {
  7357. this._onObserverAdded(observer);
  7358. }
  7359. return observer;
  7360. };
  7361. /**
  7362. * Remove an Observer from the Observable object
  7363. * @param observer the instance of the Observer to remove
  7364. * @returns false if it doesn't belong to this Observable
  7365. */
  7366. Observable.prototype.remove = function (observer) {
  7367. if (!observer) {
  7368. return false;
  7369. }
  7370. var index = this._observers.indexOf(observer);
  7371. if (index !== -1) {
  7372. this._observers.splice(index, 1);
  7373. return true;
  7374. }
  7375. return false;
  7376. };
  7377. /**
  7378. * Remove a callback from the Observable object
  7379. * @param callback the callback to remove
  7380. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7381. * @returns false if it doesn't belong to this Observable
  7382. */
  7383. Observable.prototype.removeCallback = function (callback, scope) {
  7384. for (var index = 0; index < this._observers.length; index++) {
  7385. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7386. this._observers.splice(index, 1);
  7387. return true;
  7388. }
  7389. }
  7390. return false;
  7391. };
  7392. Observable.prototype._deferUnregister = function (observer) {
  7393. var _this = this;
  7394. observer.unregisterOnNextCall = false;
  7395. observer._willBeUnregistered = true;
  7396. BABYLON.Tools.SetImmediate(function () {
  7397. _this.remove(observer);
  7398. });
  7399. };
  7400. /**
  7401. * Notify all Observers by calling their respective callback with the given data
  7402. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7403. * @param eventData defines the data to send to all observers
  7404. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7405. * @param target defines the original target of the state
  7406. * @param currentTarget defines the current target of the state
  7407. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7408. */
  7409. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7410. if (mask === void 0) { mask = -1; }
  7411. if (!this._observers.length) {
  7412. return true;
  7413. }
  7414. var state = this._eventState;
  7415. state.mask = mask;
  7416. state.target = target;
  7417. state.currentTarget = currentTarget;
  7418. state.skipNextObservers = false;
  7419. state.lastReturnValue = eventData;
  7420. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7421. var obs = _a[_i];
  7422. if (obs._willBeUnregistered) {
  7423. continue;
  7424. }
  7425. if (obs.mask & mask) {
  7426. if (obs.scope) {
  7427. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7428. }
  7429. else {
  7430. state.lastReturnValue = obs.callback(eventData, state);
  7431. }
  7432. if (obs.unregisterOnNextCall) {
  7433. this._deferUnregister(obs);
  7434. }
  7435. }
  7436. if (state.skipNextObservers) {
  7437. return false;
  7438. }
  7439. }
  7440. return true;
  7441. };
  7442. /**
  7443. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7444. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7445. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7446. * and it is crucial that all callbacks will be executed.
  7447. * The order of the callbacks is kept, callbacks are not executed parallel.
  7448. *
  7449. * @param eventData The data to be sent to each callback
  7450. * @param mask is used to filter observers defaults to -1
  7451. * @param target defines the callback target (see EventState)
  7452. * @param currentTarget defines he current object in the bubbling phase
  7453. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7454. */
  7455. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7456. var _this = this;
  7457. if (mask === void 0) { mask = -1; }
  7458. // create an empty promise
  7459. var p = Promise.resolve(eventData);
  7460. // no observers? return this promise.
  7461. if (!this._observers.length) {
  7462. return p;
  7463. }
  7464. var state = this._eventState;
  7465. state.mask = mask;
  7466. state.target = target;
  7467. state.currentTarget = currentTarget;
  7468. state.skipNextObservers = false;
  7469. // execute one callback after another (not using Promise.all, the order is important)
  7470. this._observers.forEach(function (obs) {
  7471. if (state.skipNextObservers) {
  7472. return;
  7473. }
  7474. if (obs._willBeUnregistered) {
  7475. return;
  7476. }
  7477. if (obs.mask & mask) {
  7478. if (obs.scope) {
  7479. p = p.then(function (lastReturnedValue) {
  7480. state.lastReturnValue = lastReturnedValue;
  7481. return obs.callback.apply(obs.scope, [eventData, state]);
  7482. });
  7483. }
  7484. else {
  7485. p = p.then(function (lastReturnedValue) {
  7486. state.lastReturnValue = lastReturnedValue;
  7487. return obs.callback(eventData, state);
  7488. });
  7489. }
  7490. if (obs.unregisterOnNextCall) {
  7491. _this._deferUnregister(obs);
  7492. }
  7493. }
  7494. });
  7495. // return the eventData
  7496. return p.then(function () { return eventData; });
  7497. };
  7498. /**
  7499. * Notify a specific observer
  7500. * @param observer defines the observer to notify
  7501. * @param eventData defines the data to be sent to each callback
  7502. * @param mask is used to filter observers defaults to -1
  7503. */
  7504. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7505. if (mask === void 0) { mask = -1; }
  7506. var state = this._eventState;
  7507. state.mask = mask;
  7508. state.skipNextObservers = false;
  7509. observer.callback(eventData, state);
  7510. };
  7511. /**
  7512. * Gets a boolean indicating if the observable has at least one observer
  7513. * @returns true is the Observable has at least one Observer registered
  7514. */
  7515. Observable.prototype.hasObservers = function () {
  7516. return this._observers.length > 0;
  7517. };
  7518. /**
  7519. * Clear the list of observers
  7520. */
  7521. Observable.prototype.clear = function () {
  7522. this._observers = new Array();
  7523. this._onObserverAdded = null;
  7524. };
  7525. /**
  7526. * Clone the current observable
  7527. * @returns a new observable
  7528. */
  7529. Observable.prototype.clone = function () {
  7530. var result = new Observable();
  7531. result._observers = this._observers.slice(0);
  7532. return result;
  7533. };
  7534. /**
  7535. * Does this observable handles observer registered with a given mask
  7536. * @param mask defines the mask to be tested
  7537. * @return whether or not one observer registered with the given mask is handeled
  7538. **/
  7539. Observable.prototype.hasSpecificMask = function (mask) {
  7540. if (mask === void 0) { mask = -1; }
  7541. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7542. var obs = _a[_i];
  7543. if (obs.mask & mask || obs.mask === mask) {
  7544. return true;
  7545. }
  7546. }
  7547. return false;
  7548. };
  7549. return Observable;
  7550. }());
  7551. BABYLON.Observable = Observable;
  7552. })(BABYLON || (BABYLON = {}));
  7553. //# sourceMappingURL=babylon.observable.js.map
  7554. var BABYLON;
  7555. (function (BABYLON) {
  7556. var SmartArray = /** @class */ (function () {
  7557. function SmartArray(capacity) {
  7558. this.length = 0;
  7559. this.data = new Array(capacity);
  7560. this._id = SmartArray._GlobalId++;
  7561. }
  7562. SmartArray.prototype.push = function (value) {
  7563. this.data[this.length++] = value;
  7564. if (this.length > this.data.length) {
  7565. this.data.length *= 2;
  7566. }
  7567. };
  7568. SmartArray.prototype.forEach = function (func) {
  7569. for (var index = 0; index < this.length; index++) {
  7570. func(this.data[index]);
  7571. }
  7572. };
  7573. SmartArray.prototype.sort = function (compareFn) {
  7574. this.data.sort(compareFn);
  7575. };
  7576. SmartArray.prototype.reset = function () {
  7577. this.length = 0;
  7578. };
  7579. SmartArray.prototype.dispose = function () {
  7580. this.reset();
  7581. if (this.data) {
  7582. this.data.length = 0;
  7583. this.data = [];
  7584. }
  7585. };
  7586. SmartArray.prototype.concat = function (array) {
  7587. if (array.length === 0) {
  7588. return;
  7589. }
  7590. if (this.length + array.length > this.data.length) {
  7591. this.data.length = (this.length + array.length) * 2;
  7592. }
  7593. for (var index = 0; index < array.length; index++) {
  7594. this.data[this.length++] = (array.data || array)[index];
  7595. }
  7596. };
  7597. SmartArray.prototype.indexOf = function (value) {
  7598. var position = this.data.indexOf(value);
  7599. if (position >= this.length) {
  7600. return -1;
  7601. }
  7602. return position;
  7603. };
  7604. SmartArray.prototype.contains = function (value) {
  7605. return this.data.indexOf(value) !== -1;
  7606. };
  7607. // Statics
  7608. SmartArray._GlobalId = 0;
  7609. return SmartArray;
  7610. }());
  7611. BABYLON.SmartArray = SmartArray;
  7612. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7613. __extends(SmartArrayNoDuplicate, _super);
  7614. function SmartArrayNoDuplicate() {
  7615. var _this = _super !== null && _super.apply(this, arguments) || this;
  7616. _this._duplicateId = 0;
  7617. return _this;
  7618. }
  7619. SmartArrayNoDuplicate.prototype.push = function (value) {
  7620. _super.prototype.push.call(this, value);
  7621. if (!value.__smartArrayFlags) {
  7622. value.__smartArrayFlags = {};
  7623. }
  7624. value.__smartArrayFlags[this._id] = this._duplicateId;
  7625. };
  7626. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7627. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7628. return false;
  7629. }
  7630. this.push(value);
  7631. return true;
  7632. };
  7633. SmartArrayNoDuplicate.prototype.reset = function () {
  7634. _super.prototype.reset.call(this);
  7635. this._duplicateId++;
  7636. };
  7637. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7638. if (array.length === 0) {
  7639. return;
  7640. }
  7641. if (this.length + array.length > this.data.length) {
  7642. this.data.length = (this.length + array.length) * 2;
  7643. }
  7644. for (var index = 0; index < array.length; index++) {
  7645. var item = (array.data || array)[index];
  7646. this.pushNoDuplicate(item);
  7647. }
  7648. };
  7649. return SmartArrayNoDuplicate;
  7650. }(SmartArray));
  7651. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7652. })(BABYLON || (BABYLON = {}));
  7653. //# sourceMappingURL=babylon.smartArray.js.map
  7654. var BABYLON;
  7655. (function (BABYLON) {
  7656. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7657. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7658. var LoadFileError = /** @class */ (function (_super) {
  7659. __extends(LoadFileError, _super);
  7660. function LoadFileError(message, request) {
  7661. var _this = _super.call(this, message) || this;
  7662. _this.request = request;
  7663. _this.name = "LoadFileError";
  7664. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7665. return _this;
  7666. }
  7667. // Polyfill for Object.setPrototypeOf if necessary.
  7668. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7669. return LoadFileError;
  7670. }(Error));
  7671. BABYLON.LoadFileError = LoadFileError;
  7672. var RetryStrategy = /** @class */ (function () {
  7673. function RetryStrategy() {
  7674. }
  7675. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7676. if (maxRetries === void 0) { maxRetries = 3; }
  7677. if (baseInterval === void 0) { baseInterval = 500; }
  7678. return function (url, request, retryIndex) {
  7679. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7680. return -1;
  7681. }
  7682. return Math.pow(2, retryIndex) * baseInterval;
  7683. };
  7684. };
  7685. return RetryStrategy;
  7686. }());
  7687. BABYLON.RetryStrategy = RetryStrategy;
  7688. // Screenshots
  7689. var screenshotCanvas;
  7690. var cloneValue = function (source, destinationObject) {
  7691. if (!source)
  7692. return null;
  7693. if (source instanceof BABYLON.Mesh) {
  7694. return null;
  7695. }
  7696. if (source instanceof BABYLON.SubMesh) {
  7697. return source.clone(destinationObject);
  7698. }
  7699. else if (source.clone) {
  7700. return source.clone();
  7701. }
  7702. return null;
  7703. };
  7704. var Tools = /** @class */ (function () {
  7705. function Tools() {
  7706. }
  7707. /**
  7708. * Interpolates between a and b via alpha
  7709. * @param a The lower value (returned when alpha = 0)
  7710. * @param b The upper value (returned when alpha = 1)
  7711. * @param alpha The interpolation-factor
  7712. * @return The mixed value
  7713. */
  7714. Tools.Mix = function (a, b, alpha) {
  7715. return a * (1 - alpha) + b * alpha;
  7716. };
  7717. Tools.Instantiate = function (className) {
  7718. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7719. return Tools.RegisteredExternalClasses[className];
  7720. }
  7721. var arr = className.split(".");
  7722. var fn = (window || this);
  7723. for (var i = 0, len = arr.length; i < len; i++) {
  7724. fn = fn[arr[i]];
  7725. }
  7726. if (typeof fn !== "function") {
  7727. return null;
  7728. }
  7729. return fn;
  7730. };
  7731. /**
  7732. * Provides a slice function that will work even on IE
  7733. * @param data defines the array to slice
  7734. * @returns the new sliced array
  7735. */
  7736. Tools.Slice = function (data) {
  7737. if (data.slice) {
  7738. return data.slice();
  7739. }
  7740. return Array.prototype.slice.call(data);
  7741. };
  7742. Tools.SetImmediate = function (action) {
  7743. if (window.setImmediate) {
  7744. window.setImmediate(action);
  7745. }
  7746. else {
  7747. setTimeout(action, 1);
  7748. }
  7749. };
  7750. Tools.IsExponentOfTwo = function (value) {
  7751. var count = 1;
  7752. do {
  7753. count *= 2;
  7754. } while (count < value);
  7755. return count === value;
  7756. };
  7757. /**
  7758. * Find the next highest power of two.
  7759. * @param x Number to start search from.
  7760. * @return Next highest power of two.
  7761. */
  7762. Tools.CeilingPOT = function (x) {
  7763. x--;
  7764. x |= x >> 1;
  7765. x |= x >> 2;
  7766. x |= x >> 4;
  7767. x |= x >> 8;
  7768. x |= x >> 16;
  7769. x++;
  7770. return x;
  7771. };
  7772. /**
  7773. * Find the next lowest power of two.
  7774. * @param x Number to start search from.
  7775. * @return Next lowest power of two.
  7776. */
  7777. Tools.FloorPOT = function (x) {
  7778. x = x | (x >> 1);
  7779. x = x | (x >> 2);
  7780. x = x | (x >> 4);
  7781. x = x | (x >> 8);
  7782. x = x | (x >> 16);
  7783. return x - (x >> 1);
  7784. };
  7785. /**
  7786. * Find the nearest power of two.
  7787. * @param x Number to start search from.
  7788. * @return Next nearest power of two.
  7789. */
  7790. Tools.NearestPOT = function (x) {
  7791. var c = Tools.CeilingPOT(x);
  7792. var f = Tools.FloorPOT(x);
  7793. return (c - x) > (x - f) ? f : c;
  7794. };
  7795. Tools.GetExponentOfTwo = function (value, max, mode) {
  7796. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7797. var pot;
  7798. switch (mode) {
  7799. case BABYLON.Engine.SCALEMODE_FLOOR:
  7800. pot = Tools.FloorPOT(value);
  7801. break;
  7802. case BABYLON.Engine.SCALEMODE_NEAREST:
  7803. pot = Tools.NearestPOT(value);
  7804. break;
  7805. case BABYLON.Engine.SCALEMODE_CEILING:
  7806. default:
  7807. pot = Tools.CeilingPOT(value);
  7808. break;
  7809. }
  7810. return Math.min(pot, max);
  7811. };
  7812. Tools.GetFilename = function (path) {
  7813. var index = path.lastIndexOf("/");
  7814. if (index < 0)
  7815. return path;
  7816. return path.substring(index + 1);
  7817. };
  7818. /**
  7819. * Extracts the "folder" part of a path (everything before the filename).
  7820. * @param uri The URI to extract the info from
  7821. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7822. * @returns The "folder" part of the path
  7823. */
  7824. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7825. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7826. var index = uri.lastIndexOf("/");
  7827. if (index < 0) {
  7828. if (returnUnchangedIfNoSlash) {
  7829. return uri;
  7830. }
  7831. return "";
  7832. }
  7833. return uri.substring(0, index + 1);
  7834. };
  7835. Tools.GetDOMTextContent = function (element) {
  7836. var result = "";
  7837. var child = element.firstChild;
  7838. while (child) {
  7839. if (child.nodeType === 3) {
  7840. result += child.textContent;
  7841. }
  7842. child = child.nextSibling;
  7843. }
  7844. return result;
  7845. };
  7846. Tools.ToDegrees = function (angle) {
  7847. return angle * 180 / Math.PI;
  7848. };
  7849. Tools.ToRadians = function (angle) {
  7850. return angle * Math.PI / 180;
  7851. };
  7852. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7853. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7854. var output = "";
  7855. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7856. var i = 0;
  7857. var bytes = new Uint8Array(buffer);
  7858. while (i < bytes.length) {
  7859. chr1 = bytes[i++];
  7860. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7861. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7862. enc1 = chr1 >> 2;
  7863. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7864. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7865. enc4 = chr3 & 63;
  7866. if (isNaN(chr2)) {
  7867. enc3 = enc4 = 64;
  7868. }
  7869. else if (isNaN(chr3)) {
  7870. enc4 = 64;
  7871. }
  7872. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7873. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7874. }
  7875. return "data:image/png;base64," + output;
  7876. };
  7877. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7878. if (bias === void 0) { bias = null; }
  7879. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7880. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7881. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7882. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7883. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7884. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7885. }
  7886. if (bias) {
  7887. minimum.x -= minimum.x * bias.x + bias.y;
  7888. minimum.y -= minimum.y * bias.x + bias.y;
  7889. minimum.z -= minimum.z * bias.x + bias.y;
  7890. maximum.x += maximum.x * bias.x + bias.y;
  7891. maximum.y += maximum.y * bias.x + bias.y;
  7892. maximum.z += maximum.z * bias.x + bias.y;
  7893. }
  7894. return {
  7895. minimum: minimum,
  7896. maximum: maximum
  7897. };
  7898. };
  7899. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7900. if (bias === void 0) { bias = null; }
  7901. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7902. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7903. if (!stride) {
  7904. stride = 3;
  7905. }
  7906. for (var index = start; index < start + count; index++) {
  7907. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7908. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7909. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7910. }
  7911. if (bias) {
  7912. minimum.x -= minimum.x * bias.x + bias.y;
  7913. minimum.y -= minimum.y * bias.x + bias.y;
  7914. minimum.z -= minimum.z * bias.x + bias.y;
  7915. maximum.x += maximum.x * bias.x + bias.y;
  7916. maximum.y += maximum.y * bias.x + bias.y;
  7917. maximum.z += maximum.z * bias.x + bias.y;
  7918. }
  7919. return {
  7920. minimum: minimum,
  7921. maximum: maximum
  7922. };
  7923. };
  7924. Tools.Vector2ArrayFeeder = function (array) {
  7925. return function (index) {
  7926. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7927. var length = isFloatArray ? array.length / 2 : array.length;
  7928. if (index >= length) {
  7929. return null;
  7930. }
  7931. if (isFloatArray) {
  7932. var fa = array;
  7933. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7934. }
  7935. var a = array;
  7936. return a[index];
  7937. };
  7938. };
  7939. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7940. if (bias === void 0) { bias = null; }
  7941. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7942. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7943. var i = 0;
  7944. var cur = feeder(i++);
  7945. while (cur) {
  7946. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7947. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7948. cur = feeder(i++);
  7949. }
  7950. if (bias) {
  7951. minimum.x -= minimum.x * bias.x + bias.y;
  7952. minimum.y -= minimum.y * bias.x + bias.y;
  7953. maximum.x += maximum.x * bias.x + bias.y;
  7954. maximum.y += maximum.y * bias.x + bias.y;
  7955. }
  7956. return {
  7957. minimum: minimum,
  7958. maximum: maximum
  7959. };
  7960. };
  7961. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7962. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7963. return null;
  7964. return Array.isArray(obj) ? obj : [obj];
  7965. };
  7966. // Misc.
  7967. Tools.GetPointerPrefix = function () {
  7968. var eventPrefix = "pointer";
  7969. // Check if pointer events are supported
  7970. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7971. eventPrefix = "mouse";
  7972. }
  7973. return eventPrefix;
  7974. };
  7975. /**
  7976. * @param func - the function to be called
  7977. * @param requester - the object that will request the next frame. Falls back to window.
  7978. */
  7979. Tools.QueueNewFrame = function (func, requester) {
  7980. if (!Tools.IsWindowObjectExist()) {
  7981. return setTimeout(func, 16);
  7982. }
  7983. if (!requester) {
  7984. requester = window;
  7985. }
  7986. if (requester.requestAnimationFrame) {
  7987. return requester.requestAnimationFrame(func);
  7988. }
  7989. else if (requester.msRequestAnimationFrame) {
  7990. return requester.msRequestAnimationFrame(func);
  7991. }
  7992. else if (requester.webkitRequestAnimationFrame) {
  7993. return requester.webkitRequestAnimationFrame(func);
  7994. }
  7995. else if (requester.mozRequestAnimationFrame) {
  7996. return requester.mozRequestAnimationFrame(func);
  7997. }
  7998. else if (requester.oRequestAnimationFrame) {
  7999. return requester.oRequestAnimationFrame(func);
  8000. }
  8001. else {
  8002. return window.setTimeout(func, 16);
  8003. }
  8004. };
  8005. Tools.RequestFullscreen = function (element) {
  8006. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8007. if (!requestFunction)
  8008. return;
  8009. requestFunction.call(element);
  8010. };
  8011. Tools.ExitFullscreen = function () {
  8012. if (document.exitFullscreen) {
  8013. document.exitFullscreen();
  8014. }
  8015. else if (document.mozCancelFullScreen) {
  8016. document.mozCancelFullScreen();
  8017. }
  8018. else if (document.webkitCancelFullScreen) {
  8019. document.webkitCancelFullScreen();
  8020. }
  8021. else if (document.msCancelFullScreen) {
  8022. document.msCancelFullScreen();
  8023. }
  8024. };
  8025. Tools.SetCorsBehavior = function (url, element) {
  8026. if (url && url.indexOf("data:") === 0) {
  8027. return;
  8028. }
  8029. if (Tools.CorsBehavior) {
  8030. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8031. element.crossOrigin = Tools.CorsBehavior;
  8032. }
  8033. else {
  8034. var result = Tools.CorsBehavior(url);
  8035. if (result) {
  8036. element.crossOrigin = result;
  8037. }
  8038. }
  8039. }
  8040. };
  8041. // External files
  8042. Tools.CleanUrl = function (url) {
  8043. url = url.replace(/#/mg, "%23");
  8044. return url;
  8045. };
  8046. Tools.LoadImage = function (url, onLoad, onError, database) {
  8047. if (url instanceof ArrayBuffer) {
  8048. url = Tools.EncodeArrayBufferTobase64(url);
  8049. }
  8050. url = Tools.CleanUrl(url);
  8051. url = Tools.PreprocessUrl(url);
  8052. var img = new Image();
  8053. Tools.SetCorsBehavior(url, img);
  8054. var loadHandler = function () {
  8055. img.removeEventListener("load", loadHandler);
  8056. img.removeEventListener("error", errorHandler);
  8057. onLoad(img);
  8058. };
  8059. var errorHandler = function (err) {
  8060. img.removeEventListener("load", loadHandler);
  8061. img.removeEventListener("error", errorHandler);
  8062. Tools.Error("Error while trying to load image: " + url);
  8063. if (onError) {
  8064. onError("Error while trying to load image: " + url, err);
  8065. }
  8066. };
  8067. img.addEventListener("load", loadHandler);
  8068. img.addEventListener("error", errorHandler);
  8069. var noIndexedDB = function () {
  8070. img.src = url;
  8071. };
  8072. var loadFromIndexedDB = function () {
  8073. if (database) {
  8074. database.loadImageFromDB(url, img);
  8075. }
  8076. };
  8077. //ANY database to do!
  8078. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8079. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8080. }
  8081. else {
  8082. if (url.indexOf("file:") !== -1) {
  8083. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8084. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8085. try {
  8086. var blobURL;
  8087. try {
  8088. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8089. }
  8090. catch (ex) {
  8091. // Chrome doesn't support oneTimeOnly parameter
  8092. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8093. }
  8094. img.src = blobURL;
  8095. }
  8096. catch (e) {
  8097. img.src = "";
  8098. }
  8099. return img;
  8100. }
  8101. }
  8102. noIndexedDB();
  8103. }
  8104. return img;
  8105. };
  8106. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8107. url = Tools.CleanUrl(url);
  8108. url = Tools.PreprocessUrl(url);
  8109. // If file and file input are set
  8110. if (url.indexOf("file:") !== -1) {
  8111. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8112. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8113. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8114. }
  8115. }
  8116. var loadUrl = Tools.BaseUrl + url;
  8117. var aborted = false;
  8118. var fileRequest = {
  8119. onCompleteObservable: new BABYLON.Observable(),
  8120. abort: function () { return aborted = true; },
  8121. };
  8122. var requestFile = function () {
  8123. var request = new XMLHttpRequest();
  8124. var retryHandle = null;
  8125. fileRequest.abort = function () {
  8126. aborted = true;
  8127. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8128. request.abort();
  8129. }
  8130. if (retryHandle !== null) {
  8131. clearTimeout(retryHandle);
  8132. retryHandle = null;
  8133. }
  8134. };
  8135. var retryLoop = function (retryIndex) {
  8136. request.open('GET', loadUrl, true);
  8137. if (useArrayBuffer) {
  8138. request.responseType = "arraybuffer";
  8139. }
  8140. if (onProgress) {
  8141. request.addEventListener("progress", onProgress);
  8142. }
  8143. var onLoadEnd = function () {
  8144. request.removeEventListener("loadend", onLoadEnd);
  8145. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8146. fileRequest.onCompleteObservable.clear();
  8147. };
  8148. request.addEventListener("loadend", onLoadEnd);
  8149. var onReadyStateChange = function () {
  8150. if (aborted) {
  8151. return;
  8152. }
  8153. // In case of undefined state in some browsers.
  8154. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8155. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8156. request.removeEventListener("readystatechange", onReadyStateChange);
  8157. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8158. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8159. return;
  8160. }
  8161. var retryStrategy = Tools.DefaultRetryStrategy;
  8162. if (retryStrategy) {
  8163. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8164. if (waitTime !== -1) {
  8165. // Prevent the request from completing for retry.
  8166. request.removeEventListener("loadend", onLoadEnd);
  8167. request = new XMLHttpRequest();
  8168. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8169. return;
  8170. }
  8171. }
  8172. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8173. if (onError) {
  8174. onError(request, e);
  8175. }
  8176. else {
  8177. throw e;
  8178. }
  8179. }
  8180. };
  8181. request.addEventListener("readystatechange", onReadyStateChange);
  8182. request.send();
  8183. };
  8184. retryLoop(0);
  8185. };
  8186. // Caching all files
  8187. if (database && database.enableSceneOffline) {
  8188. var noIndexedDB_1 = function () {
  8189. if (!aborted) {
  8190. requestFile();
  8191. }
  8192. };
  8193. var loadFromIndexedDB = function () {
  8194. // TODO: database needs to support aborting and should return a IFileRequest
  8195. if (aborted) {
  8196. return;
  8197. }
  8198. if (database) {
  8199. database.loadFileFromDB(url, function (data) {
  8200. if (!aborted) {
  8201. onSuccess(data);
  8202. }
  8203. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8204. }, onProgress ? function (event) {
  8205. if (!aborted) {
  8206. onProgress(event);
  8207. }
  8208. } : undefined, noIndexedDB_1, useArrayBuffer);
  8209. }
  8210. };
  8211. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8212. }
  8213. else {
  8214. requestFile();
  8215. }
  8216. return fileRequest;
  8217. };
  8218. /**
  8219. * Load a script (identified by an url). When the url returns, the
  8220. * content of this file is added into a new script element, attached to the DOM (body element)
  8221. */
  8222. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8223. var head = document.getElementsByTagName('head')[0];
  8224. var script = document.createElement('script');
  8225. script.type = 'text/javascript';
  8226. script.src = scriptUrl;
  8227. script.onload = function () {
  8228. if (onSuccess) {
  8229. onSuccess();
  8230. }
  8231. };
  8232. script.onerror = function (e) {
  8233. if (onError) {
  8234. onError("Unable to load script", e);
  8235. }
  8236. };
  8237. head.appendChild(script);
  8238. };
  8239. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8240. var reader = new FileReader();
  8241. var request = {
  8242. onCompleteObservable: new BABYLON.Observable(),
  8243. abort: function () { return reader.abort(); },
  8244. };
  8245. reader.onloadend = function (e) {
  8246. request.onCompleteObservable.notifyObservers(request);
  8247. };
  8248. reader.onload = function (e) {
  8249. //target doesn't have result from ts 1.3
  8250. callback(e.target['result']);
  8251. };
  8252. reader.onprogress = progressCallback;
  8253. reader.readAsDataURL(fileToLoad);
  8254. return request;
  8255. };
  8256. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8257. var reader = new FileReader();
  8258. var request = {
  8259. onCompleteObservable: new BABYLON.Observable(),
  8260. abort: function () { return reader.abort(); },
  8261. };
  8262. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8263. reader.onerror = function (e) {
  8264. Tools.Log("Error while reading file: " + fileToLoad.name);
  8265. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8266. };
  8267. reader.onload = function (e) {
  8268. //target doesn't have result from ts 1.3
  8269. callback(e.target['result']);
  8270. };
  8271. if (progressCallBack) {
  8272. reader.onprogress = progressCallBack;
  8273. }
  8274. if (!useArrayBuffer) {
  8275. // Asynchronous read
  8276. reader.readAsText(fileToLoad);
  8277. }
  8278. else {
  8279. reader.readAsArrayBuffer(fileToLoad);
  8280. }
  8281. return request;
  8282. };
  8283. //returns a downloadable url to a file content.
  8284. Tools.FileAsURL = function (content) {
  8285. var fileBlob = new Blob([content]);
  8286. var url = window.URL || window.webkitURL;
  8287. var link = url.createObjectURL(fileBlob);
  8288. return link;
  8289. };
  8290. // Misc.
  8291. Tools.Format = function (value, decimals) {
  8292. if (decimals === void 0) { decimals = 2; }
  8293. return value.toFixed(decimals);
  8294. };
  8295. Tools.CheckExtends = function (v, min, max) {
  8296. if (v.x < min.x)
  8297. min.x = v.x;
  8298. if (v.y < min.y)
  8299. min.y = v.y;
  8300. if (v.z < min.z)
  8301. min.z = v.z;
  8302. if (v.x > max.x)
  8303. max.x = v.x;
  8304. if (v.y > max.y)
  8305. max.y = v.y;
  8306. if (v.z > max.z)
  8307. max.z = v.z;
  8308. };
  8309. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8310. for (var prop in source) {
  8311. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8312. continue;
  8313. }
  8314. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8315. continue;
  8316. }
  8317. var sourceValue = source[prop];
  8318. var typeOfSourceValue = typeof sourceValue;
  8319. if (typeOfSourceValue === "function") {
  8320. continue;
  8321. }
  8322. if (typeOfSourceValue === "object") {
  8323. if (sourceValue instanceof Array) {
  8324. destination[prop] = [];
  8325. if (sourceValue.length > 0) {
  8326. if (typeof sourceValue[0] == "object") {
  8327. for (var index = 0; index < sourceValue.length; index++) {
  8328. var clonedValue = cloneValue(sourceValue[index], destination);
  8329. if (destination[prop].indexOf(clonedValue) === -1) {
  8330. destination[prop].push(clonedValue);
  8331. }
  8332. }
  8333. }
  8334. else {
  8335. destination[prop] = sourceValue.slice(0);
  8336. }
  8337. }
  8338. }
  8339. else {
  8340. destination[prop] = cloneValue(sourceValue, destination);
  8341. }
  8342. }
  8343. else {
  8344. destination[prop] = sourceValue;
  8345. }
  8346. }
  8347. };
  8348. Tools.IsEmpty = function (obj) {
  8349. for (var i in obj) {
  8350. if (obj.hasOwnProperty(i)) {
  8351. return false;
  8352. }
  8353. }
  8354. return true;
  8355. };
  8356. Tools.RegisterTopRootEvents = function (events) {
  8357. for (var index = 0; index < events.length; index++) {
  8358. var event = events[index];
  8359. window.addEventListener(event.name, event.handler, false);
  8360. try {
  8361. if (window.parent) {
  8362. window.parent.addEventListener(event.name, event.handler, false);
  8363. }
  8364. }
  8365. catch (e) {
  8366. // Silently fails...
  8367. }
  8368. }
  8369. };
  8370. Tools.UnregisterTopRootEvents = function (events) {
  8371. for (var index = 0; index < events.length; index++) {
  8372. var event = events[index];
  8373. window.removeEventListener(event.name, event.handler);
  8374. try {
  8375. if (window.parent) {
  8376. window.parent.removeEventListener(event.name, event.handler);
  8377. }
  8378. }
  8379. catch (e) {
  8380. // Silently fails...
  8381. }
  8382. }
  8383. };
  8384. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8385. if (mimeType === void 0) { mimeType = "image/png"; }
  8386. // Read the contents of the framebuffer
  8387. var numberOfChannelsByLine = width * 4;
  8388. var halfHeight = height / 2;
  8389. //Reading datas from WebGL
  8390. var data = engine.readPixels(0, 0, width, height);
  8391. //To flip image on Y axis.
  8392. for (var i = 0; i < halfHeight; i++) {
  8393. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8394. var currentCell = j + i * numberOfChannelsByLine;
  8395. var targetLine = height - i - 1;
  8396. var targetCell = j + targetLine * numberOfChannelsByLine;
  8397. var temp = data[currentCell];
  8398. data[currentCell] = data[targetCell];
  8399. data[targetCell] = temp;
  8400. }
  8401. }
  8402. // Create a 2D canvas to store the result
  8403. if (!screenshotCanvas) {
  8404. screenshotCanvas = document.createElement('canvas');
  8405. }
  8406. screenshotCanvas.width = width;
  8407. screenshotCanvas.height = height;
  8408. var context = screenshotCanvas.getContext('2d');
  8409. if (context) {
  8410. // Copy the pixels to a 2D canvas
  8411. var imageData = context.createImageData(width, height);
  8412. var castData = (imageData.data);
  8413. castData.set(data);
  8414. context.putImageData(imageData, 0, 0);
  8415. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8416. }
  8417. };
  8418. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8419. if (mimeType === void 0) { mimeType = "image/png"; }
  8420. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8421. if (successCallback) {
  8422. successCallback(base64Image);
  8423. }
  8424. else {
  8425. // We need HTMLCanvasElement.toBlob for HD screenshots
  8426. if (!screenshotCanvas.toBlob) {
  8427. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8428. screenshotCanvas.toBlob = function (callback, type, quality) {
  8429. var _this = this;
  8430. setTimeout(function () {
  8431. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8432. for (var i = 0; i < len; i++) {
  8433. arr[i] = binStr.charCodeAt(i);
  8434. }
  8435. callback(new Blob([arr], { type: type || 'image/png' }));
  8436. });
  8437. };
  8438. }
  8439. screenshotCanvas.toBlob(function (blob) {
  8440. var url = URL.createObjectURL(blob);
  8441. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8442. if (("download" in document.createElement("a"))) {
  8443. var a = window.document.createElement("a");
  8444. a.href = url;
  8445. if (fileName) {
  8446. a.setAttribute("download", fileName);
  8447. }
  8448. else {
  8449. var date = new Date();
  8450. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8451. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8452. }
  8453. window.document.body.appendChild(a);
  8454. a.addEventListener("click", function () {
  8455. if (a.parentElement) {
  8456. a.parentElement.removeChild(a);
  8457. }
  8458. });
  8459. a.click();
  8460. }
  8461. else {
  8462. var newWindow = window.open("");
  8463. if (!newWindow)
  8464. return;
  8465. var img = newWindow.document.createElement("img");
  8466. img.onload = function () {
  8467. // no longer need to read the blob so it's revoked
  8468. URL.revokeObjectURL(url);
  8469. };
  8470. img.src = url;
  8471. newWindow.document.body.appendChild(img);
  8472. }
  8473. });
  8474. }
  8475. };
  8476. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8477. if (mimeType === void 0) { mimeType = "image/png"; }
  8478. var width;
  8479. var height;
  8480. // If a precision value is specified
  8481. if (size.precision) {
  8482. width = Math.round(engine.getRenderWidth() * size.precision);
  8483. height = Math.round(width / engine.getAspectRatio(camera));
  8484. }
  8485. else if (size.width && size.height) {
  8486. width = size.width;
  8487. height = size.height;
  8488. }
  8489. else if (size.width && !size.height) {
  8490. width = size.width;
  8491. height = Math.round(width / engine.getAspectRatio(camera));
  8492. }
  8493. else if (size.height && !size.width) {
  8494. height = size.height;
  8495. width = Math.round(height * engine.getAspectRatio(camera));
  8496. }
  8497. else if (!isNaN(size)) {
  8498. height = size;
  8499. width = size;
  8500. }
  8501. else {
  8502. Tools.Error("Invalid 'size' parameter !");
  8503. return;
  8504. }
  8505. if (!screenshotCanvas) {
  8506. screenshotCanvas = document.createElement('canvas');
  8507. }
  8508. screenshotCanvas.width = width;
  8509. screenshotCanvas.height = height;
  8510. var renderContext = screenshotCanvas.getContext("2d");
  8511. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8512. var newWidth = width;
  8513. var newHeight = newWidth / ratio;
  8514. if (newHeight > height) {
  8515. newHeight = height;
  8516. newWidth = newHeight * ratio;
  8517. }
  8518. var offsetX = Math.max(0, width - newWidth) / 2;
  8519. var offsetY = Math.max(0, height - newHeight) / 2;
  8520. var renderingCanvas = engine.getRenderingCanvas();
  8521. if (renderContext && renderingCanvas) {
  8522. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8523. }
  8524. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8525. };
  8526. /**
  8527. * Generates an image screenshot from the specified camera.
  8528. *
  8529. * @param engine The engine to use for rendering
  8530. * @param camera The camera to use for rendering
  8531. * @param size This parameter can be set to a single number or to an object with the
  8532. * following (optional) properties: precision, width, height. If a single number is passed,
  8533. * it will be used for both width and height. If an object is passed, the screenshot size
  8534. * will be derived from the parameters. The precision property is a multiplier allowing
  8535. * rendering at a higher or lower resolution.
  8536. * @param successCallback The callback receives a single parameter which contains the
  8537. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8538. * src parameter of an <img> to display it.
  8539. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8540. * Check your browser for supported MIME types.
  8541. * @param samples Texture samples (default: 1)
  8542. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8543. * @param fileName A name for for the downloaded file.
  8544. * @constructor
  8545. */
  8546. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8547. if (mimeType === void 0) { mimeType = "image/png"; }
  8548. if (samples === void 0) { samples = 1; }
  8549. if (antialiasing === void 0) { antialiasing = false; }
  8550. var width;
  8551. var height;
  8552. //If a precision value is specified
  8553. if (size.precision) {
  8554. width = Math.round(engine.getRenderWidth() * size.precision);
  8555. height = Math.round(width / engine.getAspectRatio(camera));
  8556. size = { width: width, height: height };
  8557. }
  8558. else if (size.width && size.height) {
  8559. width = size.width;
  8560. height = size.height;
  8561. }
  8562. else if (size.width && !size.height) {
  8563. width = size.width;
  8564. height = Math.round(width / engine.getAspectRatio(camera));
  8565. size = { width: width, height: height };
  8566. }
  8567. else if (size.height && !size.width) {
  8568. height = size.height;
  8569. width = Math.round(height * engine.getAspectRatio(camera));
  8570. size = { width: width, height: height };
  8571. }
  8572. else if (!isNaN(size)) {
  8573. height = size;
  8574. width = size;
  8575. }
  8576. else {
  8577. Tools.Error("Invalid 'size' parameter !");
  8578. return;
  8579. }
  8580. var scene = camera.getScene();
  8581. var previousCamera = null;
  8582. if (scene.activeCamera !== camera) {
  8583. previousCamera = scene.activeCamera;
  8584. scene.activeCamera = camera;
  8585. }
  8586. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8587. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8588. texture.renderList = null;
  8589. texture.samples = samples;
  8590. if (antialiasing) {
  8591. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8592. }
  8593. texture.onAfterRenderObservable.add(function () {
  8594. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8595. });
  8596. scene.incrementRenderId();
  8597. scene.resetCachedMaterial();
  8598. texture.render(true);
  8599. texture.dispose();
  8600. if (previousCamera) {
  8601. scene.activeCamera = previousCamera;
  8602. }
  8603. camera.getProjectionMatrix(true); // Force cache refresh;
  8604. };
  8605. // XHR response validator for local file scenario
  8606. Tools.ValidateXHRData = function (xhr, dataType) {
  8607. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8608. if (dataType === void 0) { dataType = 7; }
  8609. try {
  8610. if (dataType & 1) {
  8611. if (xhr.responseText && xhr.responseText.length > 0) {
  8612. return true;
  8613. }
  8614. else if (dataType === 1) {
  8615. return false;
  8616. }
  8617. }
  8618. if (dataType & 2) {
  8619. // Check header width and height since there is no "TGA" magic number
  8620. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8621. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8622. return true;
  8623. }
  8624. else if (dataType === 2) {
  8625. return false;
  8626. }
  8627. }
  8628. if (dataType & 4) {
  8629. // Check for the "DDS" magic number
  8630. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8631. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8632. return true;
  8633. }
  8634. else {
  8635. return false;
  8636. }
  8637. }
  8638. }
  8639. catch (e) {
  8640. // Global protection
  8641. }
  8642. return false;
  8643. };
  8644. /**
  8645. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8646. * Be aware Math.random() could cause collisions, but:
  8647. * "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"
  8648. */
  8649. Tools.RandomId = function () {
  8650. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8651. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8652. return v.toString(16);
  8653. });
  8654. };
  8655. /**
  8656. * Test if the given uri is a base64 string.
  8657. * @param uri The uri to test
  8658. * @return True if the uri is a base64 string or false otherwise.
  8659. */
  8660. Tools.IsBase64 = function (uri) {
  8661. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8662. };
  8663. /**
  8664. * Decode the given base64 uri.
  8665. * @param uri The uri to decode
  8666. * @return The decoded base64 data.
  8667. */
  8668. Tools.DecodeBase64 = function (uri) {
  8669. var decodedString = atob(uri.split(",")[1]);
  8670. var bufferLength = decodedString.length;
  8671. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8672. for (var i = 0; i < bufferLength; i++) {
  8673. bufferView[i] = decodedString.charCodeAt(i);
  8674. }
  8675. return bufferView.buffer;
  8676. };
  8677. Object.defineProperty(Tools, "NoneLogLevel", {
  8678. get: function () {
  8679. return Tools._NoneLogLevel;
  8680. },
  8681. enumerable: true,
  8682. configurable: true
  8683. });
  8684. Object.defineProperty(Tools, "MessageLogLevel", {
  8685. get: function () {
  8686. return Tools._MessageLogLevel;
  8687. },
  8688. enumerable: true,
  8689. configurable: true
  8690. });
  8691. Object.defineProperty(Tools, "WarningLogLevel", {
  8692. get: function () {
  8693. return Tools._WarningLogLevel;
  8694. },
  8695. enumerable: true,
  8696. configurable: true
  8697. });
  8698. Object.defineProperty(Tools, "ErrorLogLevel", {
  8699. get: function () {
  8700. return Tools._ErrorLogLevel;
  8701. },
  8702. enumerable: true,
  8703. configurable: true
  8704. });
  8705. Object.defineProperty(Tools, "AllLogLevel", {
  8706. get: function () {
  8707. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8708. },
  8709. enumerable: true,
  8710. configurable: true
  8711. });
  8712. Tools._AddLogEntry = function (entry) {
  8713. Tools._LogCache = entry + Tools._LogCache;
  8714. if (Tools.OnNewCacheEntry) {
  8715. Tools.OnNewCacheEntry(entry);
  8716. }
  8717. };
  8718. Tools._FormatMessage = function (message) {
  8719. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8720. var date = new Date();
  8721. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8722. };
  8723. Tools._LogDisabled = function (message) {
  8724. // nothing to do
  8725. };
  8726. Tools._LogEnabled = function (message) {
  8727. var formattedMessage = Tools._FormatMessage(message);
  8728. console.log("BJS - " + formattedMessage);
  8729. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8730. Tools._AddLogEntry(entry);
  8731. };
  8732. Tools._WarnDisabled = function (message) {
  8733. // nothing to do
  8734. };
  8735. Tools._WarnEnabled = function (message) {
  8736. var formattedMessage = Tools._FormatMessage(message);
  8737. console.warn("BJS - " + formattedMessage);
  8738. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8739. Tools._AddLogEntry(entry);
  8740. };
  8741. Tools._ErrorDisabled = function (message) {
  8742. // nothing to do
  8743. };
  8744. Tools._ErrorEnabled = function (message) {
  8745. Tools.errorsCount++;
  8746. var formattedMessage = Tools._FormatMessage(message);
  8747. console.error("BJS - " + formattedMessage);
  8748. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8749. Tools._AddLogEntry(entry);
  8750. };
  8751. Object.defineProperty(Tools, "LogCache", {
  8752. get: function () {
  8753. return Tools._LogCache;
  8754. },
  8755. enumerable: true,
  8756. configurable: true
  8757. });
  8758. Tools.ClearLogCache = function () {
  8759. Tools._LogCache = "";
  8760. Tools.errorsCount = 0;
  8761. };
  8762. Object.defineProperty(Tools, "LogLevels", {
  8763. set: function (level) {
  8764. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8765. Tools.Log = Tools._LogEnabled;
  8766. }
  8767. else {
  8768. Tools.Log = Tools._LogDisabled;
  8769. }
  8770. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8771. Tools.Warn = Tools._WarnEnabled;
  8772. }
  8773. else {
  8774. Tools.Warn = Tools._WarnDisabled;
  8775. }
  8776. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8777. Tools.Error = Tools._ErrorEnabled;
  8778. }
  8779. else {
  8780. Tools.Error = Tools._ErrorDisabled;
  8781. }
  8782. },
  8783. enumerable: true,
  8784. configurable: true
  8785. });
  8786. Tools.IsWindowObjectExist = function () {
  8787. return (typeof window) !== "undefined";
  8788. };
  8789. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8790. get: function () {
  8791. return Tools._PerformanceNoneLogLevel;
  8792. },
  8793. enumerable: true,
  8794. configurable: true
  8795. });
  8796. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8797. get: function () {
  8798. return Tools._PerformanceUserMarkLogLevel;
  8799. },
  8800. enumerable: true,
  8801. configurable: true
  8802. });
  8803. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8804. get: function () {
  8805. return Tools._PerformanceConsoleLogLevel;
  8806. },
  8807. enumerable: true,
  8808. configurable: true
  8809. });
  8810. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8811. set: function (level) {
  8812. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8813. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8814. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8815. return;
  8816. }
  8817. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8818. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8819. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8820. return;
  8821. }
  8822. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8823. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8824. },
  8825. enumerable: true,
  8826. configurable: true
  8827. });
  8828. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8829. };
  8830. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8831. };
  8832. Tools._StartUserMark = function (counterName, condition) {
  8833. if (condition === void 0) { condition = true; }
  8834. if (!Tools._performance) {
  8835. if (!Tools.IsWindowObjectExist()) {
  8836. return;
  8837. }
  8838. Tools._performance = window.performance;
  8839. }
  8840. if (!condition || !Tools._performance.mark) {
  8841. return;
  8842. }
  8843. Tools._performance.mark(counterName + "-Begin");
  8844. };
  8845. Tools._EndUserMark = function (counterName, condition) {
  8846. if (condition === void 0) { condition = true; }
  8847. if (!condition || !Tools._performance.mark) {
  8848. return;
  8849. }
  8850. Tools._performance.mark(counterName + "-End");
  8851. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8852. };
  8853. Tools._StartPerformanceConsole = function (counterName, condition) {
  8854. if (condition === void 0) { condition = true; }
  8855. if (!condition) {
  8856. return;
  8857. }
  8858. Tools._StartUserMark(counterName, condition);
  8859. if (console.time) {
  8860. console.time(counterName);
  8861. }
  8862. };
  8863. Tools._EndPerformanceConsole = function (counterName, condition) {
  8864. if (condition === void 0) { condition = true; }
  8865. if (!condition) {
  8866. return;
  8867. }
  8868. Tools._EndUserMark(counterName, condition);
  8869. if (console.time) {
  8870. console.timeEnd(counterName);
  8871. }
  8872. };
  8873. Object.defineProperty(Tools, "Now", {
  8874. get: function () {
  8875. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8876. return window.performance.now();
  8877. }
  8878. return new Date().getTime();
  8879. },
  8880. enumerable: true,
  8881. configurable: true
  8882. });
  8883. /**
  8884. * This method will return the name of the class used to create the instance of the given object.
  8885. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8886. * @param object the object to get the class name from
  8887. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8888. */
  8889. Tools.GetClassName = function (object, isType) {
  8890. if (isType === void 0) { isType = false; }
  8891. var name = null;
  8892. if (!isType && object.getClassName) {
  8893. name = object.getClassName();
  8894. }
  8895. else {
  8896. if (object instanceof Object) {
  8897. var classObj = isType ? object : Object.getPrototypeOf(object);
  8898. name = classObj.constructor["__bjsclassName__"];
  8899. }
  8900. if (!name) {
  8901. name = typeof object;
  8902. }
  8903. }
  8904. return name;
  8905. };
  8906. Tools.First = function (array, predicate) {
  8907. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8908. var el = array_1[_i];
  8909. if (predicate(el)) {
  8910. return el;
  8911. }
  8912. }
  8913. return null;
  8914. };
  8915. /**
  8916. * This method will return the name of the full name of the class, including its owning module (if any).
  8917. * 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).
  8918. * @param object the object to get the class name from
  8919. * @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.
  8920. */
  8921. Tools.getFullClassName = function (object, isType) {
  8922. if (isType === void 0) { isType = false; }
  8923. var className = null;
  8924. var moduleName = null;
  8925. if (!isType && object.getClassName) {
  8926. className = object.getClassName();
  8927. }
  8928. else {
  8929. if (object instanceof Object) {
  8930. var classObj = isType ? object : Object.getPrototypeOf(object);
  8931. className = classObj.constructor["__bjsclassName__"];
  8932. moduleName = classObj.constructor["__bjsmoduleName__"];
  8933. }
  8934. if (!className) {
  8935. className = typeof object;
  8936. }
  8937. }
  8938. if (!className) {
  8939. return null;
  8940. }
  8941. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8942. };
  8943. /**
  8944. * 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.
  8945. * @param array
  8946. */
  8947. Tools.arrayOrStringFeeder = function (array) {
  8948. return function (index) {
  8949. if (index >= array.length) {
  8950. return null;
  8951. }
  8952. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8953. if (val && val.getHashCode) {
  8954. val = val.getHashCode();
  8955. }
  8956. if (typeof val === "string") {
  8957. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8958. }
  8959. return val;
  8960. };
  8961. };
  8962. /**
  8963. * Compute the hashCode of a stream of number
  8964. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8965. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8966. * @return the hash code computed
  8967. */
  8968. Tools.hashCodeFromStream = function (feeder) {
  8969. // Based from here: http://stackoverflow.com/a/7616484/802124
  8970. var hash = 0;
  8971. var index = 0;
  8972. var chr = feeder(index++);
  8973. while (chr != null) {
  8974. hash = ((hash << 5) - hash) + chr;
  8975. hash |= 0; // Convert to 32bit integer
  8976. chr = feeder(index++);
  8977. }
  8978. return hash;
  8979. };
  8980. /**
  8981. * Returns a promise that resolves after the given amount of time.
  8982. * @param delay Number of milliseconds to delay
  8983. * @returns Promise that resolves after the given amount of time
  8984. */
  8985. Tools.DelayAsync = function (delay) {
  8986. return new Promise(function (resolve) {
  8987. setTimeout(function () {
  8988. resolve();
  8989. }, delay);
  8990. });
  8991. };
  8992. Tools.BaseUrl = "";
  8993. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8994. /**
  8995. * Default behaviour for cors in the application.
  8996. * It can be a string if the expected behavior is identical in the entire app.
  8997. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8998. */
  8999. Tools.CorsBehavior = "anonymous";
  9000. Tools.UseFallbackTexture = true;
  9001. /**
  9002. * Use this object to register external classes like custom textures or material
  9003. * to allow the laoders to instantiate them
  9004. */
  9005. Tools.RegisteredExternalClasses = {};
  9006. // Used in case of a texture loading problem
  9007. 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";
  9008. Tools.PreprocessUrl = function (url) {
  9009. return url;
  9010. };
  9011. // Logs
  9012. Tools._NoneLogLevel = 0;
  9013. Tools._MessageLogLevel = 1;
  9014. Tools._WarningLogLevel = 2;
  9015. Tools._ErrorLogLevel = 4;
  9016. Tools._LogCache = "";
  9017. Tools.errorsCount = 0;
  9018. Tools.Log = Tools._LogEnabled;
  9019. Tools.Warn = Tools._WarnEnabled;
  9020. Tools.Error = Tools._ErrorEnabled;
  9021. // Performances
  9022. Tools._PerformanceNoneLogLevel = 0;
  9023. Tools._PerformanceUserMarkLogLevel = 1;
  9024. Tools._PerformanceConsoleLogLevel = 2;
  9025. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9026. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9027. return Tools;
  9028. }());
  9029. BABYLON.Tools = Tools;
  9030. /**
  9031. * This class is used to track a performance counter which is number based.
  9032. * The user has access to many properties which give statistics of different nature
  9033. *
  9034. * The implementer can track two kinds of Performance Counter: time and count
  9035. * 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.
  9036. * 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.
  9037. */
  9038. var PerfCounter = /** @class */ (function () {
  9039. function PerfCounter() {
  9040. this._startMonitoringTime = 0;
  9041. this._min = 0;
  9042. this._max = 0;
  9043. this._average = 0;
  9044. this._lastSecAverage = 0;
  9045. this._current = 0;
  9046. this._totalValueCount = 0;
  9047. this._totalAccumulated = 0;
  9048. this._lastSecAccumulated = 0;
  9049. this._lastSecTime = 0;
  9050. this._lastSecValueCount = 0;
  9051. }
  9052. Object.defineProperty(PerfCounter.prototype, "min", {
  9053. /**
  9054. * Returns the smallest value ever
  9055. */
  9056. get: function () {
  9057. return this._min;
  9058. },
  9059. enumerable: true,
  9060. configurable: true
  9061. });
  9062. Object.defineProperty(PerfCounter.prototype, "max", {
  9063. /**
  9064. * Returns the biggest value ever
  9065. */
  9066. get: function () {
  9067. return this._max;
  9068. },
  9069. enumerable: true,
  9070. configurable: true
  9071. });
  9072. Object.defineProperty(PerfCounter.prototype, "average", {
  9073. /**
  9074. * Returns the average value since the performance counter is running
  9075. */
  9076. get: function () {
  9077. return this._average;
  9078. },
  9079. enumerable: true,
  9080. configurable: true
  9081. });
  9082. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9083. /**
  9084. * Returns the average value of the last second the counter was monitored
  9085. */
  9086. get: function () {
  9087. return this._lastSecAverage;
  9088. },
  9089. enumerable: true,
  9090. configurable: true
  9091. });
  9092. Object.defineProperty(PerfCounter.prototype, "current", {
  9093. /**
  9094. * Returns the current value
  9095. */
  9096. get: function () {
  9097. return this._current;
  9098. },
  9099. enumerable: true,
  9100. configurable: true
  9101. });
  9102. Object.defineProperty(PerfCounter.prototype, "total", {
  9103. get: function () {
  9104. return this._totalAccumulated;
  9105. },
  9106. enumerable: true,
  9107. configurable: true
  9108. });
  9109. Object.defineProperty(PerfCounter.prototype, "count", {
  9110. get: function () {
  9111. return this._totalValueCount;
  9112. },
  9113. enumerable: true,
  9114. configurable: true
  9115. });
  9116. /**
  9117. * Call this method to start monitoring a new frame.
  9118. * 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.
  9119. */
  9120. PerfCounter.prototype.fetchNewFrame = function () {
  9121. this._totalValueCount++;
  9122. this._current = 0;
  9123. this._lastSecValueCount++;
  9124. };
  9125. /**
  9126. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9127. * @param newCount the count value to add to the monitored count
  9128. * @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.
  9129. */
  9130. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9131. if (!PerfCounter.Enabled) {
  9132. return;
  9133. }
  9134. this._current += newCount;
  9135. if (fetchResult) {
  9136. this._fetchResult();
  9137. }
  9138. };
  9139. /**
  9140. * Start monitoring this performance counter
  9141. */
  9142. PerfCounter.prototype.beginMonitoring = function () {
  9143. if (!PerfCounter.Enabled) {
  9144. return;
  9145. }
  9146. this._startMonitoringTime = Tools.Now;
  9147. };
  9148. /**
  9149. * Compute the time lapsed since the previous beginMonitoring() call.
  9150. * @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
  9151. */
  9152. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9153. if (newFrame === void 0) { newFrame = true; }
  9154. if (!PerfCounter.Enabled) {
  9155. return;
  9156. }
  9157. if (newFrame) {
  9158. this.fetchNewFrame();
  9159. }
  9160. var currentTime = Tools.Now;
  9161. this._current = currentTime - this._startMonitoringTime;
  9162. if (newFrame) {
  9163. this._fetchResult();
  9164. }
  9165. };
  9166. PerfCounter.prototype._fetchResult = function () {
  9167. this._totalAccumulated += this._current;
  9168. this._lastSecAccumulated += this._current;
  9169. // Min/Max update
  9170. this._min = Math.min(this._min, this._current);
  9171. this._max = Math.max(this._max, this._current);
  9172. this._average = this._totalAccumulated / this._totalValueCount;
  9173. // Reset last sec?
  9174. var now = Tools.Now;
  9175. if ((now - this._lastSecTime) > 1000) {
  9176. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9177. this._lastSecTime = now;
  9178. this._lastSecAccumulated = 0;
  9179. this._lastSecValueCount = 0;
  9180. }
  9181. };
  9182. PerfCounter.Enabled = true;
  9183. return PerfCounter;
  9184. }());
  9185. BABYLON.PerfCounter = PerfCounter;
  9186. /**
  9187. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9188. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9189. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9190. * @param name The name of the class, case should be preserved
  9191. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9192. */
  9193. function className(name, module) {
  9194. return function (target) {
  9195. target["__bjsclassName__"] = name;
  9196. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9197. };
  9198. }
  9199. BABYLON.className = className;
  9200. /**
  9201. * An implementation of a loop for asynchronous functions.
  9202. */
  9203. var AsyncLoop = /** @class */ (function () {
  9204. /**
  9205. * Constroctor.
  9206. * @param iterations the number of iterations.
  9207. * @param _fn the function to run each iteration
  9208. * @param _successCallback the callback that will be called upon succesful execution
  9209. * @param offset starting offset.
  9210. */
  9211. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9212. if (offset === void 0) { offset = 0; }
  9213. this.iterations = iterations;
  9214. this._fn = _fn;
  9215. this._successCallback = _successCallback;
  9216. this.index = offset - 1;
  9217. this._done = false;
  9218. }
  9219. /**
  9220. * Execute the next iteration. Must be called after the last iteration was finished.
  9221. */
  9222. AsyncLoop.prototype.executeNext = function () {
  9223. if (!this._done) {
  9224. if (this.index + 1 < this.iterations) {
  9225. ++this.index;
  9226. this._fn(this);
  9227. }
  9228. else {
  9229. this.breakLoop();
  9230. }
  9231. }
  9232. };
  9233. /**
  9234. * Break the loop and run the success callback.
  9235. */
  9236. AsyncLoop.prototype.breakLoop = function () {
  9237. this._done = true;
  9238. this._successCallback();
  9239. };
  9240. /**
  9241. * Helper function
  9242. */
  9243. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9244. if (offset === void 0) { offset = 0; }
  9245. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9246. loop.executeNext();
  9247. return loop;
  9248. };
  9249. /**
  9250. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9251. * @param iterations total number of iterations
  9252. * @param syncedIterations number of synchronous iterations in each async iteration.
  9253. * @param fn the function to call each iteration.
  9254. * @param callback a success call back that will be called when iterating stops.
  9255. * @param breakFunction a break condition (optional)
  9256. * @param timeout timeout settings for the setTimeout function. default - 0.
  9257. * @constructor
  9258. */
  9259. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9260. if (timeout === void 0) { timeout = 0; }
  9261. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9262. if (breakFunction && breakFunction())
  9263. loop.breakLoop();
  9264. else {
  9265. setTimeout(function () {
  9266. for (var i = 0; i < syncedIterations; ++i) {
  9267. var iteration = (loop.index * syncedIterations) + i;
  9268. if (iteration >= iterations)
  9269. break;
  9270. fn(iteration);
  9271. if (breakFunction && breakFunction()) {
  9272. loop.breakLoop();
  9273. break;
  9274. }
  9275. }
  9276. loop.executeNext();
  9277. }, timeout);
  9278. }
  9279. }, callback);
  9280. };
  9281. return AsyncLoop;
  9282. }());
  9283. BABYLON.AsyncLoop = AsyncLoop;
  9284. })(BABYLON || (BABYLON = {}));
  9285. //# sourceMappingURL=babylon.tools.js.map
  9286. var BABYLON;
  9287. (function (BABYLON) {
  9288. var PromiseStates;
  9289. (function (PromiseStates) {
  9290. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9291. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9292. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9293. })(PromiseStates || (PromiseStates = {}));
  9294. var FulFillmentAgregator = /** @class */ (function () {
  9295. function FulFillmentAgregator() {
  9296. this.count = 0;
  9297. this.target = 0;
  9298. this.results = [];
  9299. }
  9300. return FulFillmentAgregator;
  9301. }());
  9302. var InternalPromise = /** @class */ (function () {
  9303. function InternalPromise(resolver) {
  9304. var _this = this;
  9305. this._state = PromiseStates.Pending;
  9306. this._children = new Array();
  9307. this._rejectWasConsumed = false;
  9308. if (!resolver) {
  9309. return;
  9310. }
  9311. try {
  9312. resolver(function (value) {
  9313. _this._resolve(value);
  9314. }, function (reason) {
  9315. _this._reject(reason);
  9316. });
  9317. }
  9318. catch (e) {
  9319. this._reject(e);
  9320. }
  9321. }
  9322. InternalPromise.prototype.catch = function (onRejected) {
  9323. return this.then(undefined, onRejected);
  9324. };
  9325. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9326. var _this = this;
  9327. var newPromise = new InternalPromise();
  9328. newPromise._onFulfilled = onFulfilled;
  9329. newPromise._onRejected = onRejected;
  9330. // Composition
  9331. this._children.push(newPromise);
  9332. if (this._state !== PromiseStates.Pending) {
  9333. BABYLON.Tools.SetImmediate(function () {
  9334. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9335. var returnedValue = newPromise._resolve(_this._result);
  9336. if (returnedValue !== undefined && returnedValue !== null) {
  9337. if (returnedValue._state !== undefined) {
  9338. var returnedPromise = returnedValue;
  9339. newPromise._children.push(returnedPromise);
  9340. newPromise = returnedPromise;
  9341. }
  9342. else {
  9343. newPromise._result = returnedValue;
  9344. }
  9345. }
  9346. }
  9347. else {
  9348. newPromise._reject(_this._reason);
  9349. }
  9350. });
  9351. }
  9352. return newPromise;
  9353. };
  9354. InternalPromise.prototype._moveChildren = function (children) {
  9355. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9356. if (this._state === PromiseStates.Fulfilled) {
  9357. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9358. var child = _b[_i];
  9359. child._resolve(this._result);
  9360. }
  9361. }
  9362. else if (this._state === PromiseStates.Rejected) {
  9363. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9364. var child = _d[_c];
  9365. child._reject(this._reason);
  9366. }
  9367. }
  9368. var _a;
  9369. };
  9370. InternalPromise.prototype._resolve = function (value) {
  9371. try {
  9372. this._state = PromiseStates.Fulfilled;
  9373. this._result = value;
  9374. var returnedValue = null;
  9375. if (this._onFulfilled) {
  9376. returnedValue = this._onFulfilled(value);
  9377. }
  9378. if (returnedValue !== undefined && returnedValue !== null) {
  9379. if (returnedValue._state !== undefined) {
  9380. // Transmit children
  9381. var returnedPromise = returnedValue;
  9382. returnedPromise._moveChildren(this._children);
  9383. }
  9384. else {
  9385. value = returnedValue;
  9386. }
  9387. }
  9388. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9389. var child = _a[_i];
  9390. child._resolve(value);
  9391. }
  9392. this._children.length = 0;
  9393. delete this._onFulfilled;
  9394. delete this._onRejected;
  9395. return returnedValue;
  9396. }
  9397. catch (e) {
  9398. this._reject(e, true);
  9399. }
  9400. return null;
  9401. };
  9402. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9403. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9404. this._state = PromiseStates.Rejected;
  9405. this._reason = reason;
  9406. if (this._onRejected && !onLocalThrow) {
  9407. try {
  9408. this._onRejected(reason);
  9409. this._rejectWasConsumed = true;
  9410. }
  9411. catch (e) {
  9412. reason = e;
  9413. }
  9414. }
  9415. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9416. var child = _a[_i];
  9417. if (this._rejectWasConsumed) {
  9418. child._resolve(null);
  9419. }
  9420. else {
  9421. child._reject(reason);
  9422. }
  9423. }
  9424. this._children.length = 0;
  9425. delete this._onFulfilled;
  9426. delete this._onRejected;
  9427. };
  9428. InternalPromise.resolve = function (value) {
  9429. var newPromise = new InternalPromise();
  9430. newPromise._resolve(value);
  9431. return newPromise;
  9432. };
  9433. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9434. promise.then(function (value) {
  9435. agregator.results[index] = value;
  9436. agregator.count++;
  9437. if (agregator.count === agregator.target) {
  9438. agregator.rootPromise._resolve(agregator.results);
  9439. }
  9440. return null;
  9441. }, function (reason) {
  9442. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9443. agregator.rootPromise._reject(reason);
  9444. }
  9445. });
  9446. };
  9447. InternalPromise.all = function (promises) {
  9448. var newPromise = new InternalPromise();
  9449. var agregator = new FulFillmentAgregator();
  9450. agregator.target = promises.length;
  9451. agregator.rootPromise = newPromise;
  9452. if (promises.length) {
  9453. for (var index = 0; index < promises.length; index++) {
  9454. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9455. }
  9456. }
  9457. else {
  9458. newPromise._resolve([]);
  9459. }
  9460. return newPromise;
  9461. };
  9462. return InternalPromise;
  9463. }());
  9464. /**
  9465. * Helper class that provides a small promise polyfill
  9466. */
  9467. var PromisePolyfill = /** @class */ (function () {
  9468. function PromisePolyfill() {
  9469. }
  9470. /**
  9471. * Static function used to check if the polyfill is required
  9472. * If this is the case then the function will inject the polyfill to window.Promise
  9473. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9474. */
  9475. PromisePolyfill.Apply = function (force) {
  9476. if (force === void 0) { force = false; }
  9477. if (force || typeof Promise === 'undefined') {
  9478. var root = window;
  9479. root.Promise = InternalPromise;
  9480. }
  9481. };
  9482. return PromisePolyfill;
  9483. }());
  9484. BABYLON.PromisePolyfill = PromisePolyfill;
  9485. })(BABYLON || (BABYLON = {}));
  9486. //# sourceMappingURL=babylon.promise.js.map
  9487. var BABYLON;
  9488. (function (BABYLON) {
  9489. var _AlphaState = /** @class */ (function () {
  9490. /**
  9491. * Initializes the state.
  9492. */
  9493. function _AlphaState() {
  9494. this._isAlphaBlendDirty = false;
  9495. this._isBlendFunctionParametersDirty = false;
  9496. this._isBlendEquationParametersDirty = false;
  9497. this._isBlendConstantsDirty = false;
  9498. this._alphaBlend = false;
  9499. this._blendFunctionParameters = new Array(4);
  9500. this._blendEquationParameters = new Array(2);
  9501. this._blendConstants = new Array(4);
  9502. this.reset();
  9503. }
  9504. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9505. get: function () {
  9506. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9507. },
  9508. enumerable: true,
  9509. configurable: true
  9510. });
  9511. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9512. get: function () {
  9513. return this._alphaBlend;
  9514. },
  9515. set: function (value) {
  9516. if (this._alphaBlend === value) {
  9517. return;
  9518. }
  9519. this._alphaBlend = value;
  9520. this._isAlphaBlendDirty = true;
  9521. },
  9522. enumerable: true,
  9523. configurable: true
  9524. });
  9525. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9526. if (this._blendConstants[0] === r &&
  9527. this._blendConstants[1] === g &&
  9528. this._blendConstants[2] === b &&
  9529. this._blendConstants[3] === a) {
  9530. return;
  9531. }
  9532. this._blendConstants[0] = r;
  9533. this._blendConstants[1] = g;
  9534. this._blendConstants[2] = b;
  9535. this._blendConstants[3] = a;
  9536. this._isBlendConstantsDirty = true;
  9537. };
  9538. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9539. if (this._blendFunctionParameters[0] === value0 &&
  9540. this._blendFunctionParameters[1] === value1 &&
  9541. this._blendFunctionParameters[2] === value2 &&
  9542. this._blendFunctionParameters[3] === value3) {
  9543. return;
  9544. }
  9545. this._blendFunctionParameters[0] = value0;
  9546. this._blendFunctionParameters[1] = value1;
  9547. this._blendFunctionParameters[2] = value2;
  9548. this._blendFunctionParameters[3] = value3;
  9549. this._isBlendFunctionParametersDirty = true;
  9550. };
  9551. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9552. if (this._blendEquationParameters[0] === rgb &&
  9553. this._blendEquationParameters[1] === alpha) {
  9554. return;
  9555. }
  9556. this._blendEquationParameters[0] = rgb;
  9557. this._blendEquationParameters[1] = alpha;
  9558. this._isBlendEquationParametersDirty = true;
  9559. };
  9560. _AlphaState.prototype.reset = function () {
  9561. this._alphaBlend = false;
  9562. this._blendFunctionParameters[0] = null;
  9563. this._blendFunctionParameters[1] = null;
  9564. this._blendFunctionParameters[2] = null;
  9565. this._blendFunctionParameters[3] = null;
  9566. this._blendEquationParameters[0] = null;
  9567. this._blendEquationParameters[1] = null;
  9568. this._blendConstants[0] = null;
  9569. this._blendConstants[1] = null;
  9570. this._blendConstants[2] = null;
  9571. this._blendConstants[3] = null;
  9572. this._isAlphaBlendDirty = true;
  9573. this._isBlendFunctionParametersDirty = false;
  9574. this._isBlendEquationParametersDirty = false;
  9575. this._isBlendConstantsDirty = false;
  9576. };
  9577. _AlphaState.prototype.apply = function (gl) {
  9578. if (!this.isDirty) {
  9579. return;
  9580. }
  9581. // Alpha blend
  9582. if (this._isAlphaBlendDirty) {
  9583. if (this._alphaBlend) {
  9584. gl.enable(gl.BLEND);
  9585. }
  9586. else {
  9587. gl.disable(gl.BLEND);
  9588. }
  9589. this._isAlphaBlendDirty = false;
  9590. }
  9591. // Alpha function
  9592. if (this._isBlendFunctionParametersDirty) {
  9593. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9594. this._isBlendFunctionParametersDirty = false;
  9595. }
  9596. // Alpha equation
  9597. if (this._isBlendEquationParametersDirty) {
  9598. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9599. this._isBlendEquationParametersDirty = false;
  9600. }
  9601. // Constants
  9602. if (this._isBlendConstantsDirty) {
  9603. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9604. this._isBlendConstantsDirty = false;
  9605. }
  9606. };
  9607. return _AlphaState;
  9608. }());
  9609. BABYLON._AlphaState = _AlphaState;
  9610. })(BABYLON || (BABYLON = {}));
  9611. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9612. var BABYLON;
  9613. (function (BABYLON) {
  9614. var _DepthCullingState = /** @class */ (function () {
  9615. /**
  9616. * Initializes the state.
  9617. */
  9618. function _DepthCullingState() {
  9619. this._isDepthTestDirty = false;
  9620. this._isDepthMaskDirty = false;
  9621. this._isDepthFuncDirty = false;
  9622. this._isCullFaceDirty = false;
  9623. this._isCullDirty = false;
  9624. this._isZOffsetDirty = false;
  9625. this._isFrontFaceDirty = false;
  9626. this.reset();
  9627. }
  9628. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9629. get: function () {
  9630. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9631. },
  9632. enumerable: true,
  9633. configurable: true
  9634. });
  9635. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9636. get: function () {
  9637. return this._zOffset;
  9638. },
  9639. set: function (value) {
  9640. if (this._zOffset === value) {
  9641. return;
  9642. }
  9643. this._zOffset = value;
  9644. this._isZOffsetDirty = true;
  9645. },
  9646. enumerable: true,
  9647. configurable: true
  9648. });
  9649. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9650. get: function () {
  9651. return this._cullFace;
  9652. },
  9653. set: function (value) {
  9654. if (this._cullFace === value) {
  9655. return;
  9656. }
  9657. this._cullFace = value;
  9658. this._isCullFaceDirty = true;
  9659. },
  9660. enumerable: true,
  9661. configurable: true
  9662. });
  9663. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9664. get: function () {
  9665. return this._cull;
  9666. },
  9667. set: function (value) {
  9668. if (this._cull === value) {
  9669. return;
  9670. }
  9671. this._cull = value;
  9672. this._isCullDirty = true;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9678. get: function () {
  9679. return this._depthFunc;
  9680. },
  9681. set: function (value) {
  9682. if (this._depthFunc === value) {
  9683. return;
  9684. }
  9685. this._depthFunc = value;
  9686. this._isDepthFuncDirty = true;
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9692. get: function () {
  9693. return this._depthMask;
  9694. },
  9695. set: function (value) {
  9696. if (this._depthMask === value) {
  9697. return;
  9698. }
  9699. this._depthMask = value;
  9700. this._isDepthMaskDirty = true;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9706. get: function () {
  9707. return this._depthTest;
  9708. },
  9709. set: function (value) {
  9710. if (this._depthTest === value) {
  9711. return;
  9712. }
  9713. this._depthTest = value;
  9714. this._isDepthTestDirty = true;
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9720. get: function () {
  9721. return this._frontFace;
  9722. },
  9723. set: function (value) {
  9724. if (this._frontFace === value) {
  9725. return;
  9726. }
  9727. this._frontFace = value;
  9728. this._isFrontFaceDirty = true;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. _DepthCullingState.prototype.reset = function () {
  9734. this._depthMask = true;
  9735. this._depthTest = true;
  9736. this._depthFunc = null;
  9737. this._cullFace = null;
  9738. this._cull = null;
  9739. this._zOffset = 0;
  9740. this._frontFace = null;
  9741. this._isDepthTestDirty = true;
  9742. this._isDepthMaskDirty = true;
  9743. this._isDepthFuncDirty = false;
  9744. this._isCullFaceDirty = false;
  9745. this._isCullDirty = false;
  9746. this._isZOffsetDirty = false;
  9747. this._isFrontFaceDirty = false;
  9748. };
  9749. _DepthCullingState.prototype.apply = function (gl) {
  9750. if (!this.isDirty) {
  9751. return;
  9752. }
  9753. // Cull
  9754. if (this._isCullDirty) {
  9755. if (this.cull) {
  9756. gl.enable(gl.CULL_FACE);
  9757. }
  9758. else {
  9759. gl.disable(gl.CULL_FACE);
  9760. }
  9761. this._isCullDirty = false;
  9762. }
  9763. // Cull face
  9764. if (this._isCullFaceDirty) {
  9765. gl.cullFace(this.cullFace);
  9766. this._isCullFaceDirty = false;
  9767. }
  9768. // Depth mask
  9769. if (this._isDepthMaskDirty) {
  9770. gl.depthMask(this.depthMask);
  9771. this._isDepthMaskDirty = false;
  9772. }
  9773. // Depth test
  9774. if (this._isDepthTestDirty) {
  9775. if (this.depthTest) {
  9776. gl.enable(gl.DEPTH_TEST);
  9777. }
  9778. else {
  9779. gl.disable(gl.DEPTH_TEST);
  9780. }
  9781. this._isDepthTestDirty = false;
  9782. }
  9783. // Depth func
  9784. if (this._isDepthFuncDirty) {
  9785. gl.depthFunc(this.depthFunc);
  9786. this._isDepthFuncDirty = false;
  9787. }
  9788. // zOffset
  9789. if (this._isZOffsetDirty) {
  9790. if (this.zOffset) {
  9791. gl.enable(gl.POLYGON_OFFSET_FILL);
  9792. gl.polygonOffset(this.zOffset, 0);
  9793. }
  9794. else {
  9795. gl.disable(gl.POLYGON_OFFSET_FILL);
  9796. }
  9797. this._isZOffsetDirty = false;
  9798. }
  9799. // Front face
  9800. if (this._isFrontFaceDirty) {
  9801. gl.frontFace(this.frontFace);
  9802. this._isFrontFaceDirty = false;
  9803. }
  9804. };
  9805. return _DepthCullingState;
  9806. }());
  9807. BABYLON._DepthCullingState = _DepthCullingState;
  9808. })(BABYLON || (BABYLON = {}));
  9809. //# sourceMappingURL=babylon.depthCullingState.js.map
  9810. var BABYLON;
  9811. (function (BABYLON) {
  9812. var _StencilState = /** @class */ (function () {
  9813. function _StencilState() {
  9814. this._isStencilTestDirty = false;
  9815. this._isStencilMaskDirty = false;
  9816. this._isStencilFuncDirty = false;
  9817. this._isStencilOpDirty = false;
  9818. this.reset();
  9819. }
  9820. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9821. get: function () {
  9822. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9823. },
  9824. enumerable: true,
  9825. configurable: true
  9826. });
  9827. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9828. get: function () {
  9829. return this._stencilFunc;
  9830. },
  9831. set: function (value) {
  9832. if (this._stencilFunc === value) {
  9833. return;
  9834. }
  9835. this._stencilFunc = value;
  9836. this._isStencilFuncDirty = true;
  9837. },
  9838. enumerable: true,
  9839. configurable: true
  9840. });
  9841. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9842. get: function () {
  9843. return this._stencilFuncRef;
  9844. },
  9845. set: function (value) {
  9846. if (this._stencilFuncRef === value) {
  9847. return;
  9848. }
  9849. this._stencilFuncRef = value;
  9850. this._isStencilFuncDirty = true;
  9851. },
  9852. enumerable: true,
  9853. configurable: true
  9854. });
  9855. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9856. get: function () {
  9857. return this._stencilFuncMask;
  9858. },
  9859. set: function (value) {
  9860. if (this._stencilFuncMask === value) {
  9861. return;
  9862. }
  9863. this._stencilFuncMask = value;
  9864. this._isStencilFuncDirty = true;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9870. get: function () {
  9871. return this._stencilOpStencilFail;
  9872. },
  9873. set: function (value) {
  9874. if (this._stencilOpStencilFail === value) {
  9875. return;
  9876. }
  9877. this._stencilOpStencilFail = value;
  9878. this._isStencilOpDirty = true;
  9879. },
  9880. enumerable: true,
  9881. configurable: true
  9882. });
  9883. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9884. get: function () {
  9885. return this._stencilOpDepthFail;
  9886. },
  9887. set: function (value) {
  9888. if (this._stencilOpDepthFail === value) {
  9889. return;
  9890. }
  9891. this._stencilOpDepthFail = value;
  9892. this._isStencilOpDirty = true;
  9893. },
  9894. enumerable: true,
  9895. configurable: true
  9896. });
  9897. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9898. get: function () {
  9899. return this._stencilOpStencilDepthPass;
  9900. },
  9901. set: function (value) {
  9902. if (this._stencilOpStencilDepthPass === value) {
  9903. return;
  9904. }
  9905. this._stencilOpStencilDepthPass = value;
  9906. this._isStencilOpDirty = true;
  9907. },
  9908. enumerable: true,
  9909. configurable: true
  9910. });
  9911. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9912. get: function () {
  9913. return this._stencilMask;
  9914. },
  9915. set: function (value) {
  9916. if (this._stencilMask === value) {
  9917. return;
  9918. }
  9919. this._stencilMask = value;
  9920. this._isStencilMaskDirty = true;
  9921. },
  9922. enumerable: true,
  9923. configurable: true
  9924. });
  9925. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9926. get: function () {
  9927. return this._stencilTest;
  9928. },
  9929. set: function (value) {
  9930. if (this._stencilTest === value) {
  9931. return;
  9932. }
  9933. this._stencilTest = value;
  9934. this._isStencilTestDirty = true;
  9935. },
  9936. enumerable: true,
  9937. configurable: true
  9938. });
  9939. _StencilState.prototype.reset = function () {
  9940. this._stencilTest = false;
  9941. this._stencilMask = 0xFF;
  9942. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9943. this._stencilFuncRef = 1;
  9944. this._stencilFuncMask = 0xFF;
  9945. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9946. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9947. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9948. this._isStencilTestDirty = true;
  9949. this._isStencilMaskDirty = true;
  9950. this._isStencilFuncDirty = true;
  9951. this._isStencilOpDirty = true;
  9952. };
  9953. _StencilState.prototype.apply = function (gl) {
  9954. if (!this.isDirty) {
  9955. return;
  9956. }
  9957. // Stencil test
  9958. if (this._isStencilTestDirty) {
  9959. if (this.stencilTest) {
  9960. gl.enable(gl.STENCIL_TEST);
  9961. }
  9962. else {
  9963. gl.disable(gl.STENCIL_TEST);
  9964. }
  9965. this._isStencilTestDirty = false;
  9966. }
  9967. // Stencil mask
  9968. if (this._isStencilMaskDirty) {
  9969. gl.stencilMask(this.stencilMask);
  9970. this._isStencilMaskDirty = false;
  9971. }
  9972. // Stencil func
  9973. if (this._isStencilFuncDirty) {
  9974. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9975. this._isStencilFuncDirty = false;
  9976. }
  9977. // Stencil op
  9978. if (this._isStencilOpDirty) {
  9979. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9980. this._isStencilOpDirty = false;
  9981. }
  9982. };
  9983. return _StencilState;
  9984. }());
  9985. BABYLON._StencilState = _StencilState;
  9986. })(BABYLON || (BABYLON = {}));
  9987. //# sourceMappingURL=babylon.stencilState.js.map
  9988. var __assign = (this && this.__assign) || Object.assign || function(t) {
  9989. for (var s, i = 1, n = arguments.length; i < n; i++) {
  9990. s = arguments[i];
  9991. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  9992. t[p] = s[p];
  9993. }
  9994. return t;
  9995. };
  9996. var BABYLON;
  9997. (function (BABYLON) {
  9998. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9999. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10000. };
  10001. var compileRawShader = function (gl, source, type) {
  10002. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10003. gl.shaderSource(shader, source);
  10004. gl.compileShader(shader);
  10005. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10006. var log = gl.getShaderInfoLog(shader);
  10007. if (log) {
  10008. throw new Error(log);
  10009. }
  10010. }
  10011. if (!shader) {
  10012. throw new Error("Something went wrong while compile the shader.");
  10013. }
  10014. return shader;
  10015. };
  10016. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10017. var magFilter = gl.NEAREST;
  10018. var minFilter = gl.NEAREST;
  10019. switch (samplingMode) {
  10020. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10021. magFilter = gl.LINEAR;
  10022. if (generateMipMaps) {
  10023. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10024. }
  10025. else {
  10026. minFilter = gl.LINEAR;
  10027. }
  10028. break;
  10029. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10030. magFilter = gl.LINEAR;
  10031. if (generateMipMaps) {
  10032. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10033. }
  10034. else {
  10035. minFilter = gl.LINEAR;
  10036. }
  10037. break;
  10038. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10039. magFilter = gl.NEAREST;
  10040. if (generateMipMaps) {
  10041. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10042. }
  10043. else {
  10044. minFilter = gl.NEAREST;
  10045. }
  10046. break;
  10047. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10048. magFilter = gl.NEAREST;
  10049. if (generateMipMaps) {
  10050. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10051. }
  10052. else {
  10053. minFilter = gl.NEAREST;
  10054. }
  10055. break;
  10056. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10057. magFilter = gl.NEAREST;
  10058. if (generateMipMaps) {
  10059. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10060. }
  10061. else {
  10062. minFilter = gl.LINEAR;
  10063. }
  10064. break;
  10065. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10066. magFilter = gl.NEAREST;
  10067. if (generateMipMaps) {
  10068. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10069. }
  10070. else {
  10071. minFilter = gl.LINEAR;
  10072. }
  10073. break;
  10074. case BABYLON.Texture.NEAREST_LINEAR:
  10075. magFilter = gl.NEAREST;
  10076. minFilter = gl.LINEAR;
  10077. break;
  10078. case BABYLON.Texture.NEAREST_NEAREST:
  10079. magFilter = gl.NEAREST;
  10080. minFilter = gl.NEAREST;
  10081. break;
  10082. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10083. magFilter = gl.LINEAR;
  10084. if (generateMipMaps) {
  10085. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10086. }
  10087. else {
  10088. minFilter = gl.NEAREST;
  10089. }
  10090. break;
  10091. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10092. magFilter = gl.LINEAR;
  10093. if (generateMipMaps) {
  10094. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10095. }
  10096. else {
  10097. minFilter = gl.NEAREST;
  10098. }
  10099. break;
  10100. case BABYLON.Texture.LINEAR_LINEAR:
  10101. magFilter = gl.LINEAR;
  10102. minFilter = gl.LINEAR;
  10103. break;
  10104. case BABYLON.Texture.LINEAR_NEAREST:
  10105. magFilter = gl.LINEAR;
  10106. minFilter = gl.NEAREST;
  10107. break;
  10108. }
  10109. return {
  10110. min: minFilter,
  10111. mag: magFilter
  10112. };
  10113. };
  10114. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10115. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10116. var img;
  10117. var onload = function () {
  10118. loadedImages[index] = img;
  10119. loadedImages._internalCount++;
  10120. if (scene) {
  10121. scene._removePendingData(img);
  10122. }
  10123. if (loadedImages._internalCount === 6) {
  10124. onfinish(loadedImages);
  10125. }
  10126. };
  10127. var onerror = function (message, exception) {
  10128. if (scene) {
  10129. scene._removePendingData(img);
  10130. }
  10131. if (onErrorCallBack) {
  10132. onErrorCallBack(message, exception);
  10133. }
  10134. };
  10135. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10136. if (scene) {
  10137. scene._addPendingData(img);
  10138. }
  10139. };
  10140. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10141. if (onError === void 0) { onError = null; }
  10142. var loadedImages = [];
  10143. loadedImages._internalCount = 0;
  10144. for (var index = 0; index < 6; index++) {
  10145. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10146. }
  10147. };
  10148. var BufferPointer = /** @class */ (function () {
  10149. function BufferPointer() {
  10150. }
  10151. return BufferPointer;
  10152. }());
  10153. var InstancingAttributeInfo = /** @class */ (function () {
  10154. function InstancingAttributeInfo() {
  10155. }
  10156. return InstancingAttributeInfo;
  10157. }());
  10158. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10159. /**
  10160. * Define options used to create a render target texture
  10161. */
  10162. var RenderTargetCreationOptions = /** @class */ (function () {
  10163. function RenderTargetCreationOptions() {
  10164. }
  10165. return RenderTargetCreationOptions;
  10166. }());
  10167. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10168. /**
  10169. * Regroup several parameters relative to the browser in use
  10170. */
  10171. var EngineCapabilities = /** @class */ (function () {
  10172. function EngineCapabilities() {
  10173. }
  10174. return EngineCapabilities;
  10175. }());
  10176. BABYLON.EngineCapabilities = EngineCapabilities;
  10177. /**
  10178. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10179. */
  10180. var Engine = /** @class */ (function () {
  10181. /**
  10182. * @constructor
  10183. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10184. * @param antialias defines enable antialiasing (default: false)
  10185. * @param options defines further options to be sent to the getContext() function
  10186. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10187. */
  10188. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10189. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10190. var _this = this;
  10191. // Public members
  10192. this.forcePOTTextures = false;
  10193. this.isFullscreen = false;
  10194. this.isPointerLock = false;
  10195. this.cullBackFaces = true;
  10196. this.renderEvenInBackground = true;
  10197. this.preventCacheWipeBetweenFrames = false;
  10198. // To enable/disable IDB support and avoid XHR on .manifest
  10199. this.enableOfflineSupport = false;
  10200. this.scenes = new Array();
  10201. this.postProcesses = new Array();
  10202. // Observables
  10203. /**
  10204. * Observable event triggered each time the rendering canvas is resized
  10205. */
  10206. this.onResizeObservable = new BABYLON.Observable();
  10207. /**
  10208. * Observable event triggered each time the canvas loses focus
  10209. */
  10210. this.onCanvasBlurObservable = new BABYLON.Observable();
  10211. /**
  10212. * Observable event triggered each time the canvas gains focus
  10213. */
  10214. this.onCanvasFocusObservable = new BABYLON.Observable();
  10215. /**
  10216. * Observable event triggered each time the canvas receives pointerout event
  10217. */
  10218. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10219. /**
  10220. * Observable event triggered before each texture is initialized
  10221. */
  10222. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10223. //WebVR
  10224. this._vrDisplay = undefined;
  10225. this._vrSupported = false;
  10226. this._vrExclusivePointerMode = false;
  10227. // Uniform buffers list
  10228. this.disableUniformBuffers = false;
  10229. this._uniformBuffers = new Array();
  10230. // Observables
  10231. /**
  10232. * Observable raised when the engine begins a new frame
  10233. */
  10234. this.onBeginFrameObservable = new BABYLON.Observable();
  10235. /**
  10236. * Observable raised when the engine ends the current frame
  10237. */
  10238. this.onEndFrameObservable = new BABYLON.Observable();
  10239. /**
  10240. * Observable raised when the engine is about to compile a shader
  10241. */
  10242. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10243. /**
  10244. * Observable raised when the engine has jsut compiled a shader
  10245. */
  10246. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10247. this._windowIsBackground = false;
  10248. this._webGLVersion = 1.0;
  10249. this._badOS = false;
  10250. this._badDesktopOS = false;
  10251. /**
  10252. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10253. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10254. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10255. */
  10256. this.disableTextureBindingOptimization = false;
  10257. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10258. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10259. this.onVRRequestPresentStart = new BABYLON.Observable();
  10260. this._colorWrite = true;
  10261. this._drawCalls = new BABYLON.PerfCounter();
  10262. this._textureCollisions = new BABYLON.PerfCounter();
  10263. this._renderingQueueLaunched = false;
  10264. this._activeRenderLoops = new Array();
  10265. // Deterministic lockstepMaxSteps
  10266. this._deterministicLockstep = false;
  10267. this._lockstepMaxSteps = 4;
  10268. // Lost context
  10269. this.onContextLostObservable = new BABYLON.Observable();
  10270. this.onContextRestoredObservable = new BABYLON.Observable();
  10271. this._contextWasLost = false;
  10272. this._doNotHandleContextLost = false;
  10273. // FPS
  10274. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10275. this._fps = 60;
  10276. this._deltaTime = 0;
  10277. /**
  10278. * Turn this value on if you want to pause FPS computation when in background
  10279. */
  10280. this.disablePerformanceMonitorInBackground = false;
  10281. // States
  10282. this._depthCullingState = new BABYLON._DepthCullingState();
  10283. this._stencilState = new BABYLON._StencilState();
  10284. this._alphaState = new BABYLON._AlphaState();
  10285. this._alphaMode = Engine.ALPHA_DISABLE;
  10286. // Cache
  10287. this._internalTexturesCache = new Array();
  10288. this._activeChannel = 0;
  10289. this._currentTextureChannel = -1;
  10290. this._boundTexturesCache = {};
  10291. this._compiledEffects = {};
  10292. this._vertexAttribArraysEnabled = [];
  10293. this._uintIndicesCurrentlySet = false;
  10294. this._currentBoundBuffer = new Array();
  10295. this._currentBufferPointers = new Array();
  10296. this._currentInstanceLocations = new Array();
  10297. this._currentInstanceBuffers = new Array();
  10298. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10299. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10300. this._vaoRecordInProgress = false;
  10301. this._mustWipeVertexAttributes = false;
  10302. this._nextFreeTextureSlots = new Array();
  10303. this._maxSimultaneousTextures = 0;
  10304. this._activeRequests = new Array();
  10305. // Hardware supported Compressed Textures
  10306. this._texturesSupported = new Array();
  10307. this._onVRFullScreenTriggered = function () {
  10308. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10309. //get the old size before we change
  10310. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10311. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10312. //get the width and height, change the render size
  10313. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10314. _this.setHardwareScalingLevel(1);
  10315. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10316. }
  10317. else {
  10318. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10319. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10320. }
  10321. };
  10322. this._boundUniforms = {};
  10323. // Register promises
  10324. BABYLON.PromisePolyfill.Apply();
  10325. var canvas = null;
  10326. Engine.Instances.push(this);
  10327. if (!canvasOrContext) {
  10328. return;
  10329. }
  10330. options = options || {};
  10331. if (canvasOrContext.getContext) {
  10332. canvas = canvasOrContext;
  10333. this._renderingCanvas = canvas;
  10334. if (antialias != null) {
  10335. options.antialias = antialias;
  10336. }
  10337. if (options.deterministicLockstep === undefined) {
  10338. options.deterministicLockstep = false;
  10339. }
  10340. if (options.lockstepMaxSteps === undefined) {
  10341. options.lockstepMaxSteps = 4;
  10342. }
  10343. if (options.preserveDrawingBuffer === undefined) {
  10344. options.preserveDrawingBuffer = false;
  10345. }
  10346. if (options.audioEngine === undefined) {
  10347. options.audioEngine = true;
  10348. }
  10349. if (options.stencil === undefined) {
  10350. options.stencil = true;
  10351. }
  10352. this._deterministicLockstep = options.deterministicLockstep;
  10353. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10354. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10355. // Exceptions
  10356. if (navigator && navigator.userAgent) {
  10357. var ua = navigator.userAgent;
  10358. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10359. var exception = _a[_i];
  10360. var key = exception.key;
  10361. var targets = exception.targets;
  10362. if (ua.indexOf(key) > -1) {
  10363. if (exception.capture && exception.captureConstraint) {
  10364. var capture = exception.capture;
  10365. var constraint = exception.captureConstraint;
  10366. var regex = new RegExp(capture);
  10367. var matches = regex.exec(ua);
  10368. if (matches && matches.length > 0) {
  10369. var capturedValue = parseInt(matches[matches.length - 1]);
  10370. if (capturedValue >= constraint) {
  10371. continue;
  10372. }
  10373. }
  10374. }
  10375. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10376. var target = targets_1[_b];
  10377. switch (target) {
  10378. case "uniformBuffer":
  10379. this.disableUniformBuffers = true;
  10380. break;
  10381. case "textureBindingOptimization":
  10382. this.disableTextureBindingOptimization = true;
  10383. break;
  10384. }
  10385. }
  10386. break;
  10387. }
  10388. }
  10389. }
  10390. // GL
  10391. if (!options.disableWebGL2Support) {
  10392. try {
  10393. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10394. if (this._gl) {
  10395. this._webGLVersion = 2.0;
  10396. }
  10397. }
  10398. catch (e) {
  10399. // Do nothing
  10400. }
  10401. }
  10402. if (!this._gl) {
  10403. if (!canvas) {
  10404. throw new Error("The provided canvas is null or undefined.");
  10405. }
  10406. try {
  10407. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10408. }
  10409. catch (e) {
  10410. throw new Error("WebGL not supported");
  10411. }
  10412. }
  10413. if (!this._gl) {
  10414. throw new Error("WebGL not supported");
  10415. }
  10416. this._onCanvasFocus = function () {
  10417. _this.onCanvasFocusObservable.notifyObservers(_this);
  10418. };
  10419. this._onCanvasBlur = function () {
  10420. _this.onCanvasBlurObservable.notifyObservers(_this);
  10421. };
  10422. canvas.addEventListener("focus", this._onCanvasFocus);
  10423. canvas.addEventListener("blur", this._onCanvasBlur);
  10424. this._onBlur = function () {
  10425. if (_this.disablePerformanceMonitorInBackground) {
  10426. _this._performanceMonitor.disable();
  10427. }
  10428. _this._windowIsBackground = true;
  10429. };
  10430. this._onFocus = function () {
  10431. if (_this.disablePerformanceMonitorInBackground) {
  10432. _this._performanceMonitor.enable();
  10433. }
  10434. _this._windowIsBackground = false;
  10435. };
  10436. this._onCanvasPointerOut = function () {
  10437. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10438. };
  10439. window.addEventListener("blur", this._onBlur);
  10440. window.addEventListener("focus", this._onFocus);
  10441. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10442. // Context lost
  10443. if (!this._doNotHandleContextLost) {
  10444. this._onContextLost = function (evt) {
  10445. evt.preventDefault();
  10446. _this._contextWasLost = true;
  10447. BABYLON.Tools.Warn("WebGL context lost.");
  10448. _this.onContextLostObservable.notifyObservers(_this);
  10449. };
  10450. this._onContextRestored = function (evt) {
  10451. // Adding a timeout to avoid race condition at browser level
  10452. setTimeout(function () {
  10453. // Rebuild gl context
  10454. _this._initGLContext();
  10455. // Rebuild effects
  10456. _this._rebuildEffects();
  10457. // Rebuild textures
  10458. _this._rebuildInternalTextures();
  10459. // Rebuild buffers
  10460. _this._rebuildBuffers();
  10461. // Cache
  10462. _this.wipeCaches(true);
  10463. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10464. _this.onContextRestoredObservable.notifyObservers(_this);
  10465. _this._contextWasLost = false;
  10466. }, 0);
  10467. };
  10468. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10469. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10470. }
  10471. }
  10472. else {
  10473. this._gl = canvasOrContext;
  10474. this._renderingCanvas = this._gl.canvas;
  10475. if (this._gl.renderbufferStorageMultisample) {
  10476. this._webGLVersion = 2.0;
  10477. }
  10478. options.stencil = this._gl.getContextAttributes().stencil;
  10479. }
  10480. // Viewport
  10481. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10482. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10483. this.resize();
  10484. this._isStencilEnable = options.stencil ? true : false;
  10485. this._initGLContext();
  10486. if (canvas) {
  10487. // Fullscreen
  10488. this._onFullscreenChange = function () {
  10489. if (document.fullscreen !== undefined) {
  10490. _this.isFullscreen = document.fullscreen;
  10491. }
  10492. else if (document.mozFullScreen !== undefined) {
  10493. _this.isFullscreen = document.mozFullScreen;
  10494. }
  10495. else if (document.webkitIsFullScreen !== undefined) {
  10496. _this.isFullscreen = document.webkitIsFullScreen;
  10497. }
  10498. else if (document.msIsFullScreen !== undefined) {
  10499. _this.isFullscreen = document.msIsFullScreen;
  10500. }
  10501. // Pointer lock
  10502. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10503. canvas.requestPointerLock = canvas.requestPointerLock ||
  10504. canvas.msRequestPointerLock ||
  10505. canvas.mozRequestPointerLock ||
  10506. canvas.webkitRequestPointerLock;
  10507. if (canvas.requestPointerLock) {
  10508. canvas.requestPointerLock();
  10509. }
  10510. }
  10511. };
  10512. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10513. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10514. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10515. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10516. // Pointer lock
  10517. this._onPointerLockChange = function () {
  10518. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10519. document.webkitPointerLockElement === canvas ||
  10520. document.msPointerLockElement === canvas ||
  10521. document.pointerLockElement === canvas);
  10522. };
  10523. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10524. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10525. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10526. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10527. this._onVRDisplayPointerRestricted = function () {
  10528. if (canvas) {
  10529. canvas.requestPointerLock();
  10530. }
  10531. };
  10532. this._onVRDisplayPointerUnrestricted = function () {
  10533. document.exitPointerLock();
  10534. };
  10535. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10536. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10537. }
  10538. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10539. Engine.audioEngine = new BABYLON.AudioEngine();
  10540. }
  10541. // Prepare buffer pointers
  10542. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10543. this._currentBufferPointers[i] = new BufferPointer();
  10544. }
  10545. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10546. // Load WebVR Devices
  10547. if (options.autoEnableWebVR) {
  10548. this.initWebVR();
  10549. }
  10550. // Detect if we are running on a faulty buggy OS.
  10551. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10552. // Detect if we are running on a faulty buggy desktop OS.
  10553. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10554. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10555. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10556. }
  10557. Object.defineProperty(Engine, "LastCreatedEngine", {
  10558. get: function () {
  10559. if (Engine.Instances.length === 0) {
  10560. return null;
  10561. }
  10562. return Engine.Instances[Engine.Instances.length - 1];
  10563. },
  10564. enumerable: true,
  10565. configurable: true
  10566. });
  10567. Object.defineProperty(Engine, "LastCreatedScene", {
  10568. get: function () {
  10569. var lastCreatedEngine = Engine.LastCreatedEngine;
  10570. if (!lastCreatedEngine) {
  10571. return null;
  10572. }
  10573. if (lastCreatedEngine.scenes.length === 0) {
  10574. return null;
  10575. }
  10576. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10577. },
  10578. enumerable: true,
  10579. configurable: true
  10580. });
  10581. /**
  10582. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10583. */
  10584. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10585. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10586. var engine = Engine.Instances[engineIndex];
  10587. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10588. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10589. }
  10590. }
  10591. };
  10592. Object.defineProperty(Engine, "NEVER", {
  10593. get: function () {
  10594. return Engine._NEVER;
  10595. },
  10596. enumerable: true,
  10597. configurable: true
  10598. });
  10599. Object.defineProperty(Engine, "ALWAYS", {
  10600. get: function () {
  10601. return Engine._ALWAYS;
  10602. },
  10603. enumerable: true,
  10604. configurable: true
  10605. });
  10606. Object.defineProperty(Engine, "LESS", {
  10607. get: function () {
  10608. return Engine._LESS;
  10609. },
  10610. enumerable: true,
  10611. configurable: true
  10612. });
  10613. Object.defineProperty(Engine, "EQUAL", {
  10614. get: function () {
  10615. return Engine._EQUAL;
  10616. },
  10617. enumerable: true,
  10618. configurable: true
  10619. });
  10620. Object.defineProperty(Engine, "LEQUAL", {
  10621. get: function () {
  10622. return Engine._LEQUAL;
  10623. },
  10624. enumerable: true,
  10625. configurable: true
  10626. });
  10627. Object.defineProperty(Engine, "GREATER", {
  10628. get: function () {
  10629. return Engine._GREATER;
  10630. },
  10631. enumerable: true,
  10632. configurable: true
  10633. });
  10634. Object.defineProperty(Engine, "GEQUAL", {
  10635. get: function () {
  10636. return Engine._GEQUAL;
  10637. },
  10638. enumerable: true,
  10639. configurable: true
  10640. });
  10641. Object.defineProperty(Engine, "NOTEQUAL", {
  10642. get: function () {
  10643. return Engine._NOTEQUAL;
  10644. },
  10645. enumerable: true,
  10646. configurable: true
  10647. });
  10648. Object.defineProperty(Engine, "KEEP", {
  10649. get: function () {
  10650. return Engine._KEEP;
  10651. },
  10652. enumerable: true,
  10653. configurable: true
  10654. });
  10655. Object.defineProperty(Engine, "REPLACE", {
  10656. get: function () {
  10657. return Engine._REPLACE;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. Object.defineProperty(Engine, "INCR", {
  10663. get: function () {
  10664. return Engine._INCR;
  10665. },
  10666. enumerable: true,
  10667. configurable: true
  10668. });
  10669. Object.defineProperty(Engine, "DECR", {
  10670. get: function () {
  10671. return Engine._DECR;
  10672. },
  10673. enumerable: true,
  10674. configurable: true
  10675. });
  10676. Object.defineProperty(Engine, "INVERT", {
  10677. get: function () {
  10678. return Engine._INVERT;
  10679. },
  10680. enumerable: true,
  10681. configurable: true
  10682. });
  10683. Object.defineProperty(Engine, "INCR_WRAP", {
  10684. get: function () {
  10685. return Engine._INCR_WRAP;
  10686. },
  10687. enumerable: true,
  10688. configurable: true
  10689. });
  10690. Object.defineProperty(Engine, "DECR_WRAP", {
  10691. get: function () {
  10692. return Engine._DECR_WRAP;
  10693. },
  10694. enumerable: true,
  10695. configurable: true
  10696. });
  10697. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10698. get: function () {
  10699. return Engine._ALPHA_DISABLE;
  10700. },
  10701. enumerable: true,
  10702. configurable: true
  10703. });
  10704. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10705. get: function () {
  10706. return Engine._ALPHA_ONEONE;
  10707. },
  10708. enumerable: true,
  10709. configurable: true
  10710. });
  10711. Object.defineProperty(Engine, "ALPHA_ADD", {
  10712. get: function () {
  10713. return Engine._ALPHA_ADD;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10719. get: function () {
  10720. return Engine._ALPHA_COMBINE;
  10721. },
  10722. enumerable: true,
  10723. configurable: true
  10724. });
  10725. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10726. get: function () {
  10727. return Engine._ALPHA_SUBTRACT;
  10728. },
  10729. enumerable: true,
  10730. configurable: true
  10731. });
  10732. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10733. get: function () {
  10734. return Engine._ALPHA_MULTIPLY;
  10735. },
  10736. enumerable: true,
  10737. configurable: true
  10738. });
  10739. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10740. get: function () {
  10741. return Engine._ALPHA_MAXIMIZED;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10747. get: function () {
  10748. return Engine._ALPHA_PREMULTIPLIED;
  10749. },
  10750. enumerable: true,
  10751. configurable: true
  10752. });
  10753. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10754. get: function () {
  10755. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10756. },
  10757. enumerable: true,
  10758. configurable: true
  10759. });
  10760. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10761. get: function () {
  10762. return Engine._ALPHA_INTERPOLATE;
  10763. },
  10764. enumerable: true,
  10765. configurable: true
  10766. });
  10767. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10768. get: function () {
  10769. return Engine._ALPHA_SCREENMODE;
  10770. },
  10771. enumerable: true,
  10772. configurable: true
  10773. });
  10774. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10775. get: function () {
  10776. return Engine._DELAYLOADSTATE_NONE;
  10777. },
  10778. enumerable: true,
  10779. configurable: true
  10780. });
  10781. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10782. get: function () {
  10783. return Engine._DELAYLOADSTATE_LOADED;
  10784. },
  10785. enumerable: true,
  10786. configurable: true
  10787. });
  10788. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10789. get: function () {
  10790. return Engine._DELAYLOADSTATE_LOADING;
  10791. },
  10792. enumerable: true,
  10793. configurable: true
  10794. });
  10795. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10796. get: function () {
  10797. return Engine._DELAYLOADSTATE_NOTLOADED;
  10798. },
  10799. enumerable: true,
  10800. configurable: true
  10801. });
  10802. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10803. get: function () {
  10804. return Engine._TEXTUREFORMAT_ALPHA;
  10805. },
  10806. enumerable: true,
  10807. configurable: true
  10808. });
  10809. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10810. get: function () {
  10811. return Engine._TEXTUREFORMAT_LUMINANCE;
  10812. },
  10813. enumerable: true,
  10814. configurable: true
  10815. });
  10816. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10817. /**
  10818. * R32F
  10819. */
  10820. get: function () {
  10821. return Engine._TEXTUREFORMAT_R32F;
  10822. },
  10823. enumerable: true,
  10824. configurable: true
  10825. });
  10826. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10827. /**
  10828. * RG32F
  10829. */
  10830. get: function () {
  10831. return Engine._TEXTUREFORMAT_RG32F;
  10832. },
  10833. enumerable: true,
  10834. configurable: true
  10835. });
  10836. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10837. /**
  10838. * RGB32F
  10839. */
  10840. get: function () {
  10841. return Engine._TEXTUREFORMAT_RGB32F;
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10847. get: function () {
  10848. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10849. },
  10850. enumerable: true,
  10851. configurable: true
  10852. });
  10853. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10854. get: function () {
  10855. return Engine._TEXTUREFORMAT_RGB;
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10861. get: function () {
  10862. return Engine._TEXTUREFORMAT_RGBA;
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10868. get: function () {
  10869. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10870. },
  10871. enumerable: true,
  10872. configurable: true
  10873. });
  10874. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10875. get: function () {
  10876. return Engine._TEXTURETYPE_FLOAT;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10882. get: function () {
  10883. return Engine._TEXTURETYPE_HALF_FLOAT;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10889. get: function () {
  10890. return Engine._SCALEMODE_FLOOR;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10896. get: function () {
  10897. return Engine._SCALEMODE_NEAREST;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10903. get: function () {
  10904. return Engine._SCALEMODE_CEILING;
  10905. },
  10906. enumerable: true,
  10907. configurable: true
  10908. });
  10909. Object.defineProperty(Engine, "Version", {
  10910. get: function () {
  10911. return "3.2.0-alpha7";
  10912. },
  10913. enumerable: true,
  10914. configurable: true
  10915. });
  10916. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10917. get: function () {
  10918. return this._vrExclusivePointerMode;
  10919. },
  10920. enumerable: true,
  10921. configurable: true
  10922. });
  10923. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10924. get: function () {
  10925. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10926. },
  10927. enumerable: true,
  10928. configurable: true
  10929. });
  10930. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10931. get: function () {
  10932. return this._webGLVersion < 2 || this.forcePOTTextures;
  10933. },
  10934. enumerable: true,
  10935. configurable: true
  10936. });
  10937. Object.defineProperty(Engine.prototype, "badOS", {
  10938. get: function () {
  10939. return this._badOS;
  10940. },
  10941. enumerable: true,
  10942. configurable: true
  10943. });
  10944. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10945. get: function () {
  10946. return this._badDesktopOS;
  10947. },
  10948. enumerable: true,
  10949. configurable: true
  10950. });
  10951. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10952. get: function () {
  10953. return this._performanceMonitor;
  10954. },
  10955. enumerable: true,
  10956. configurable: true
  10957. });
  10958. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10959. get: function () {
  10960. return this._texturesSupported;
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10966. get: function () {
  10967. return this._textureFormatInUse;
  10968. },
  10969. enumerable: true,
  10970. configurable: true
  10971. });
  10972. Object.defineProperty(Engine.prototype, "currentViewport", {
  10973. get: function () {
  10974. return this._cachedViewport;
  10975. },
  10976. enumerable: true,
  10977. configurable: true
  10978. });
  10979. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10980. // Empty texture
  10981. get: function () {
  10982. if (!this._emptyTexture) {
  10983. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10984. }
  10985. return this._emptyTexture;
  10986. },
  10987. enumerable: true,
  10988. configurable: true
  10989. });
  10990. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10991. get: function () {
  10992. if (!this._emptyTexture3D) {
  10993. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10994. }
  10995. return this._emptyTexture3D;
  10996. },
  10997. enumerable: true,
  10998. configurable: true
  10999. });
  11000. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11001. get: function () {
  11002. if (!this._emptyCubeTexture) {
  11003. var faceData = new Uint8Array(4);
  11004. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11005. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11006. }
  11007. return this._emptyCubeTexture;
  11008. },
  11009. enumerable: true,
  11010. configurable: true
  11011. });
  11012. Engine.prototype._rebuildInternalTextures = function () {
  11013. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11014. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11015. var internalTexture = currentState_1[_i];
  11016. internalTexture._rebuild();
  11017. }
  11018. };
  11019. Engine.prototype._rebuildEffects = function () {
  11020. for (var key in this._compiledEffects) {
  11021. var effect = this._compiledEffects[key];
  11022. effect._prepareEffect();
  11023. }
  11024. BABYLON.Effect.ResetCache();
  11025. };
  11026. Engine.prototype._rebuildBuffers = function () {
  11027. // Index / Vertex
  11028. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11029. var scene = _a[_i];
  11030. scene.resetCachedMaterial();
  11031. scene._rebuildGeometries();
  11032. scene._rebuildTextures();
  11033. }
  11034. // Uniforms
  11035. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11036. var uniformBuffer = _c[_b];
  11037. uniformBuffer._rebuild();
  11038. }
  11039. };
  11040. Engine.prototype._initGLContext = function () {
  11041. // Caps
  11042. this._caps = new EngineCapabilities();
  11043. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11044. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11045. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11046. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11047. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11048. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11049. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11050. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11051. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11052. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11053. // Infos
  11054. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11055. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11056. if (rendererInfo != null) {
  11057. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11058. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11059. }
  11060. if (!this._glVendor) {
  11061. this._glVendor = "Unknown vendor";
  11062. }
  11063. if (!this._glRenderer) {
  11064. this._glRenderer = "Unknown renderer";
  11065. }
  11066. // Constants
  11067. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11068. if (this._gl.RGBA16F !== 0x881A) {
  11069. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11070. }
  11071. if (this._gl.RGBA32F !== 0x8814) {
  11072. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11073. }
  11074. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11075. this._gl.DEPTH24_STENCIL8 = 35056;
  11076. }
  11077. // Extensions
  11078. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11079. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11080. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11081. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11082. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11083. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11084. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11085. 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');
  11086. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11087. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11088. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11089. this._caps.highPrecisionShaderSupported = true;
  11090. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11091. if (this._caps.timerQuery) {
  11092. if (this._webGLVersion === 1) {
  11093. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11094. }
  11095. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11096. }
  11097. // Checks if some of the format renders first to allow the use of webgl inspector.
  11098. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11099. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11100. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11101. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11102. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11103. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11104. if (this._webGLVersion > 1) {
  11105. this._gl.HALF_FLOAT_OES = 0x140B;
  11106. }
  11107. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11108. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11109. // Draw buffers
  11110. if (this._webGLVersion > 1) {
  11111. this._caps.drawBuffersExtension = true;
  11112. }
  11113. else {
  11114. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11115. if (drawBuffersExtension !== null) {
  11116. this._caps.drawBuffersExtension = true;
  11117. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11118. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11119. for (var i = 0; i < 16; i++) {
  11120. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11121. }
  11122. }
  11123. else {
  11124. this._caps.drawBuffersExtension = false;
  11125. }
  11126. }
  11127. // Depth Texture
  11128. if (this._webGLVersion > 1) {
  11129. this._caps.depthTextureExtension = true;
  11130. }
  11131. else {
  11132. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11133. if (depthTextureExtension != null) {
  11134. this._caps.depthTextureExtension = true;
  11135. }
  11136. }
  11137. // Vertex array object
  11138. if (this._webGLVersion > 1) {
  11139. this._caps.vertexArrayObject = true;
  11140. }
  11141. else {
  11142. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11143. if (vertexArrayObjectExtension != null) {
  11144. this._caps.vertexArrayObject = true;
  11145. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11146. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11147. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11148. }
  11149. else {
  11150. this._caps.vertexArrayObject = false;
  11151. }
  11152. }
  11153. // Instances count
  11154. if (this._webGLVersion > 1) {
  11155. this._caps.instancedArrays = true;
  11156. }
  11157. else {
  11158. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11159. if (instanceExtension != null) {
  11160. this._caps.instancedArrays = true;
  11161. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11162. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11163. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11164. }
  11165. else {
  11166. this._caps.instancedArrays = false;
  11167. }
  11168. }
  11169. // Intelligently add supported compressed formats in order to check for.
  11170. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11171. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11172. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11173. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11174. if (this._caps.astc)
  11175. this.texturesSupported.push('-astc.ktx');
  11176. if (this._caps.s3tc)
  11177. this.texturesSupported.push('-dxt.ktx');
  11178. if (this._caps.pvrtc)
  11179. this.texturesSupported.push('-pvrtc.ktx');
  11180. if (this._caps.etc2)
  11181. this.texturesSupported.push('-etc2.ktx');
  11182. if (this._caps.etc1)
  11183. this.texturesSupported.push('-etc1.ktx');
  11184. if (this._gl.getShaderPrecisionFormat) {
  11185. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11186. if (highp) {
  11187. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11188. }
  11189. }
  11190. // Depth buffer
  11191. this.setDepthBuffer(true);
  11192. this.setDepthFunctionToLessOrEqual();
  11193. this.setDepthWrite(true);
  11194. // Texture maps
  11195. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11196. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11197. this._nextFreeTextureSlots.push(slot);
  11198. }
  11199. };
  11200. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11201. get: function () {
  11202. return this._webGLVersion;
  11203. },
  11204. enumerable: true,
  11205. configurable: true
  11206. });
  11207. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11208. /**
  11209. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11210. */
  11211. get: function () {
  11212. return this._isStencilEnable;
  11213. },
  11214. enumerable: true,
  11215. configurable: true
  11216. });
  11217. Engine.prototype._prepareWorkingCanvas = function () {
  11218. if (this._workingCanvas) {
  11219. return;
  11220. }
  11221. this._workingCanvas = document.createElement("canvas");
  11222. var context = this._workingCanvas.getContext("2d");
  11223. if (context) {
  11224. this._workingContext = context;
  11225. }
  11226. };
  11227. Engine.prototype.resetTextureCache = function () {
  11228. for (var key in this._boundTexturesCache) {
  11229. var boundTexture = this._boundTexturesCache[key];
  11230. if (boundTexture) {
  11231. this._removeDesignatedSlot(boundTexture);
  11232. }
  11233. this._boundTexturesCache[key] = null;
  11234. }
  11235. if (!this.disableTextureBindingOptimization) {
  11236. this._nextFreeTextureSlots = [];
  11237. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11238. this._nextFreeTextureSlots.push(slot);
  11239. }
  11240. }
  11241. this._currentTextureChannel = -1;
  11242. };
  11243. Engine.prototype.isDeterministicLockStep = function () {
  11244. return this._deterministicLockstep;
  11245. };
  11246. Engine.prototype.getLockstepMaxSteps = function () {
  11247. return this._lockstepMaxSteps;
  11248. };
  11249. Engine.prototype.getGlInfo = function () {
  11250. return {
  11251. vendor: this._glVendor,
  11252. renderer: this._glRenderer,
  11253. version: this._glVersion
  11254. };
  11255. };
  11256. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11257. if (useScreen === void 0) { useScreen = false; }
  11258. var viewport = camera.viewport;
  11259. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11260. };
  11261. Engine.prototype.getRenderWidth = function (useScreen) {
  11262. if (useScreen === void 0) { useScreen = false; }
  11263. if (!useScreen && this._currentRenderTarget) {
  11264. return this._currentRenderTarget.width;
  11265. }
  11266. return this._gl.drawingBufferWidth;
  11267. };
  11268. Engine.prototype.getRenderHeight = function (useScreen) {
  11269. if (useScreen === void 0) { useScreen = false; }
  11270. if (!useScreen && this._currentRenderTarget) {
  11271. return this._currentRenderTarget.height;
  11272. }
  11273. return this._gl.drawingBufferHeight;
  11274. };
  11275. Engine.prototype.getRenderingCanvas = function () {
  11276. return this._renderingCanvas;
  11277. };
  11278. Engine.prototype.getRenderingCanvasClientRect = function () {
  11279. if (!this._renderingCanvas) {
  11280. return null;
  11281. }
  11282. return this._renderingCanvas.getBoundingClientRect();
  11283. };
  11284. Engine.prototype.setHardwareScalingLevel = function (level) {
  11285. this._hardwareScalingLevel = level;
  11286. this.resize();
  11287. };
  11288. Engine.prototype.getHardwareScalingLevel = function () {
  11289. return this._hardwareScalingLevel;
  11290. };
  11291. Engine.prototype.getLoadedTexturesCache = function () {
  11292. return this._internalTexturesCache;
  11293. };
  11294. Engine.prototype.getCaps = function () {
  11295. return this._caps;
  11296. };
  11297. Object.defineProperty(Engine.prototype, "drawCalls", {
  11298. /** The number of draw calls submitted last frame */
  11299. get: function () {
  11300. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11301. return 0;
  11302. },
  11303. enumerable: true,
  11304. configurable: true
  11305. });
  11306. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11307. get: function () {
  11308. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11309. return null;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Engine.prototype.getDepthFunction = function () {
  11315. return this._depthCullingState.depthFunc;
  11316. };
  11317. Engine.prototype.setDepthFunction = function (depthFunc) {
  11318. this._depthCullingState.depthFunc = depthFunc;
  11319. };
  11320. Engine.prototype.setDepthFunctionToGreater = function () {
  11321. this._depthCullingState.depthFunc = this._gl.GREATER;
  11322. };
  11323. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11324. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11325. };
  11326. Engine.prototype.setDepthFunctionToLess = function () {
  11327. this._depthCullingState.depthFunc = this._gl.LESS;
  11328. };
  11329. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11330. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11331. };
  11332. Engine.prototype.getStencilBuffer = function () {
  11333. return this._stencilState.stencilTest;
  11334. };
  11335. Engine.prototype.setStencilBuffer = function (enable) {
  11336. this._stencilState.stencilTest = enable;
  11337. };
  11338. Engine.prototype.getStencilMask = function () {
  11339. return this._stencilState.stencilMask;
  11340. };
  11341. Engine.prototype.setStencilMask = function (mask) {
  11342. this._stencilState.stencilMask = mask;
  11343. };
  11344. Engine.prototype.getStencilFunction = function () {
  11345. return this._stencilState.stencilFunc;
  11346. };
  11347. Engine.prototype.getStencilFunctionReference = function () {
  11348. return this._stencilState.stencilFuncRef;
  11349. };
  11350. Engine.prototype.getStencilFunctionMask = function () {
  11351. return this._stencilState.stencilFuncMask;
  11352. };
  11353. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11354. this._stencilState.stencilFunc = stencilFunc;
  11355. };
  11356. Engine.prototype.setStencilFunctionReference = function (reference) {
  11357. this._stencilState.stencilFuncRef = reference;
  11358. };
  11359. Engine.prototype.setStencilFunctionMask = function (mask) {
  11360. this._stencilState.stencilFuncMask = mask;
  11361. };
  11362. Engine.prototype.getStencilOperationFail = function () {
  11363. return this._stencilState.stencilOpStencilFail;
  11364. };
  11365. Engine.prototype.getStencilOperationDepthFail = function () {
  11366. return this._stencilState.stencilOpDepthFail;
  11367. };
  11368. Engine.prototype.getStencilOperationPass = function () {
  11369. return this._stencilState.stencilOpStencilDepthPass;
  11370. };
  11371. Engine.prototype.setStencilOperationFail = function (operation) {
  11372. this._stencilState.stencilOpStencilFail = operation;
  11373. };
  11374. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11375. this._stencilState.stencilOpDepthFail = operation;
  11376. };
  11377. Engine.prototype.setStencilOperationPass = function (operation) {
  11378. this._stencilState.stencilOpStencilDepthPass = operation;
  11379. };
  11380. Engine.prototype.setDitheringState = function (value) {
  11381. if (value) {
  11382. this._gl.enable(this._gl.DITHER);
  11383. }
  11384. else {
  11385. this._gl.disable(this._gl.DITHER);
  11386. }
  11387. };
  11388. Engine.prototype.setRasterizerState = function (value) {
  11389. if (value) {
  11390. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11391. }
  11392. else {
  11393. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11394. }
  11395. };
  11396. /**
  11397. * stop executing a render loop function and remove it from the execution array
  11398. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11399. */
  11400. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11401. if (!renderFunction) {
  11402. this._activeRenderLoops = [];
  11403. return;
  11404. }
  11405. var index = this._activeRenderLoops.indexOf(renderFunction);
  11406. if (index >= 0) {
  11407. this._activeRenderLoops.splice(index, 1);
  11408. }
  11409. };
  11410. Engine.prototype._renderLoop = function () {
  11411. if (!this._contextWasLost) {
  11412. var shouldRender = true;
  11413. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11414. shouldRender = false;
  11415. }
  11416. if (shouldRender) {
  11417. // Start new frame
  11418. this.beginFrame();
  11419. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11420. var renderFunction = this._activeRenderLoops[index];
  11421. renderFunction();
  11422. }
  11423. // Present
  11424. this.endFrame();
  11425. }
  11426. }
  11427. if (this._activeRenderLoops.length > 0) {
  11428. // Register new frame
  11429. var requester = null;
  11430. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11431. requester = this._vrDisplay;
  11432. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11433. }
  11434. else {
  11435. this._renderingQueueLaunched = false;
  11436. }
  11437. };
  11438. /**
  11439. * Register and execute a render loop. The engine can have more than one render function.
  11440. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11441. * @example
  11442. * engine.runRenderLoop(function () {
  11443. * scene.render()
  11444. * })
  11445. */
  11446. Engine.prototype.runRenderLoop = function (renderFunction) {
  11447. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11448. return;
  11449. }
  11450. this._activeRenderLoops.push(renderFunction);
  11451. if (!this._renderingQueueLaunched) {
  11452. this._renderingQueueLaunched = true;
  11453. this._bindedRenderFunction = this._renderLoop.bind(this);
  11454. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11455. }
  11456. };
  11457. /**
  11458. * Toggle full screen mode.
  11459. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11460. * @param {any} options - an options object to be sent to the requestFullscreen function
  11461. */
  11462. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11463. if (this.isFullscreen) {
  11464. BABYLON.Tools.ExitFullscreen();
  11465. }
  11466. else {
  11467. this._pointerLockRequested = requestPointerLock;
  11468. if (this._renderingCanvas) {
  11469. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11470. }
  11471. }
  11472. };
  11473. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11474. if (stencil === void 0) { stencil = false; }
  11475. this.applyStates();
  11476. var mode = 0;
  11477. if (backBuffer && color) {
  11478. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11479. mode |= this._gl.COLOR_BUFFER_BIT;
  11480. }
  11481. if (depth) {
  11482. this._gl.clearDepth(1.0);
  11483. mode |= this._gl.DEPTH_BUFFER_BIT;
  11484. }
  11485. if (stencil) {
  11486. this._gl.clearStencil(0);
  11487. mode |= this._gl.STENCIL_BUFFER_BIT;
  11488. }
  11489. this._gl.clear(mode);
  11490. };
  11491. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11492. var gl = this._gl;
  11493. // Save state
  11494. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11495. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11496. // Change state
  11497. gl.enable(gl.SCISSOR_TEST);
  11498. gl.scissor(x, y, width, height);
  11499. // Clear
  11500. this.clear(clearColor, true, true, true);
  11501. // Restore state
  11502. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11503. if (curScissor === true) {
  11504. gl.enable(gl.SCISSOR_TEST);
  11505. }
  11506. else {
  11507. gl.disable(gl.SCISSOR_TEST);
  11508. }
  11509. };
  11510. /**
  11511. * Set the WebGL's viewport
  11512. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11513. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11514. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11515. */
  11516. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11517. var width = requiredWidth || this.getRenderWidth();
  11518. var height = requiredHeight || this.getRenderHeight();
  11519. var x = viewport.x || 0;
  11520. var y = viewport.y || 0;
  11521. this._cachedViewport = viewport;
  11522. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11523. };
  11524. /**
  11525. * Directly set the WebGL Viewport
  11526. * The x, y, width & height are directly passed to the WebGL call
  11527. * @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.
  11528. */
  11529. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11530. var currentViewport = this._cachedViewport;
  11531. this._cachedViewport = null;
  11532. this._gl.viewport(x, y, width, height);
  11533. return currentViewport;
  11534. };
  11535. Engine.prototype.beginFrame = function () {
  11536. this.onBeginFrameObservable.notifyObservers(this);
  11537. this._measureFps();
  11538. };
  11539. Engine.prototype.endFrame = function () {
  11540. //force a flush in case we are using a bad OS.
  11541. if (this._badOS) {
  11542. this.flushFramebuffer();
  11543. }
  11544. //submit frame to the vr device, if enabled
  11545. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11546. // TODO: We should only submit the frame if we read frameData successfully.
  11547. this._vrDisplay.submitFrame();
  11548. }
  11549. this.onEndFrameObservable.notifyObservers(this);
  11550. };
  11551. /**
  11552. * resize the view according to the canvas' size.
  11553. * @example
  11554. * window.addEventListener("resize", function () {
  11555. * engine.resize();
  11556. * });
  11557. */
  11558. Engine.prototype.resize = function () {
  11559. // We're not resizing the size of the canvas while in VR mode & presenting
  11560. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11561. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11562. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11563. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11564. }
  11565. };
  11566. /**
  11567. * force a specific size of the canvas
  11568. * @param {number} width - the new canvas' width
  11569. * @param {number} height - the new canvas' height
  11570. */
  11571. Engine.prototype.setSize = function (width, height) {
  11572. if (!this._renderingCanvas) {
  11573. return;
  11574. }
  11575. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11576. return;
  11577. }
  11578. this._renderingCanvas.width = width;
  11579. this._renderingCanvas.height = height;
  11580. for (var index = 0; index < this.scenes.length; index++) {
  11581. var scene = this.scenes[index];
  11582. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11583. var cam = scene.cameras[camIndex];
  11584. cam._currentRenderId = 0;
  11585. }
  11586. }
  11587. if (this.onResizeObservable.hasObservers) {
  11588. this.onResizeObservable.notifyObservers(this);
  11589. }
  11590. };
  11591. // WebVR functions
  11592. Engine.prototype.isVRDevicePresent = function () {
  11593. return !!this._vrDisplay;
  11594. };
  11595. Engine.prototype.getVRDevice = function () {
  11596. return this._vrDisplay;
  11597. };
  11598. /**
  11599. * Initializes a webVR display and starts listening to display change events.
  11600. * The onVRDisplayChangedObservable will be notified upon these changes.
  11601. * @returns The onVRDisplayChangedObservable.
  11602. */
  11603. Engine.prototype.initWebVR = function () {
  11604. this.initWebVRAsync();
  11605. return this.onVRDisplayChangedObservable;
  11606. };
  11607. /**
  11608. * Initializes a webVR display and starts listening to display change events.
  11609. * The onVRDisplayChangedObservable will be notified upon these changes.
  11610. * @returns A promise containing a VRDisplay and if vr is supported.
  11611. */
  11612. Engine.prototype.initWebVRAsync = function () {
  11613. var _this = this;
  11614. var notifyObservers = function () {
  11615. var eventArgs = {
  11616. vrDisplay: _this._vrDisplay,
  11617. vrSupported: _this._vrSupported
  11618. };
  11619. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11620. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11621. };
  11622. if (!this._onVrDisplayConnect) {
  11623. this._onVrDisplayConnect = function (event) {
  11624. _this._vrDisplay = event.display;
  11625. notifyObservers();
  11626. };
  11627. this._onVrDisplayDisconnect = function () {
  11628. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11629. _this._vrDisplay = undefined;
  11630. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11631. notifyObservers();
  11632. };
  11633. this._onVrDisplayPresentChange = function () {
  11634. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11635. };
  11636. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11637. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11638. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11639. }
  11640. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11641. this._webVRInitPromise.then(notifyObservers);
  11642. return this._webVRInitPromise;
  11643. };
  11644. Engine.prototype.enableVR = function () {
  11645. var _this = this;
  11646. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11647. var onResolved = function () {
  11648. _this.onVRRequestPresentComplete.notifyObservers(true);
  11649. _this._onVRFullScreenTriggered();
  11650. };
  11651. var onRejected = function () {
  11652. _this.onVRRequestPresentComplete.notifyObservers(false);
  11653. };
  11654. this.onVRRequestPresentStart.notifyObservers(this);
  11655. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11656. }
  11657. };
  11658. Engine.prototype.disableVR = function () {
  11659. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11660. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11661. }
  11662. };
  11663. Engine.prototype._getVRDisplaysAsync = function () {
  11664. var _this = this;
  11665. return new Promise(function (res, rej) {
  11666. if (navigator.getVRDisplays) {
  11667. navigator.getVRDisplays().then(function (devices) {
  11668. _this._vrSupported = true;
  11669. // note that devices may actually be an empty array. This is fine;
  11670. // we expect this._vrDisplay to be undefined in this case.
  11671. _this._vrDisplay = devices[0];
  11672. res({
  11673. vrDisplay: _this._vrDisplay,
  11674. vrSupported: _this._vrSupported
  11675. });
  11676. });
  11677. }
  11678. else {
  11679. _this._vrDisplay = undefined;
  11680. _this._vrSupported = false;
  11681. res({
  11682. vrDisplay: _this._vrDisplay,
  11683. vrSupported: _this._vrSupported
  11684. });
  11685. }
  11686. });
  11687. };
  11688. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11689. if (this._currentRenderTarget) {
  11690. this.unBindFramebuffer(this._currentRenderTarget);
  11691. }
  11692. this._currentRenderTarget = texture;
  11693. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11694. var gl = this._gl;
  11695. if (texture.isCube) {
  11696. if (faceIndex === undefined) {
  11697. faceIndex = 0;
  11698. }
  11699. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11700. }
  11701. if (this._cachedViewport && !forceFullscreenViewport) {
  11702. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11703. }
  11704. else {
  11705. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11706. }
  11707. this.wipeCaches();
  11708. };
  11709. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11710. if (this._currentFramebuffer !== framebuffer) {
  11711. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11712. this._currentFramebuffer = framebuffer;
  11713. }
  11714. };
  11715. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11716. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11717. this._currentRenderTarget = null;
  11718. // If MSAA, we need to bitblt back to main texture
  11719. var gl = this._gl;
  11720. if (texture._MSAAFramebuffer) {
  11721. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11722. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11723. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11724. }
  11725. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11726. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11727. gl.generateMipmap(gl.TEXTURE_2D);
  11728. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11729. }
  11730. if (onBeforeUnbind) {
  11731. if (texture._MSAAFramebuffer) {
  11732. // Bind the correct framebuffer
  11733. this.bindUnboundFramebuffer(texture._framebuffer);
  11734. }
  11735. onBeforeUnbind();
  11736. }
  11737. this.bindUnboundFramebuffer(null);
  11738. };
  11739. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11740. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11741. this._currentRenderTarget = null;
  11742. // If MSAA, we need to bitblt back to main texture
  11743. var gl = this._gl;
  11744. if (textures[0]._MSAAFramebuffer) {
  11745. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11746. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11747. var attachments = textures[0]._attachments;
  11748. if (!attachments) {
  11749. attachments = new Array(textures.length);
  11750. textures[0]._attachments = attachments;
  11751. }
  11752. for (var i = 0; i < textures.length; i++) {
  11753. var texture = textures[i];
  11754. for (var j = 0; j < attachments.length; j++) {
  11755. attachments[j] = gl.NONE;
  11756. }
  11757. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11758. gl.readBuffer(attachments[i]);
  11759. gl.drawBuffers(attachments);
  11760. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11761. }
  11762. for (var i = 0; i < attachments.length; i++) {
  11763. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11764. }
  11765. gl.drawBuffers(attachments);
  11766. }
  11767. for (var i = 0; i < textures.length; i++) {
  11768. var texture = textures[i];
  11769. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11770. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11771. gl.generateMipmap(gl.TEXTURE_2D);
  11772. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11773. }
  11774. }
  11775. if (onBeforeUnbind) {
  11776. if (textures[0]._MSAAFramebuffer) {
  11777. // Bind the correct framebuffer
  11778. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11779. }
  11780. onBeforeUnbind();
  11781. }
  11782. this.bindUnboundFramebuffer(null);
  11783. };
  11784. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11785. if (texture.generateMipMaps) {
  11786. var gl = this._gl;
  11787. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11788. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11789. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11790. }
  11791. };
  11792. Engine.prototype.flushFramebuffer = function () {
  11793. this._gl.flush();
  11794. };
  11795. Engine.prototype.restoreDefaultFramebuffer = function () {
  11796. if (this._currentRenderTarget) {
  11797. this.unBindFramebuffer(this._currentRenderTarget);
  11798. }
  11799. else {
  11800. this.bindUnboundFramebuffer(null);
  11801. }
  11802. if (this._cachedViewport) {
  11803. this.setViewport(this._cachedViewport);
  11804. }
  11805. this.wipeCaches();
  11806. };
  11807. // UBOs
  11808. Engine.prototype.createUniformBuffer = function (elements) {
  11809. var ubo = this._gl.createBuffer();
  11810. if (!ubo) {
  11811. throw new Error("Unable to create uniform buffer");
  11812. }
  11813. this.bindUniformBuffer(ubo);
  11814. if (elements instanceof Float32Array) {
  11815. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11816. }
  11817. else {
  11818. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11819. }
  11820. this.bindUniformBuffer(null);
  11821. ubo.references = 1;
  11822. return ubo;
  11823. };
  11824. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11825. var ubo = this._gl.createBuffer();
  11826. if (!ubo) {
  11827. throw new Error("Unable to create dynamic uniform buffer");
  11828. }
  11829. this.bindUniformBuffer(ubo);
  11830. if (elements instanceof Float32Array) {
  11831. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11832. }
  11833. else {
  11834. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11835. }
  11836. this.bindUniformBuffer(null);
  11837. ubo.references = 1;
  11838. return ubo;
  11839. };
  11840. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11841. this.bindUniformBuffer(uniformBuffer);
  11842. if (offset === undefined) {
  11843. offset = 0;
  11844. }
  11845. if (count === undefined) {
  11846. if (elements instanceof Float32Array) {
  11847. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11848. }
  11849. else {
  11850. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11851. }
  11852. }
  11853. else {
  11854. if (elements instanceof Float32Array) {
  11855. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11856. }
  11857. else {
  11858. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11859. }
  11860. }
  11861. this.bindUniformBuffer(null);
  11862. };
  11863. // VBOs
  11864. Engine.prototype._resetVertexBufferBinding = function () {
  11865. this.bindArrayBuffer(null);
  11866. this._cachedVertexBuffers = null;
  11867. };
  11868. Engine.prototype.createVertexBuffer = function (vertices) {
  11869. var vbo = this._gl.createBuffer();
  11870. if (!vbo) {
  11871. throw new Error("Unable to create vertex buffer");
  11872. }
  11873. this.bindArrayBuffer(vbo);
  11874. if (vertices instanceof Float32Array) {
  11875. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11876. }
  11877. else {
  11878. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11879. }
  11880. this._resetVertexBufferBinding();
  11881. vbo.references = 1;
  11882. return vbo;
  11883. };
  11884. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11885. var vbo = this._gl.createBuffer();
  11886. if (!vbo) {
  11887. throw new Error("Unable to create dynamic vertex buffer");
  11888. }
  11889. this.bindArrayBuffer(vbo);
  11890. if (vertices instanceof Float32Array) {
  11891. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11892. }
  11893. else {
  11894. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11895. }
  11896. this._resetVertexBufferBinding();
  11897. vbo.references = 1;
  11898. return vbo;
  11899. };
  11900. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11901. if (offset === void 0) { offset = 0; }
  11902. // Force cache update
  11903. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11904. this.bindIndexBuffer(indexBuffer);
  11905. var arrayBuffer;
  11906. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11907. arrayBuffer = indices;
  11908. }
  11909. else {
  11910. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11911. }
  11912. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11913. this._resetIndexBufferBinding();
  11914. };
  11915. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11916. this.bindArrayBuffer(vertexBuffer);
  11917. if (offset === undefined) {
  11918. offset = 0;
  11919. }
  11920. if (count === undefined) {
  11921. if (vertices instanceof Float32Array) {
  11922. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11923. }
  11924. else {
  11925. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11926. }
  11927. }
  11928. else {
  11929. if (vertices instanceof Float32Array) {
  11930. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11931. }
  11932. else {
  11933. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11934. }
  11935. }
  11936. this._resetVertexBufferBinding();
  11937. };
  11938. Engine.prototype._resetIndexBufferBinding = function () {
  11939. this.bindIndexBuffer(null);
  11940. this._cachedIndexBuffer = null;
  11941. };
  11942. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11943. var vbo = this._gl.createBuffer();
  11944. if (!vbo) {
  11945. throw new Error("Unable to create index buffer");
  11946. }
  11947. this.bindIndexBuffer(vbo);
  11948. // Check for 32 bits indices
  11949. var arrayBuffer;
  11950. var need32Bits = false;
  11951. if (indices instanceof Uint16Array) {
  11952. arrayBuffer = indices;
  11953. }
  11954. else {
  11955. //check 32 bit support
  11956. if (this._caps.uintIndices) {
  11957. if (indices instanceof Uint32Array) {
  11958. arrayBuffer = indices;
  11959. need32Bits = true;
  11960. }
  11961. else {
  11962. //number[] or Int32Array, check if 32 bit is necessary
  11963. for (var index = 0; index < indices.length; index++) {
  11964. if (indices[index] > 65535) {
  11965. need32Bits = true;
  11966. break;
  11967. }
  11968. }
  11969. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11970. }
  11971. }
  11972. else {
  11973. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11974. arrayBuffer = new Uint16Array(indices);
  11975. }
  11976. }
  11977. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11978. this._resetIndexBufferBinding();
  11979. vbo.references = 1;
  11980. vbo.is32Bits = need32Bits;
  11981. return vbo;
  11982. };
  11983. Engine.prototype.bindArrayBuffer = function (buffer) {
  11984. if (!this._vaoRecordInProgress) {
  11985. this._unbindVertexArrayObject();
  11986. }
  11987. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11988. };
  11989. Engine.prototype.bindUniformBuffer = function (buffer) {
  11990. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11991. };
  11992. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11993. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11994. };
  11995. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  11996. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  11997. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  11998. };
  11999. ;
  12000. Engine.prototype.bindIndexBuffer = function (buffer) {
  12001. if (!this._vaoRecordInProgress) {
  12002. this._unbindVertexArrayObject();
  12003. }
  12004. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12005. };
  12006. Engine.prototype.bindBuffer = function (buffer, target) {
  12007. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12008. this._gl.bindBuffer(target, buffer);
  12009. this._currentBoundBuffer[target] = buffer;
  12010. }
  12011. };
  12012. Engine.prototype.updateArrayBuffer = function (data) {
  12013. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12014. };
  12015. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12016. var pointer = this._currentBufferPointers[indx];
  12017. var changed = false;
  12018. if (!pointer.active) {
  12019. changed = true;
  12020. pointer.active = true;
  12021. pointer.index = indx;
  12022. pointer.size = size;
  12023. pointer.type = type;
  12024. pointer.normalized = normalized;
  12025. pointer.stride = stride;
  12026. pointer.offset = offset;
  12027. pointer.buffer = buffer;
  12028. }
  12029. else {
  12030. if (pointer.buffer !== buffer) {
  12031. pointer.buffer = buffer;
  12032. changed = true;
  12033. }
  12034. if (pointer.size !== size) {
  12035. pointer.size = size;
  12036. changed = true;
  12037. }
  12038. if (pointer.type !== type) {
  12039. pointer.type = type;
  12040. changed = true;
  12041. }
  12042. if (pointer.normalized !== normalized) {
  12043. pointer.normalized = normalized;
  12044. changed = true;
  12045. }
  12046. if (pointer.stride !== stride) {
  12047. pointer.stride = stride;
  12048. changed = true;
  12049. }
  12050. if (pointer.offset !== offset) {
  12051. pointer.offset = offset;
  12052. changed = true;
  12053. }
  12054. }
  12055. if (changed || this._vaoRecordInProgress) {
  12056. this.bindArrayBuffer(buffer);
  12057. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12058. }
  12059. };
  12060. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12061. if (indexBuffer == null) {
  12062. return;
  12063. }
  12064. if (this._cachedIndexBuffer !== indexBuffer) {
  12065. this._cachedIndexBuffer = indexBuffer;
  12066. this.bindIndexBuffer(indexBuffer);
  12067. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12068. }
  12069. };
  12070. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12071. var attributes = effect.getAttributesNames();
  12072. if (!this._vaoRecordInProgress) {
  12073. this._unbindVertexArrayObject();
  12074. }
  12075. this.unbindAllAttributes();
  12076. for (var index = 0; index < attributes.length; index++) {
  12077. var order = effect.getAttributeLocation(index);
  12078. if (order >= 0) {
  12079. var vertexBuffer = vertexBuffers[attributes[index]];
  12080. if (!vertexBuffer) {
  12081. continue;
  12082. }
  12083. this._gl.enableVertexAttribArray(order);
  12084. if (!this._vaoRecordInProgress) {
  12085. this._vertexAttribArraysEnabled[order] = true;
  12086. }
  12087. var buffer = vertexBuffer.getBuffer();
  12088. if (buffer) {
  12089. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12090. if (vertexBuffer.getIsInstanced()) {
  12091. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12092. if (!this._vaoRecordInProgress) {
  12093. this._currentInstanceLocations.push(order);
  12094. this._currentInstanceBuffers.push(buffer);
  12095. }
  12096. }
  12097. }
  12098. }
  12099. }
  12100. };
  12101. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12102. var vao = this._gl.createVertexArray();
  12103. this._vaoRecordInProgress = true;
  12104. this._gl.bindVertexArray(vao);
  12105. this._mustWipeVertexAttributes = true;
  12106. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12107. this.bindIndexBuffer(indexBuffer);
  12108. this._vaoRecordInProgress = false;
  12109. this._gl.bindVertexArray(null);
  12110. return vao;
  12111. };
  12112. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12113. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12114. this._cachedVertexArrayObject = vertexArrayObject;
  12115. this._gl.bindVertexArray(vertexArrayObject);
  12116. this._cachedVertexBuffers = null;
  12117. this._cachedIndexBuffer = null;
  12118. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12119. this._mustWipeVertexAttributes = true;
  12120. }
  12121. };
  12122. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12123. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12124. this._cachedVertexBuffers = vertexBuffer;
  12125. this._cachedEffectForVertexBuffers = effect;
  12126. var attributesCount = effect.getAttributesCount();
  12127. this._unbindVertexArrayObject();
  12128. this.unbindAllAttributes();
  12129. var offset = 0;
  12130. for (var index = 0; index < attributesCount; index++) {
  12131. if (index < vertexDeclaration.length) {
  12132. var order = effect.getAttributeLocation(index);
  12133. if (order >= 0) {
  12134. this._gl.enableVertexAttribArray(order);
  12135. this._vertexAttribArraysEnabled[order] = true;
  12136. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12137. }
  12138. offset += vertexDeclaration[index] * 4;
  12139. }
  12140. }
  12141. }
  12142. this._bindIndexBufferWithCache(indexBuffer);
  12143. };
  12144. Engine.prototype._unbindVertexArrayObject = function () {
  12145. if (!this._cachedVertexArrayObject) {
  12146. return;
  12147. }
  12148. this._cachedVertexArrayObject = null;
  12149. this._gl.bindVertexArray(null);
  12150. };
  12151. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12152. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12153. this._cachedVertexBuffers = vertexBuffers;
  12154. this._cachedEffectForVertexBuffers = effect;
  12155. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12156. }
  12157. this._bindIndexBufferWithCache(indexBuffer);
  12158. };
  12159. Engine.prototype.unbindInstanceAttributes = function () {
  12160. var boundBuffer;
  12161. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12162. var instancesBuffer = this._currentInstanceBuffers[i];
  12163. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12164. boundBuffer = instancesBuffer;
  12165. this.bindArrayBuffer(instancesBuffer);
  12166. }
  12167. var offsetLocation = this._currentInstanceLocations[i];
  12168. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12169. }
  12170. this._currentInstanceBuffers.length = 0;
  12171. this._currentInstanceLocations.length = 0;
  12172. };
  12173. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12174. this._gl.deleteVertexArray(vao);
  12175. };
  12176. Engine.prototype._releaseBuffer = function (buffer) {
  12177. buffer.references--;
  12178. if (buffer.references === 0) {
  12179. this._gl.deleteBuffer(buffer);
  12180. return true;
  12181. }
  12182. return false;
  12183. };
  12184. Engine.prototype.createInstancesBuffer = function (capacity) {
  12185. var buffer = this._gl.createBuffer();
  12186. if (!buffer) {
  12187. throw new Error("Unable to create instance buffer");
  12188. }
  12189. buffer.capacity = capacity;
  12190. this.bindArrayBuffer(buffer);
  12191. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12192. return buffer;
  12193. };
  12194. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12195. this._gl.deleteBuffer(buffer);
  12196. };
  12197. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12198. this.bindArrayBuffer(instancesBuffer);
  12199. if (data) {
  12200. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12201. }
  12202. if (offsetLocations[0].index !== undefined) {
  12203. var stride = 0;
  12204. for (var i = 0; i < offsetLocations.length; i++) {
  12205. var ai = offsetLocations[i];
  12206. stride += ai.attributeSize * 4;
  12207. }
  12208. for (var i = 0; i < offsetLocations.length; i++) {
  12209. var ai = offsetLocations[i];
  12210. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12211. this._gl.enableVertexAttribArray(ai.index);
  12212. this._vertexAttribArraysEnabled[ai.index] = true;
  12213. }
  12214. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12215. this._gl.vertexAttribDivisor(ai.index, 1);
  12216. this._currentInstanceLocations.push(ai.index);
  12217. this._currentInstanceBuffers.push(instancesBuffer);
  12218. }
  12219. }
  12220. else {
  12221. for (var index = 0; index < 4; index++) {
  12222. var offsetLocation = offsetLocations[index];
  12223. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12224. this._gl.enableVertexAttribArray(offsetLocation);
  12225. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12226. }
  12227. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12228. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12229. this._currentInstanceLocations.push(offsetLocation);
  12230. this._currentInstanceBuffers.push(instancesBuffer);
  12231. }
  12232. }
  12233. };
  12234. Engine.prototype.applyStates = function () {
  12235. this._depthCullingState.apply(this._gl);
  12236. this._stencilState.apply(this._gl);
  12237. this._alphaState.apply(this._gl);
  12238. };
  12239. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12240. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12241. };
  12242. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12243. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12244. };
  12245. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12246. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12247. };
  12248. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12249. // Apply states
  12250. this.applyStates();
  12251. this._drawCalls.addCount(1, false);
  12252. // Render
  12253. var drawMode = this.DrawMode(fillMode);
  12254. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12255. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12256. if (instancesCount) {
  12257. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12258. }
  12259. else {
  12260. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12261. }
  12262. };
  12263. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12264. // Apply states
  12265. this.applyStates();
  12266. this._drawCalls.addCount(1, false);
  12267. var drawMode = this.DrawMode(fillMode);
  12268. if (instancesCount) {
  12269. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12270. }
  12271. else {
  12272. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12273. }
  12274. };
  12275. Engine.prototype.DrawMode = function (fillMode) {
  12276. switch (fillMode) {
  12277. // Triangle views
  12278. case BABYLON.Material.TriangleFillMode:
  12279. return this._gl.TRIANGLES;
  12280. case BABYLON.Material.PointFillMode:
  12281. return this._gl.POINTS;
  12282. case BABYLON.Material.WireFrameFillMode:
  12283. return this._gl.LINES;
  12284. // Draw modes
  12285. case BABYLON.Material.PointListDrawMode:
  12286. return this._gl.POINTS;
  12287. case BABYLON.Material.LineListDrawMode:
  12288. return this._gl.LINES;
  12289. case BABYLON.Material.LineLoopDrawMode:
  12290. return this._gl.LINE_LOOP;
  12291. case BABYLON.Material.LineStripDrawMode:
  12292. return this._gl.LINE_STRIP;
  12293. case BABYLON.Material.TriangleStripDrawMode:
  12294. return this._gl.TRIANGLE_STRIP;
  12295. case BABYLON.Material.TriangleFanDrawMode:
  12296. return this._gl.TRIANGLE_FAN;
  12297. default:
  12298. return this._gl.TRIANGLES;
  12299. }
  12300. };
  12301. // Shaders
  12302. Engine.prototype._releaseEffect = function (effect) {
  12303. if (this._compiledEffects[effect._key]) {
  12304. delete this._compiledEffects[effect._key];
  12305. this._deleteProgram(effect.getProgram());
  12306. }
  12307. };
  12308. Engine.prototype._deleteProgram = function (program) {
  12309. if (program) {
  12310. program.__SPECTOR_rebuildProgram = null;
  12311. if (program.transformFeedback) {
  12312. this.deleteTransformFeedback(program.transformFeedback);
  12313. program.transformFeedback = null;
  12314. }
  12315. this._gl.deleteProgram(program);
  12316. }
  12317. };
  12318. /**
  12319. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12320. * @param samplers An array of string used to represent textures
  12321. */
  12322. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12323. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12324. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12325. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12326. if (this._compiledEffects[name]) {
  12327. var compiledEffect = this._compiledEffects[name];
  12328. if (onCompiled && compiledEffect.isReady()) {
  12329. onCompiled(compiledEffect);
  12330. }
  12331. return compiledEffect;
  12332. }
  12333. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12334. effect._key = name;
  12335. this._compiledEffects[name] = effect;
  12336. return effect;
  12337. };
  12338. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12339. if (uniformsNames === void 0) { uniformsNames = []; }
  12340. if (samplers === void 0) { samplers = []; }
  12341. if (defines === void 0) { defines = ""; }
  12342. return this.createEffect({
  12343. vertex: "particles",
  12344. fragmentElement: fragmentName
  12345. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12346. };
  12347. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12348. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12349. context = context || this._gl;
  12350. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12351. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12352. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12353. };
  12354. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12355. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12356. context = context || this._gl;
  12357. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12358. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12359. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12360. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12361. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12362. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12363. return program;
  12364. };
  12365. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12366. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12367. var shaderProgram = context.createProgram();
  12368. if (!shaderProgram) {
  12369. throw new Error("Unable to create program");
  12370. }
  12371. context.attachShader(shaderProgram, vertexShader);
  12372. context.attachShader(shaderProgram, fragmentShader);
  12373. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12374. var transformFeedback = this.createTransformFeedback();
  12375. this.bindTransformFeedback(transformFeedback);
  12376. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12377. shaderProgram.transformFeedback = transformFeedback;
  12378. }
  12379. context.linkProgram(shaderProgram);
  12380. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12381. this.bindTransformFeedback(null);
  12382. }
  12383. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12384. if (!linked) {
  12385. context.validateProgram(shaderProgram);
  12386. var error = context.getProgramInfoLog(shaderProgram);
  12387. if (error) {
  12388. throw new Error(error);
  12389. }
  12390. }
  12391. context.deleteShader(vertexShader);
  12392. context.deleteShader(fragmentShader);
  12393. return shaderProgram;
  12394. };
  12395. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12396. var results = new Array();
  12397. for (var index = 0; index < uniformsNames.length; index++) {
  12398. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12399. }
  12400. return results;
  12401. };
  12402. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12403. var results = [];
  12404. for (var index = 0; index < attributesNames.length; index++) {
  12405. try {
  12406. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12407. }
  12408. catch (e) {
  12409. results.push(-1);
  12410. }
  12411. }
  12412. return results;
  12413. };
  12414. Engine.prototype.enableEffect = function (effect) {
  12415. if (!effect) {
  12416. return;
  12417. }
  12418. // Use program
  12419. this.bindSamplers(effect);
  12420. this._currentEffect = effect;
  12421. if (effect.onBind) {
  12422. effect.onBind(effect);
  12423. }
  12424. effect.onBindObservable.notifyObservers(effect);
  12425. };
  12426. Engine.prototype.setIntArray = function (uniform, array) {
  12427. if (!uniform)
  12428. return;
  12429. this._gl.uniform1iv(uniform, array);
  12430. };
  12431. Engine.prototype.setIntArray2 = function (uniform, array) {
  12432. if (!uniform || array.length % 2 !== 0)
  12433. return;
  12434. this._gl.uniform2iv(uniform, array);
  12435. };
  12436. Engine.prototype.setIntArray3 = function (uniform, array) {
  12437. if (!uniform || array.length % 3 !== 0)
  12438. return;
  12439. this._gl.uniform3iv(uniform, array);
  12440. };
  12441. Engine.prototype.setIntArray4 = function (uniform, array) {
  12442. if (!uniform || array.length % 4 !== 0)
  12443. return;
  12444. this._gl.uniform4iv(uniform, array);
  12445. };
  12446. Engine.prototype.setFloatArray = function (uniform, array) {
  12447. if (!uniform)
  12448. return;
  12449. this._gl.uniform1fv(uniform, array);
  12450. };
  12451. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12452. if (!uniform || array.length % 2 !== 0)
  12453. return;
  12454. this._gl.uniform2fv(uniform, array);
  12455. };
  12456. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12457. if (!uniform || array.length % 3 !== 0)
  12458. return;
  12459. this._gl.uniform3fv(uniform, array);
  12460. };
  12461. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12462. if (!uniform || array.length % 4 !== 0)
  12463. return;
  12464. this._gl.uniform4fv(uniform, array);
  12465. };
  12466. Engine.prototype.setArray = function (uniform, array) {
  12467. if (!uniform)
  12468. return;
  12469. this._gl.uniform1fv(uniform, array);
  12470. };
  12471. Engine.prototype.setArray2 = function (uniform, array) {
  12472. if (!uniform || array.length % 2 !== 0)
  12473. return;
  12474. this._gl.uniform2fv(uniform, array);
  12475. };
  12476. Engine.prototype.setArray3 = function (uniform, array) {
  12477. if (!uniform || array.length % 3 !== 0)
  12478. return;
  12479. this._gl.uniform3fv(uniform, array);
  12480. };
  12481. Engine.prototype.setArray4 = function (uniform, array) {
  12482. if (!uniform || array.length % 4 !== 0)
  12483. return;
  12484. this._gl.uniform4fv(uniform, array);
  12485. };
  12486. Engine.prototype.setMatrices = function (uniform, matrices) {
  12487. if (!uniform)
  12488. return;
  12489. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12490. };
  12491. Engine.prototype.setMatrix = function (uniform, matrix) {
  12492. if (!uniform)
  12493. return;
  12494. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12495. };
  12496. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12497. if (!uniform)
  12498. return;
  12499. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12500. };
  12501. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12502. if (!uniform)
  12503. return;
  12504. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12505. };
  12506. Engine.prototype.setInt = function (uniform, value) {
  12507. if (!uniform)
  12508. return;
  12509. this._gl.uniform1i(uniform, value);
  12510. };
  12511. Engine.prototype.setFloat = function (uniform, value) {
  12512. if (!uniform)
  12513. return;
  12514. this._gl.uniform1f(uniform, value);
  12515. };
  12516. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12517. if (!uniform)
  12518. return;
  12519. this._gl.uniform2f(uniform, x, y);
  12520. };
  12521. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12522. if (!uniform)
  12523. return;
  12524. this._gl.uniform3f(uniform, x, y, z);
  12525. };
  12526. Engine.prototype.setBool = function (uniform, bool) {
  12527. if (!uniform)
  12528. return;
  12529. this._gl.uniform1i(uniform, bool);
  12530. };
  12531. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12532. if (!uniform)
  12533. return;
  12534. this._gl.uniform4f(uniform, x, y, z, w);
  12535. };
  12536. Engine.prototype.setColor3 = function (uniform, color3) {
  12537. if (!uniform)
  12538. return;
  12539. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12540. };
  12541. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12542. if (!uniform)
  12543. return;
  12544. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12545. };
  12546. /**
  12547. * Sets a Color4 on a uniform variable
  12548. * @param uniform defines the uniform location
  12549. * @param color4 defines the value to be set
  12550. */
  12551. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12552. if (!uniform)
  12553. return;
  12554. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12555. };
  12556. // States
  12557. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12558. if (zOffset === void 0) { zOffset = 0; }
  12559. if (reverseSide === void 0) { reverseSide = false; }
  12560. // Culling
  12561. if (this._depthCullingState.cull !== culling || force) {
  12562. this._depthCullingState.cull = culling;
  12563. }
  12564. // Cull face
  12565. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12566. if (this._depthCullingState.cullFace !== cullFace || force) {
  12567. this._depthCullingState.cullFace = cullFace;
  12568. }
  12569. // Z offset
  12570. this.setZOffset(zOffset);
  12571. // Front face
  12572. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12573. if (this._depthCullingState.frontFace !== frontFace || force) {
  12574. this._depthCullingState.frontFace = frontFace;
  12575. }
  12576. };
  12577. Engine.prototype.setZOffset = function (value) {
  12578. this._depthCullingState.zOffset = value;
  12579. };
  12580. Engine.prototype.getZOffset = function () {
  12581. return this._depthCullingState.zOffset;
  12582. };
  12583. Engine.prototype.setDepthBuffer = function (enable) {
  12584. this._depthCullingState.depthTest = enable;
  12585. };
  12586. Engine.prototype.getDepthWrite = function () {
  12587. return this._depthCullingState.depthMask;
  12588. };
  12589. Engine.prototype.setDepthWrite = function (enable) {
  12590. this._depthCullingState.depthMask = enable;
  12591. };
  12592. Engine.prototype.setColorWrite = function (enable) {
  12593. this._gl.colorMask(enable, enable, enable, enable);
  12594. this._colorWrite = enable;
  12595. };
  12596. Engine.prototype.getColorWrite = function () {
  12597. return this._colorWrite;
  12598. };
  12599. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12600. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12601. };
  12602. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12603. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12604. if (this._alphaMode === mode) {
  12605. return;
  12606. }
  12607. switch (mode) {
  12608. case Engine.ALPHA_DISABLE:
  12609. this._alphaState.alphaBlend = false;
  12610. break;
  12611. case Engine.ALPHA_PREMULTIPLIED:
  12612. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12613. this._alphaState.alphaBlend = true;
  12614. break;
  12615. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12616. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12617. this._alphaState.alphaBlend = true;
  12618. break;
  12619. case Engine.ALPHA_COMBINE:
  12620. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12621. this._alphaState.alphaBlend = true;
  12622. break;
  12623. case Engine.ALPHA_ONEONE:
  12624. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12625. this._alphaState.alphaBlend = true;
  12626. break;
  12627. case Engine.ALPHA_ADD:
  12628. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12629. this._alphaState.alphaBlend = true;
  12630. break;
  12631. case Engine.ALPHA_SUBTRACT:
  12632. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12633. this._alphaState.alphaBlend = true;
  12634. break;
  12635. case Engine.ALPHA_MULTIPLY:
  12636. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12637. this._alphaState.alphaBlend = true;
  12638. break;
  12639. case Engine.ALPHA_MAXIMIZED:
  12640. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12641. this._alphaState.alphaBlend = true;
  12642. break;
  12643. case Engine.ALPHA_INTERPOLATE:
  12644. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12645. this._alphaState.alphaBlend = true;
  12646. break;
  12647. case Engine.ALPHA_SCREENMODE:
  12648. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12649. this._alphaState.alphaBlend = true;
  12650. break;
  12651. }
  12652. if (!noDepthWriteChange) {
  12653. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12654. }
  12655. this._alphaMode = mode;
  12656. };
  12657. Engine.prototype.getAlphaMode = function () {
  12658. return this._alphaMode;
  12659. };
  12660. // Textures
  12661. Engine.prototype.wipeCaches = function (bruteForce) {
  12662. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12663. return;
  12664. }
  12665. this._currentEffect = null;
  12666. // 6/8/2017: deltakosh: Should not be required anymore.
  12667. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12668. if (bruteForce) {
  12669. this.resetTextureCache();
  12670. this._currentProgram = null;
  12671. this._stencilState.reset();
  12672. this._depthCullingState.reset();
  12673. this.setDepthFunctionToLessOrEqual();
  12674. this._alphaState.reset();
  12675. }
  12676. this._resetVertexBufferBinding();
  12677. this._cachedIndexBuffer = null;
  12678. this._cachedEffectForVertexBuffers = null;
  12679. this._unbindVertexArrayObject();
  12680. this.bindIndexBuffer(null);
  12681. };
  12682. /**
  12683. * Set the compressed texture format to use, based on the formats you have, and the formats
  12684. * supported by the hardware / browser.
  12685. *
  12686. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12687. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12688. * to API arguments needed to compressed textures. This puts the burden on the container
  12689. * generator to house the arcane code for determining these for current & future formats.
  12690. *
  12691. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12692. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12693. *
  12694. * Note: The result of this call is not taken into account when a texture is base64.
  12695. *
  12696. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12697. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12698. *
  12699. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12700. * @returns The extension selected.
  12701. */
  12702. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12703. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12704. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12705. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12706. return this._textureFormatInUse = this._texturesSupported[i];
  12707. }
  12708. }
  12709. }
  12710. // actively set format to nothing, to allow this to be called more than once
  12711. // and possibly fail the 2nd time
  12712. this._textureFormatInUse = null;
  12713. return null;
  12714. };
  12715. Engine.prototype._createTexture = function () {
  12716. var texture = this._gl.createTexture();
  12717. if (!texture) {
  12718. throw new Error("Unable to create texture");
  12719. }
  12720. return texture;
  12721. };
  12722. /**
  12723. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12724. * @param {string} urlArg- This contains one of the following:
  12725. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12726. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12727. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12728. *
  12729. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12730. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12731. * @param {Scene} scene- Needed for loading to the correct scene.
  12732. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12733. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12734. * @param {callback} onError- Optional callback to be called upon failure.
  12735. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12736. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12737. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12738. *
  12739. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12740. */
  12741. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12742. var _this = this;
  12743. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12744. if (onLoad === void 0) { onLoad = null; }
  12745. if (onError === void 0) { onError = null; }
  12746. if (buffer === void 0) { buffer = null; }
  12747. if (fallBack === void 0) { fallBack = null; }
  12748. if (format === void 0) { format = null; }
  12749. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12750. var fromData = url.substr(0, 5) === "data:";
  12751. var fromBlob = url.substr(0, 5) === "blob:";
  12752. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12753. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12754. // establish the file extension, if possible
  12755. var lastDot = url.lastIndexOf('.');
  12756. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12757. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12758. var isTGA = (extension.indexOf(".tga") === 0);
  12759. // determine if a ktx file should be substituted
  12760. var isKTX = false;
  12761. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12762. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12763. isKTX = true;
  12764. }
  12765. if (scene) {
  12766. scene._addPendingData(texture);
  12767. }
  12768. texture.url = url;
  12769. texture.generateMipMaps = !noMipmap;
  12770. texture.samplingMode = samplingMode;
  12771. texture.invertY = invertY;
  12772. if (!this._doNotHandleContextLost) {
  12773. // Keep a link to the buffer only if we plan to handle context lost
  12774. texture._buffer = buffer;
  12775. }
  12776. var onLoadObserver = null;
  12777. if (onLoad && !fallBack) {
  12778. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12779. }
  12780. if (!fallBack)
  12781. this._internalTexturesCache.push(texture);
  12782. var onerror = function (message, exception) {
  12783. if (scene) {
  12784. scene._removePendingData(texture);
  12785. }
  12786. if (onLoadObserver) {
  12787. texture.onLoadedObservable.remove(onLoadObserver);
  12788. }
  12789. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12790. if (isKTX) {
  12791. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12792. }
  12793. else if (BABYLON.Tools.UseFallbackTexture) {
  12794. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12795. }
  12796. if (onError) {
  12797. onError(message || "Unknown error", exception);
  12798. }
  12799. };
  12800. var callback = null;
  12801. // processing for non-image formats
  12802. if (isKTX || isTGA || isDDS) {
  12803. if (isKTX) {
  12804. callback = function (data) {
  12805. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12806. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12807. ktx.uploadLevels(_this._gl, !noMipmap);
  12808. return false;
  12809. }, samplingMode);
  12810. };
  12811. }
  12812. else if (isTGA) {
  12813. callback = function (arrayBuffer) {
  12814. var data = new Uint8Array(arrayBuffer);
  12815. var header = BABYLON.TGATools.GetTGAHeader(data);
  12816. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12817. BABYLON.TGATools.UploadContent(_this._gl, data);
  12818. return false;
  12819. }, samplingMode);
  12820. };
  12821. }
  12822. else if (isDDS) {
  12823. callback = function (data) {
  12824. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12825. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12826. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12827. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12828. return false;
  12829. }, samplingMode);
  12830. };
  12831. }
  12832. if (!buffer) {
  12833. this._loadFile(url, function (data) {
  12834. if (callback) {
  12835. callback(data);
  12836. }
  12837. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12838. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12839. });
  12840. }
  12841. else {
  12842. if (callback) {
  12843. callback(buffer);
  12844. }
  12845. }
  12846. // image format processing
  12847. }
  12848. else {
  12849. var onload = function (img) {
  12850. if (fromBlob && !_this._doNotHandleContextLost) {
  12851. // We need to store the image if we need to rebuild the texture
  12852. // in case of a webgl context lost
  12853. texture._buffer = img;
  12854. }
  12855. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12856. var gl = _this._gl;
  12857. var isPot = (img.width === potWidth && img.height === potHeight);
  12858. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12859. if (isPot) {
  12860. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12861. return false;
  12862. }
  12863. // Using shaders to rescale because canvas.drawImage is lossy
  12864. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12865. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12866. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12868. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12869. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12871. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12872. _this._releaseTexture(source);
  12873. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12874. continuationCallback();
  12875. });
  12876. return true;
  12877. }, samplingMode);
  12878. };
  12879. if (!fromData || isBase64)
  12880. if (buffer instanceof HTMLImageElement) {
  12881. onload(buffer);
  12882. }
  12883. else {
  12884. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12885. }
  12886. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12887. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12888. else
  12889. onload(buffer);
  12890. }
  12891. return texture;
  12892. };
  12893. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12894. var _this = this;
  12895. var rtt = this.createRenderTargetTexture({
  12896. width: destination.width,
  12897. height: destination.height,
  12898. }, {
  12899. generateMipMaps: false,
  12900. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12901. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12902. generateDepthBuffer: false,
  12903. generateStencilBuffer: false
  12904. });
  12905. if (!this._rescalePostProcess) {
  12906. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12907. }
  12908. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12909. _this._rescalePostProcess.onApply = function (effect) {
  12910. effect._bindTexture("textureSampler", source);
  12911. };
  12912. var hostingScene = scene;
  12913. if (!hostingScene) {
  12914. hostingScene = _this.scenes[_this.scenes.length - 1];
  12915. }
  12916. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12917. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12918. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12919. _this.unBindFramebuffer(rtt);
  12920. _this._releaseTexture(rtt);
  12921. if (onComplete) {
  12922. onComplete();
  12923. }
  12924. });
  12925. };
  12926. Engine.prototype._getInternalFormat = function (format) {
  12927. var internalFormat = this._gl.RGBA;
  12928. switch (format) {
  12929. case Engine.TEXTUREFORMAT_ALPHA:
  12930. internalFormat = this._gl.ALPHA;
  12931. break;
  12932. case Engine.TEXTUREFORMAT_LUMINANCE:
  12933. internalFormat = this._gl.LUMINANCE;
  12934. break;
  12935. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12936. internalFormat = this._gl.LUMINANCE_ALPHA;
  12937. break;
  12938. case Engine.TEXTUREFORMAT_RGB:
  12939. case Engine.TEXTUREFORMAT_RGB32F:
  12940. internalFormat = this._gl.RGB;
  12941. break;
  12942. case Engine.TEXTUREFORMAT_RGBA:
  12943. internalFormat = this._gl.RGBA;
  12944. break;
  12945. case Engine.TEXTUREFORMAT_R32F:
  12946. internalFormat = this._gl.RED;
  12947. break;
  12948. case Engine.TEXTUREFORMAT_RG32F:
  12949. internalFormat = this._gl.RG;
  12950. break;
  12951. }
  12952. return internalFormat;
  12953. };
  12954. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12955. if (compression === void 0) { compression = null; }
  12956. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12957. if (!texture) {
  12958. return;
  12959. }
  12960. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  12961. var internalFormat = this._getInternalFormat(format);
  12962. var textureType = this._getWebGLTextureType(type);
  12963. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12964. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12965. if (!this._doNotHandleContextLost) {
  12966. texture._bufferView = data;
  12967. texture.format = format;
  12968. texture.type = type;
  12969. texture.invertY = invertY;
  12970. texture._compression = compression;
  12971. }
  12972. if (texture.width % 4 !== 0) {
  12973. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12974. }
  12975. if (compression && data) {
  12976. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12977. }
  12978. else {
  12979. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12980. }
  12981. if (texture.generateMipMaps) {
  12982. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12983. }
  12984. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12985. // this.resetTextureCache();
  12986. texture.isReady = true;
  12987. };
  12988. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12989. if (compression === void 0) { compression = null; }
  12990. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12991. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12992. texture.baseWidth = width;
  12993. texture.baseHeight = height;
  12994. texture.width = width;
  12995. texture.height = height;
  12996. texture.format = format;
  12997. texture.generateMipMaps = generateMipMaps;
  12998. texture.samplingMode = samplingMode;
  12999. texture.invertY = invertY;
  13000. texture._compression = compression;
  13001. texture.type = type;
  13002. if (!this._doNotHandleContextLost) {
  13003. texture._bufferView = data;
  13004. }
  13005. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13006. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13007. // Filters
  13008. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13009. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13010. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13011. if (generateMipMaps) {
  13012. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13013. }
  13014. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13015. this._internalTexturesCache.push(texture);
  13016. return texture;
  13017. };
  13018. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13019. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13020. texture.baseWidth = width;
  13021. texture.baseHeight = height;
  13022. if (generateMipMaps) {
  13023. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13024. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13025. }
  13026. // this.resetTextureCache();
  13027. texture.width = width;
  13028. texture.height = height;
  13029. texture.isReady = false;
  13030. texture.generateMipMaps = generateMipMaps;
  13031. texture.samplingMode = samplingMode;
  13032. this.updateTextureSamplingMode(samplingMode, texture);
  13033. this._internalTexturesCache.push(texture);
  13034. return texture;
  13035. };
  13036. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13037. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13038. if (texture.isCube) {
  13039. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13040. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13041. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13042. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13043. }
  13044. else if (texture.is3D) {
  13045. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13046. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13047. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13048. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13049. }
  13050. else {
  13051. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13052. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13053. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13054. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13055. }
  13056. texture.samplingMode = samplingMode;
  13057. };
  13058. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13059. if (premulAlpha === void 0) { premulAlpha = false; }
  13060. if (!texture) {
  13061. return;
  13062. }
  13063. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13064. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13065. if (premulAlpha) {
  13066. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13067. }
  13068. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13069. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13070. if (texture.generateMipMaps) {
  13071. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13072. }
  13073. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13074. if (premulAlpha) {
  13075. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13076. }
  13077. texture.isReady = true;
  13078. };
  13079. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13080. if (!texture || texture._isDisabled) {
  13081. return;
  13082. }
  13083. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13084. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13085. try {
  13086. // Testing video texture support
  13087. if (this._videoTextureSupported === undefined) {
  13088. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13089. if (this._gl.getError() !== 0) {
  13090. this._videoTextureSupported = false;
  13091. }
  13092. else {
  13093. this._videoTextureSupported = true;
  13094. }
  13095. }
  13096. // Copy video through the current working canvas if video texture is not supported
  13097. if (!this._videoTextureSupported) {
  13098. if (!texture._workingCanvas) {
  13099. texture._workingCanvas = document.createElement("canvas");
  13100. var context = texture._workingCanvas.getContext("2d");
  13101. if (!context) {
  13102. throw new Error("Unable to get 2d context");
  13103. }
  13104. texture._workingContext = context;
  13105. texture._workingCanvas.width = texture.width;
  13106. texture._workingCanvas.height = texture.height;
  13107. }
  13108. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13109. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13110. }
  13111. else {
  13112. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13113. }
  13114. if (texture.generateMipMaps) {
  13115. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13116. }
  13117. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13118. // this.resetTextureCache();
  13119. texture.isReady = true;
  13120. }
  13121. catch (ex) {
  13122. // Something unexpected
  13123. // Let's disable the texture
  13124. texture._isDisabled = true;
  13125. }
  13126. };
  13127. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13128. var fullOptions = new RenderTargetCreationOptions();
  13129. if (options !== undefined && typeof options === "object") {
  13130. fullOptions.generateMipMaps = options.generateMipMaps;
  13131. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13132. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13133. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13134. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13135. }
  13136. else {
  13137. fullOptions.generateMipMaps = options;
  13138. fullOptions.generateDepthBuffer = true;
  13139. fullOptions.generateStencilBuffer = false;
  13140. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13141. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13142. }
  13143. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13144. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13145. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13146. }
  13147. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13148. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13149. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13150. }
  13151. var gl = this._gl;
  13152. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13153. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13154. var width = size.width || size;
  13155. var height = size.height || size;
  13156. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13157. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13158. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13159. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13160. }
  13161. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13164. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13165. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13166. // Create the framebuffer
  13167. var framebuffer = gl.createFramebuffer();
  13168. this.bindUnboundFramebuffer(framebuffer);
  13169. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13170. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13171. if (fullOptions.generateMipMaps) {
  13172. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13173. }
  13174. // Unbind
  13175. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13176. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13177. this.bindUnboundFramebuffer(null);
  13178. texture._framebuffer = framebuffer;
  13179. texture.baseWidth = width;
  13180. texture.baseHeight = height;
  13181. texture.width = width;
  13182. texture.height = height;
  13183. texture.isReady = true;
  13184. texture.samples = 1;
  13185. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13186. texture.samplingMode = fullOptions.samplingMode;
  13187. texture.type = fullOptions.type;
  13188. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13189. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13190. // this.resetTextureCache();
  13191. this._internalTexturesCache.push(texture);
  13192. return texture;
  13193. };
  13194. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13195. var generateMipMaps = false;
  13196. var generateDepthBuffer = true;
  13197. var generateStencilBuffer = false;
  13198. var generateDepthTexture = false;
  13199. var textureCount = 1;
  13200. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13201. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13202. var types = [], samplingModes = [];
  13203. if (options !== undefined) {
  13204. generateMipMaps = options.generateMipMaps;
  13205. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13206. generateStencilBuffer = options.generateStencilBuffer;
  13207. generateDepthTexture = options.generateDepthTexture;
  13208. textureCount = options.textureCount || 1;
  13209. if (options.types) {
  13210. types = options.types;
  13211. }
  13212. if (options.samplingModes) {
  13213. samplingModes = options.samplingModes;
  13214. }
  13215. }
  13216. var gl = this._gl;
  13217. // Create the framebuffer
  13218. var framebuffer = gl.createFramebuffer();
  13219. this.bindUnboundFramebuffer(framebuffer);
  13220. var width = size.width || size;
  13221. var height = size.height || size;
  13222. var textures = [];
  13223. var attachments = [];
  13224. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13225. for (var i = 0; i < textureCount; i++) {
  13226. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13227. var type = types[i] || defaultType;
  13228. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13229. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13230. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13231. }
  13232. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13233. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13234. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13235. }
  13236. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13237. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13238. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13239. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13240. }
  13241. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13242. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13243. textures.push(texture);
  13244. attachments.push(attachment);
  13245. gl.activeTexture(gl["TEXTURE" + i]);
  13246. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13249. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13250. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13251. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13252. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13253. if (generateMipMaps) {
  13254. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13255. }
  13256. // Unbind
  13257. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13258. texture._framebuffer = framebuffer;
  13259. texture._depthStencilBuffer = depthStencilBuffer;
  13260. texture.baseWidth = width;
  13261. texture.baseHeight = height;
  13262. texture.width = width;
  13263. texture.height = height;
  13264. texture.isReady = true;
  13265. texture.samples = 1;
  13266. texture.generateMipMaps = generateMipMaps;
  13267. texture.samplingMode = samplingMode;
  13268. texture.type = type;
  13269. texture._generateDepthBuffer = generateDepthBuffer;
  13270. texture._generateStencilBuffer = generateStencilBuffer;
  13271. texture._attachments = attachments;
  13272. this._internalTexturesCache.push(texture);
  13273. }
  13274. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13275. // Depth texture
  13276. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13277. gl.activeTexture(gl.TEXTURE0);
  13278. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13279. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13280. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13281. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13282. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13283. 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);
  13284. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13285. depthTexture._framebuffer = framebuffer;
  13286. depthTexture.baseWidth = width;
  13287. depthTexture.baseHeight = height;
  13288. depthTexture.width = width;
  13289. depthTexture.height = height;
  13290. depthTexture.isReady = true;
  13291. depthTexture.samples = 1;
  13292. depthTexture.generateMipMaps = generateMipMaps;
  13293. depthTexture.samplingMode = gl.NEAREST;
  13294. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13295. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13296. textures.push(depthTexture);
  13297. this._internalTexturesCache.push(depthTexture);
  13298. }
  13299. gl.drawBuffers(attachments);
  13300. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13301. this.bindUnboundFramebuffer(null);
  13302. this.resetTextureCache();
  13303. return textures;
  13304. };
  13305. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13306. if (samples === void 0) { samples = 1; }
  13307. var depthStencilBuffer = null;
  13308. var gl = this._gl;
  13309. // Create the depth/stencil buffer
  13310. if (generateStencilBuffer) {
  13311. depthStencilBuffer = gl.createRenderbuffer();
  13312. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13313. if (samples > 1) {
  13314. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13315. }
  13316. else {
  13317. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13318. }
  13319. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13320. }
  13321. else if (generateDepthBuffer) {
  13322. depthStencilBuffer = gl.createRenderbuffer();
  13323. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13324. if (samples > 1) {
  13325. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13326. }
  13327. else {
  13328. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13329. }
  13330. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13331. }
  13332. return depthStencilBuffer;
  13333. };
  13334. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13335. if (this.webGLVersion < 2 || !texture) {
  13336. return 1;
  13337. }
  13338. if (texture.samples === samples) {
  13339. return samples;
  13340. }
  13341. var gl = this._gl;
  13342. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13343. // Dispose previous render buffers
  13344. if (texture._depthStencilBuffer) {
  13345. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13346. texture._depthStencilBuffer = null;
  13347. }
  13348. if (texture._MSAAFramebuffer) {
  13349. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13350. texture._MSAAFramebuffer = null;
  13351. }
  13352. if (texture._MSAARenderBuffer) {
  13353. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13354. texture._MSAARenderBuffer = null;
  13355. }
  13356. if (samples > 1) {
  13357. var framebuffer = gl.createFramebuffer();
  13358. if (!framebuffer) {
  13359. throw new Error("Unable to create multi sampled framebuffer");
  13360. }
  13361. texture._MSAAFramebuffer = framebuffer;
  13362. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13363. var colorRenderbuffer = gl.createRenderbuffer();
  13364. if (!colorRenderbuffer) {
  13365. throw new Error("Unable to create multi sampled framebuffer");
  13366. }
  13367. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13368. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13369. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13370. texture._MSAARenderBuffer = colorRenderbuffer;
  13371. }
  13372. else {
  13373. this.bindUnboundFramebuffer(texture._framebuffer);
  13374. }
  13375. texture.samples = samples;
  13376. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13377. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13378. this.bindUnboundFramebuffer(null);
  13379. return samples;
  13380. };
  13381. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13382. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13383. return 1;
  13384. }
  13385. if (textures[0].samples === samples) {
  13386. return samples;
  13387. }
  13388. var gl = this._gl;
  13389. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13390. // Dispose previous render buffers
  13391. if (textures[0]._depthStencilBuffer) {
  13392. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13393. textures[0]._depthStencilBuffer = null;
  13394. }
  13395. if (textures[0]._MSAAFramebuffer) {
  13396. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13397. textures[0]._MSAAFramebuffer = null;
  13398. }
  13399. for (var i = 0; i < textures.length; i++) {
  13400. if (textures[i]._MSAARenderBuffer) {
  13401. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13402. textures[i]._MSAARenderBuffer = null;
  13403. }
  13404. }
  13405. if (samples > 1) {
  13406. var framebuffer = gl.createFramebuffer();
  13407. if (!framebuffer) {
  13408. throw new Error("Unable to create multi sampled framebuffer");
  13409. }
  13410. this.bindUnboundFramebuffer(framebuffer);
  13411. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13412. var attachments = [];
  13413. for (var i = 0; i < textures.length; i++) {
  13414. var texture = textures[i];
  13415. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13416. var colorRenderbuffer = gl.createRenderbuffer();
  13417. if (!colorRenderbuffer) {
  13418. throw new Error("Unable to create multi sampled framebuffer");
  13419. }
  13420. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13421. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13422. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13423. texture._MSAAFramebuffer = framebuffer;
  13424. texture._MSAARenderBuffer = colorRenderbuffer;
  13425. texture.samples = samples;
  13426. texture._depthStencilBuffer = depthStencilBuffer;
  13427. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13428. attachments.push(attachment);
  13429. }
  13430. gl.drawBuffers(attachments);
  13431. }
  13432. else {
  13433. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13434. }
  13435. this.bindUnboundFramebuffer(null);
  13436. return samples;
  13437. };
  13438. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13439. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13440. };
  13441. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13442. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13443. };
  13444. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13445. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13446. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13447. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13448. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13449. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13450. }
  13451. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13452. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13453. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13454. }
  13455. var gl = this._gl;
  13456. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13457. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13458. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13459. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13460. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13461. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13462. }
  13463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13465. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13467. for (var face = 0; face < 6; face++) {
  13468. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13469. }
  13470. // Create the framebuffer
  13471. var framebuffer = gl.createFramebuffer();
  13472. this.bindUnboundFramebuffer(framebuffer);
  13473. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13474. // MipMaps
  13475. if (fullOptions.generateMipMaps) {
  13476. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13477. }
  13478. // Unbind
  13479. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13480. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13481. this.bindUnboundFramebuffer(null);
  13482. texture._framebuffer = framebuffer;
  13483. texture.width = size;
  13484. texture.height = size;
  13485. texture.isReady = true;
  13486. texture.isCube = true;
  13487. texture.samples = 1;
  13488. texture.generateMipMaps = fullOptions.generateMipMaps;
  13489. texture.samplingMode = fullOptions.samplingMode;
  13490. texture.type = fullOptions.type;
  13491. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13492. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13493. this._internalTexturesCache.push(texture);
  13494. return texture;
  13495. };
  13496. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13497. var _this = this;
  13498. if (onLoad === void 0) { onLoad = null; }
  13499. if (onError === void 0) { onError = null; }
  13500. if (forcedExtension === void 0) { forcedExtension = null; }
  13501. var callback = function (loadData) {
  13502. if (!loadData) {
  13503. if (onLoad) {
  13504. onLoad(null);
  13505. }
  13506. return;
  13507. }
  13508. var texture = loadData.texture;
  13509. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13510. texture._lodGenerationScale = scale;
  13511. texture._lodGenerationOffset = offset;
  13512. if (_this._caps.textureLOD) {
  13513. // Do not add extra process if texture lod is supported.
  13514. if (onLoad) {
  13515. onLoad(texture);
  13516. }
  13517. return;
  13518. }
  13519. var mipSlices = 3;
  13520. var gl = _this._gl;
  13521. var width = loadData.width;
  13522. if (!width) {
  13523. return;
  13524. }
  13525. var textures = [];
  13526. for (var i = 0; i < mipSlices; i++) {
  13527. //compute LOD from even spacing in smoothness (matching shader calculation)
  13528. var smoothness = i / (mipSlices - 1);
  13529. var roughness = 1 - smoothness;
  13530. var minLODIndex = offset; // roughness = 0
  13531. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13532. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13533. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13534. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13535. glTextureFromLod.isCube = true;
  13536. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13537. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13538. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13539. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13540. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13541. if (loadData.isDDS) {
  13542. var info = loadData.info;
  13543. var data = loadData.data;
  13544. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13545. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13546. }
  13547. else {
  13548. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13549. }
  13550. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13551. // Wrap in a base texture for easy binding.
  13552. var lodTexture = new BABYLON.BaseTexture(scene);
  13553. lodTexture.isCube = true;
  13554. lodTexture._texture = glTextureFromLod;
  13555. glTextureFromLod.isReady = true;
  13556. textures.push(lodTexture);
  13557. }
  13558. texture._lodTextureHigh = textures[2];
  13559. texture._lodTextureMid = textures[1];
  13560. texture._lodTextureLow = textures[0];
  13561. if (onLoad) {
  13562. onLoad(texture);
  13563. }
  13564. };
  13565. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13566. };
  13567. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13568. var _this = this;
  13569. if (onLoad === void 0) { onLoad = null; }
  13570. if (onError === void 0) { onError = null; }
  13571. if (forcedExtension === void 0) { forcedExtension = null; }
  13572. var gl = this._gl;
  13573. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13574. texture.isCube = true;
  13575. texture.url = rootUrl;
  13576. texture.generateMipMaps = !noMipmap;
  13577. if (!this._doNotHandleContextLost) {
  13578. texture._extension = forcedExtension;
  13579. texture._files = files;
  13580. }
  13581. var isKTX = false;
  13582. var isDDS = false;
  13583. var lastDot = rootUrl.lastIndexOf('.');
  13584. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13585. if (this._textureFormatInUse) {
  13586. extension = this._textureFormatInUse;
  13587. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13588. isKTX = true;
  13589. }
  13590. else {
  13591. isDDS = (extension === ".dds");
  13592. }
  13593. var onerror = function (request, exception) {
  13594. if (onError && request) {
  13595. onError(request.status + " " + request.statusText, exception);
  13596. }
  13597. };
  13598. if (isKTX) {
  13599. this._loadFile(rootUrl, function (data) {
  13600. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13601. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13602. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13603. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13604. ktx.uploadLevels(_this._gl, !noMipmap);
  13605. _this.setCubeMapTextureParams(gl, loadMipmap);
  13606. texture.width = ktx.pixelWidth;
  13607. texture.height = ktx.pixelHeight;
  13608. texture.isReady = true;
  13609. }, undefined, undefined, true, onerror);
  13610. }
  13611. else if (isDDS) {
  13612. if (files && files.length === 6) {
  13613. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13614. var info;
  13615. var loadMipmap = false;
  13616. var width = 0;
  13617. for (var index = 0; index < imgs.length; index++) {
  13618. var data = imgs[index];
  13619. info = BABYLON.DDSTools.GetDDSInfo(data);
  13620. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13621. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13622. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13623. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13624. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13625. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13626. }
  13627. texture.width = info.width;
  13628. texture.height = info.height;
  13629. texture.type = info.textureType;
  13630. width = info.width;
  13631. }
  13632. _this.setCubeMapTextureParams(gl, loadMipmap);
  13633. texture.isReady = true;
  13634. if (onLoad) {
  13635. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13636. }
  13637. }, files, onError);
  13638. }
  13639. else {
  13640. this._loadFile(rootUrl, function (data) {
  13641. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13642. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13643. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13644. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13645. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13646. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13647. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13648. }
  13649. _this.setCubeMapTextureParams(gl, loadMipmap);
  13650. texture.width = info.width;
  13651. texture.height = info.height;
  13652. texture.isReady = true;
  13653. texture.type = info.textureType;
  13654. if (onLoad) {
  13655. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13656. }
  13657. }, undefined, undefined, true, onerror);
  13658. }
  13659. }
  13660. else {
  13661. if (!files) {
  13662. throw new Error("Cannot load cubemap because files were not defined");
  13663. }
  13664. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13665. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13666. var height = width;
  13667. _this._prepareWorkingCanvas();
  13668. if (!_this._workingCanvas || !_this._workingContext) {
  13669. return;
  13670. }
  13671. _this._workingCanvas.width = width;
  13672. _this._workingCanvas.height = height;
  13673. var faces = [
  13674. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13675. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13676. ];
  13677. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13678. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13679. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13680. for (var index = 0; index < faces.length; index++) {
  13681. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13682. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13683. }
  13684. if (!noMipmap) {
  13685. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13686. }
  13687. _this.setCubeMapTextureParams(gl, !noMipmap);
  13688. texture.width = width;
  13689. texture.height = height;
  13690. texture.isReady = true;
  13691. if (format) {
  13692. texture.format = format;
  13693. }
  13694. texture.onLoadedObservable.notifyObservers(texture);
  13695. texture.onLoadedObservable.clear();
  13696. if (onLoad) {
  13697. onLoad();
  13698. }
  13699. }, files, onError);
  13700. }
  13701. this._internalTexturesCache.push(texture);
  13702. return texture;
  13703. };
  13704. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13705. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13706. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13707. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13708. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13709. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13710. // this.resetTextureCache();
  13711. };
  13712. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13713. if (compression === void 0) { compression = null; }
  13714. if (level === void 0) { level = 0; }
  13715. texture._bufferViewArray = data;
  13716. texture.format = format;
  13717. texture.type = type;
  13718. texture.invertY = invertY;
  13719. texture._compression = compression;
  13720. var gl = this._gl;
  13721. var textureType = this._getWebGLTextureType(type);
  13722. var internalFormat = this._getInternalFormat(format);
  13723. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13724. var needConversion = false;
  13725. if (internalFormat === gl.RGB) {
  13726. internalFormat = gl.RGBA;
  13727. needConversion = true;
  13728. }
  13729. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13730. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13731. if (texture.width % 4 !== 0) {
  13732. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13733. }
  13734. // Data are known to be in +X +Y +Z -X -Y -Z
  13735. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13736. var faceData = data[faceIndex];
  13737. if (compression) {
  13738. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13739. }
  13740. else {
  13741. if (needConversion) {
  13742. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13743. }
  13744. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13745. }
  13746. }
  13747. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13748. if (isPot && texture.generateMipMaps && level === 0) {
  13749. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13750. }
  13751. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13752. // this.resetTextureCache();
  13753. texture.isReady = true;
  13754. };
  13755. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13756. if (compression === void 0) { compression = null; }
  13757. var gl = this._gl;
  13758. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13759. texture.isCube = true;
  13760. texture.generateMipMaps = generateMipMaps;
  13761. texture.format = format;
  13762. texture.type = type;
  13763. if (!this._doNotHandleContextLost) {
  13764. texture._bufferViewArray = data;
  13765. }
  13766. var textureType = this._getWebGLTextureType(type);
  13767. var internalFormat = this._getInternalFormat(format);
  13768. if (internalFormat === gl.RGB) {
  13769. internalFormat = gl.RGBA;
  13770. }
  13771. var width = size;
  13772. var height = width;
  13773. texture.width = width;
  13774. texture.height = height;
  13775. // Double check on POT to generate Mips.
  13776. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13777. if (!isPot) {
  13778. generateMipMaps = false;
  13779. }
  13780. // Upload data if needed. The texture won't be ready until then.
  13781. if (data) {
  13782. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13783. }
  13784. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13785. // Filters
  13786. if (data && generateMipMaps) {
  13787. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13788. }
  13789. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13790. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13792. }
  13793. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13796. }
  13797. else {
  13798. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13801. }
  13802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13804. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13805. return texture;
  13806. };
  13807. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13808. var _this = this;
  13809. if (onLoad === void 0) { onLoad = null; }
  13810. if (onError === void 0) { onError = null; }
  13811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13812. if (invertY === void 0) { invertY = false; }
  13813. var gl = this._gl;
  13814. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13815. scene._addPendingData(texture);
  13816. texture.url = url;
  13817. this._internalTexturesCache.push(texture);
  13818. var onerror = function (request, exception) {
  13819. scene._removePendingData(texture);
  13820. if (onError && request) {
  13821. onError(request.status + " " + request.statusText, exception);
  13822. }
  13823. };
  13824. var internalCallback = function (data) {
  13825. var width = texture.width;
  13826. var faceDataArrays = callback(data);
  13827. if (!faceDataArrays) {
  13828. return;
  13829. }
  13830. if (mipmmapGenerator) {
  13831. var textureType = _this._getWebGLTextureType(type);
  13832. var internalFormat = _this._getInternalFormat(format);
  13833. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13834. var needConversion = false;
  13835. if (internalFormat === gl.RGB) {
  13836. internalFormat = gl.RGBA;
  13837. needConversion = true;
  13838. }
  13839. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13840. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13841. var mipData = mipmmapGenerator(faceDataArrays);
  13842. for (var level = 0; level < mipData.length; level++) {
  13843. var mipSize = width >> level;
  13844. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13845. var mipFaceData = mipData[level][faceIndex];
  13846. if (needConversion) {
  13847. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13848. }
  13849. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13850. }
  13851. }
  13852. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13853. }
  13854. else {
  13855. texture.generateMipMaps = !noMipmap;
  13856. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13857. }
  13858. texture.isReady = true;
  13859. // this.resetTextureCache();
  13860. scene._removePendingData(texture);
  13861. if (onLoad) {
  13862. onLoad();
  13863. }
  13864. };
  13865. this._loadFile(url, function (data) {
  13866. internalCallback(data);
  13867. }, undefined, scene.database, true, onerror);
  13868. return texture;
  13869. };
  13870. ;
  13871. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13872. if (compression === void 0) { compression = null; }
  13873. var internalFormat = this._getInternalFormat(format);
  13874. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13875. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13876. if (!this._doNotHandleContextLost) {
  13877. texture._bufferView = data;
  13878. texture.format = format;
  13879. texture.invertY = invertY;
  13880. texture._compression = compression;
  13881. }
  13882. if (texture.width % 4 !== 0) {
  13883. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13884. }
  13885. if (compression && data) {
  13886. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13887. }
  13888. else {
  13889. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13890. }
  13891. if (texture.generateMipMaps) {
  13892. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13893. }
  13894. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13895. // this.resetTextureCache();
  13896. texture.isReady = true;
  13897. };
  13898. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13899. if (compression === void 0) { compression = null; }
  13900. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13901. texture.baseWidth = width;
  13902. texture.baseHeight = height;
  13903. texture.baseDepth = depth;
  13904. texture.width = width;
  13905. texture.height = height;
  13906. texture.depth = depth;
  13907. texture.format = format;
  13908. texture.generateMipMaps = generateMipMaps;
  13909. texture.samplingMode = samplingMode;
  13910. texture.is3D = true;
  13911. if (!this._doNotHandleContextLost) {
  13912. texture._bufferView = data;
  13913. }
  13914. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13915. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13916. // Filters
  13917. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13918. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13919. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13920. if (generateMipMaps) {
  13921. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13922. }
  13923. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13924. this._internalTexturesCache.push(texture);
  13925. return texture;
  13926. };
  13927. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13928. var gl = this._gl;
  13929. if (!gl) {
  13930. return;
  13931. }
  13932. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13933. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13934. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13935. if (!noMipmap && !isCompressed) {
  13936. gl.generateMipmap(gl.TEXTURE_2D);
  13937. }
  13938. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13939. // this.resetTextureCache();
  13940. if (scene) {
  13941. scene._removePendingData(texture);
  13942. }
  13943. texture.onLoadedObservable.notifyObservers(texture);
  13944. texture.onLoadedObservable.clear();
  13945. };
  13946. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13947. var _this = this;
  13948. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13949. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13950. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13951. var gl = this._gl;
  13952. if (!gl) {
  13953. return;
  13954. }
  13955. if (!texture._webGLTexture) {
  13956. // this.resetTextureCache();
  13957. if (scene) {
  13958. scene._removePendingData(texture);
  13959. }
  13960. return;
  13961. }
  13962. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13963. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13964. texture.baseWidth = width;
  13965. texture.baseHeight = height;
  13966. texture.width = potWidth;
  13967. texture.height = potHeight;
  13968. texture.isReady = true;
  13969. if (processFunction(potWidth, potHeight, function () {
  13970. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13971. })) {
  13972. // Returning as texture needs extra async steps
  13973. return;
  13974. }
  13975. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13976. };
  13977. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13978. // Create new RGBA data container.
  13979. var rgbaData;
  13980. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13981. rgbaData = new Float32Array(width * height * 4);
  13982. }
  13983. else {
  13984. rgbaData = new Uint32Array(width * height * 4);
  13985. }
  13986. // Convert each pixel.
  13987. for (var x = 0; x < width; x++) {
  13988. for (var y = 0; y < height; y++) {
  13989. var index = (y * width + x) * 3;
  13990. var newIndex = (y * width + x) * 4;
  13991. // Map Old Value to new value.
  13992. rgbaData[newIndex + 0] = rgbData[index + 0];
  13993. rgbaData[newIndex + 1] = rgbData[index + 1];
  13994. rgbaData[newIndex + 2] = rgbData[index + 2];
  13995. // Add fully opaque alpha channel.
  13996. rgbaData[newIndex + 3] = 1;
  13997. }
  13998. }
  13999. return rgbaData;
  14000. };
  14001. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14002. var gl = this._gl;
  14003. if (texture._framebuffer) {
  14004. gl.deleteFramebuffer(texture._framebuffer);
  14005. texture._framebuffer = null;
  14006. }
  14007. if (texture._depthStencilBuffer) {
  14008. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14009. texture._depthStencilBuffer = null;
  14010. }
  14011. if (texture._MSAAFramebuffer) {
  14012. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14013. texture._MSAAFramebuffer = null;
  14014. }
  14015. if (texture._MSAARenderBuffer) {
  14016. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14017. texture._MSAARenderBuffer = null;
  14018. }
  14019. };
  14020. Engine.prototype._releaseTexture = function (texture) {
  14021. var gl = this._gl;
  14022. this._releaseFramebufferObjects(texture);
  14023. gl.deleteTexture(texture._webGLTexture);
  14024. // Unbind channels
  14025. this.unbindAllTextures();
  14026. var index = this._internalTexturesCache.indexOf(texture);
  14027. if (index !== -1) {
  14028. this._internalTexturesCache.splice(index, 1);
  14029. }
  14030. // Integrated fixed lod samplers.
  14031. if (texture._lodTextureHigh) {
  14032. texture._lodTextureHigh.dispose();
  14033. }
  14034. if (texture._lodTextureMid) {
  14035. texture._lodTextureMid.dispose();
  14036. }
  14037. if (texture._lodTextureLow) {
  14038. texture._lodTextureLow.dispose();
  14039. }
  14040. };
  14041. Engine.prototype.setProgram = function (program) {
  14042. if (this._currentProgram !== program) {
  14043. this._gl.useProgram(program);
  14044. this._currentProgram = program;
  14045. }
  14046. };
  14047. Engine.prototype.bindSamplers = function (effect) {
  14048. this.setProgram(effect.getProgram());
  14049. var samplers = effect.getSamplers();
  14050. for (var index = 0; index < samplers.length; index++) {
  14051. var uniform = effect.getUniform(samplers[index]);
  14052. if (uniform) {
  14053. this._boundUniforms[index] = uniform;
  14054. }
  14055. }
  14056. this._currentEffect = null;
  14057. };
  14058. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14059. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14060. return;
  14061. }
  14062. // Remove
  14063. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14064. // Bind last to it
  14065. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14066. // Bind to dummy
  14067. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14068. };
  14069. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14070. if (!internalTexture) {
  14071. return -1;
  14072. }
  14073. internalTexture._initialSlot = channel;
  14074. if (this.disableTextureBindingOptimization) {
  14075. if (channel !== internalTexture._designatedSlot) {
  14076. this._textureCollisions.addCount(1, false);
  14077. }
  14078. }
  14079. else {
  14080. if (channel !== internalTexture._designatedSlot) {
  14081. if (internalTexture._designatedSlot > -1) {
  14082. return internalTexture._designatedSlot;
  14083. }
  14084. else {
  14085. // No slot for this texture, let's pick a new one (if we find a free slot)
  14086. if (this._nextFreeTextureSlots.length) {
  14087. return this._nextFreeTextureSlots[0];
  14088. }
  14089. // We need to recycle the oldest bound texture, sorry.
  14090. this._textureCollisions.addCount(1, false);
  14091. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14092. }
  14093. }
  14094. }
  14095. return channel;
  14096. };
  14097. Engine.prototype._linkTrackers = function (previous, next) {
  14098. previous.next = next;
  14099. next.previous = previous;
  14100. };
  14101. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14102. var currentSlot = internalTexture._designatedSlot;
  14103. if (currentSlot === -1) {
  14104. return -1;
  14105. }
  14106. internalTexture._designatedSlot = -1;
  14107. if (this.disableTextureBindingOptimization) {
  14108. return -1;
  14109. }
  14110. // Remove from bound list
  14111. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14112. // Free the slot
  14113. this._boundTexturesCache[currentSlot] = null;
  14114. this._nextFreeTextureSlots.push(currentSlot);
  14115. return currentSlot;
  14116. };
  14117. Engine.prototype._activateCurrentTexture = function () {
  14118. if (this._currentTextureChannel !== this._activeChannel) {
  14119. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14120. this._currentTextureChannel = this._activeChannel;
  14121. }
  14122. };
  14123. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14124. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14125. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14126. this._activeChannel = texture._designatedSlot;
  14127. }
  14128. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14129. var isTextureForRendering = texture && texture._initialSlot > -1;
  14130. if (currentTextureBound !== texture) {
  14131. if (currentTextureBound) {
  14132. this._removeDesignatedSlot(currentTextureBound);
  14133. }
  14134. this._activateCurrentTexture();
  14135. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14136. this._boundTexturesCache[this._activeChannel] = texture;
  14137. if (texture) {
  14138. if (!this.disableTextureBindingOptimization) {
  14139. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14140. if (slotIndex > -1) {
  14141. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14142. }
  14143. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14144. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14145. }
  14146. texture._designatedSlot = this._activeChannel;
  14147. }
  14148. }
  14149. else if (forTextureDataUpdate) {
  14150. this._activateCurrentTexture();
  14151. }
  14152. if (isTextureForRendering && !forTextureDataUpdate) {
  14153. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14154. }
  14155. };
  14156. Engine.prototype._bindTexture = function (channel, texture) {
  14157. if (channel < 0) {
  14158. return;
  14159. }
  14160. if (texture) {
  14161. channel = this._getCorrectTextureChannel(channel, texture);
  14162. }
  14163. this._activeChannel = channel;
  14164. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14165. };
  14166. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14167. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14168. };
  14169. Engine.prototype.unbindAllTextures = function () {
  14170. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14171. this._activeChannel = channel;
  14172. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14173. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14174. if (this.webGLVersion > 1) {
  14175. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14176. }
  14177. }
  14178. };
  14179. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14180. if (channel < 0) {
  14181. return;
  14182. }
  14183. if (uniform) {
  14184. this._boundUniforms[channel] = uniform;
  14185. }
  14186. this._setTexture(channel, texture);
  14187. };
  14188. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14189. var uniform = this._boundUniforms[sourceSlot];
  14190. if (uniform._currentState === destination) {
  14191. return;
  14192. }
  14193. this._gl.uniform1i(uniform, destination);
  14194. uniform._currentState = destination;
  14195. };
  14196. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14197. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14198. // Not ready?
  14199. if (!texture) {
  14200. if (this._boundTexturesCache[channel] != null) {
  14201. this._activeChannel = channel;
  14202. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14203. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14204. if (this.webGLVersion > 1) {
  14205. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14206. }
  14207. }
  14208. return false;
  14209. }
  14210. // Video
  14211. if (texture.video) {
  14212. this._activeChannel = channel;
  14213. texture.update();
  14214. }
  14215. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14216. texture.delayLoad();
  14217. return false;
  14218. }
  14219. var internalTexture;
  14220. if (texture.isReady()) {
  14221. internalTexture = texture.getInternalTexture();
  14222. }
  14223. else if (texture.isCube) {
  14224. internalTexture = this.emptyCubeTexture;
  14225. }
  14226. else if (texture.is3D) {
  14227. internalTexture = this.emptyTexture3D;
  14228. }
  14229. else {
  14230. internalTexture = this.emptyTexture;
  14231. }
  14232. if (!isPartOfTextureArray) {
  14233. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14234. }
  14235. if (this._boundTexturesCache[channel] === internalTexture) {
  14236. this._moveBoundTextureOnTop(internalTexture);
  14237. if (!isPartOfTextureArray) {
  14238. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14239. }
  14240. return false;
  14241. }
  14242. this._activeChannel = channel;
  14243. if (internalTexture && internalTexture.is3D) {
  14244. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14245. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14246. internalTexture._cachedWrapU = texture.wrapU;
  14247. switch (texture.wrapU) {
  14248. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14249. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14250. break;
  14251. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14252. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14253. break;
  14254. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14255. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14256. break;
  14257. }
  14258. }
  14259. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14260. internalTexture._cachedWrapV = texture.wrapV;
  14261. switch (texture.wrapV) {
  14262. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14263. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14264. break;
  14265. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14266. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14267. break;
  14268. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14269. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14270. break;
  14271. }
  14272. }
  14273. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14274. internalTexture._cachedWrapR = texture.wrapR;
  14275. switch (texture.wrapR) {
  14276. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14277. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14278. break;
  14279. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14280. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14281. break;
  14282. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14283. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14284. break;
  14285. }
  14286. }
  14287. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14288. }
  14289. else if (internalTexture && internalTexture.isCube) {
  14290. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14291. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14292. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14293. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14294. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14295. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14296. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14297. }
  14298. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14299. }
  14300. else {
  14301. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14302. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14303. internalTexture._cachedWrapU = texture.wrapU;
  14304. switch (texture.wrapU) {
  14305. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14306. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14307. break;
  14308. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14309. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14310. break;
  14311. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14312. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14313. break;
  14314. }
  14315. }
  14316. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14317. internalTexture._cachedWrapV = texture.wrapV;
  14318. switch (texture.wrapV) {
  14319. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14321. break;
  14322. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14323. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14324. break;
  14325. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14326. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14327. break;
  14328. }
  14329. }
  14330. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14331. }
  14332. return true;
  14333. };
  14334. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14335. if (channel < 0 || !uniform) {
  14336. return;
  14337. }
  14338. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14339. this._textureUnits = new Int32Array(textures.length);
  14340. }
  14341. for (var i = 0; i < textures.length; i++) {
  14342. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14343. }
  14344. this._gl.uniform1iv(uniform, this._textureUnits);
  14345. for (var index = 0; index < textures.length; index++) {
  14346. this._setTexture(this._textureUnits[index], textures[index], true);
  14347. }
  14348. };
  14349. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14350. var internalTexture = texture.getInternalTexture();
  14351. if (!internalTexture) {
  14352. return;
  14353. }
  14354. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14355. var value = texture.anisotropicFilteringLevel;
  14356. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14357. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14358. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14359. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14360. }
  14361. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14362. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14363. internalTexture._cachedAnisotropicFilteringLevel = value;
  14364. }
  14365. };
  14366. Engine.prototype.readPixels = function (x, y, width, height) {
  14367. var data = new Uint8Array(height * width * 4);
  14368. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14369. return data;
  14370. };
  14371. /**
  14372. * Add an externaly attached data from its key.
  14373. * This method call will fail and return false, if such key already exists.
  14374. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14375. * @param key the unique key that identifies the data
  14376. * @param data the data object to associate to the key for this Engine instance
  14377. * @return true if no such key were already present and the data was added successfully, false otherwise
  14378. */
  14379. Engine.prototype.addExternalData = function (key, data) {
  14380. if (!this._externalData) {
  14381. this._externalData = new BABYLON.StringDictionary();
  14382. }
  14383. return this._externalData.add(key, data);
  14384. };
  14385. /**
  14386. * Get an externaly attached data from its key
  14387. * @param key the unique key that identifies the data
  14388. * @return the associated data, if present (can be null), or undefined if not present
  14389. */
  14390. Engine.prototype.getExternalData = function (key) {
  14391. if (!this._externalData) {
  14392. this._externalData = new BABYLON.StringDictionary();
  14393. }
  14394. return this._externalData.get(key);
  14395. };
  14396. /**
  14397. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14398. * @param key the unique key that identifies the data
  14399. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14400. * @return the associated data, can be null if the factory returned null.
  14401. */
  14402. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14403. if (!this._externalData) {
  14404. this._externalData = new BABYLON.StringDictionary();
  14405. }
  14406. return this._externalData.getOrAddWithFactory(key, factory);
  14407. };
  14408. /**
  14409. * Remove an externaly attached data from the Engine instance
  14410. * @param key the unique key that identifies the data
  14411. * @return true if the data was successfully removed, false if it doesn't exist
  14412. */
  14413. Engine.prototype.removeExternalData = function (key) {
  14414. if (!this._externalData) {
  14415. this._externalData = new BABYLON.StringDictionary();
  14416. }
  14417. return this._externalData.remove(key);
  14418. };
  14419. Engine.prototype.unbindAllAttributes = function () {
  14420. if (this._mustWipeVertexAttributes) {
  14421. this._mustWipeVertexAttributes = false;
  14422. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14423. this._gl.disableVertexAttribArray(i);
  14424. this._vertexAttribArraysEnabled[i] = false;
  14425. this._currentBufferPointers[i].active = false;
  14426. }
  14427. return;
  14428. }
  14429. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14430. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14431. continue;
  14432. }
  14433. this._gl.disableVertexAttribArray(i);
  14434. this._vertexAttribArraysEnabled[i] = false;
  14435. this._currentBufferPointers[i].active = false;
  14436. }
  14437. };
  14438. Engine.prototype.releaseEffects = function () {
  14439. for (var name in this._compiledEffects) {
  14440. this._deleteProgram(this._compiledEffects[name]._program);
  14441. }
  14442. this._compiledEffects = {};
  14443. };
  14444. // Dispose
  14445. Engine.prototype.dispose = function () {
  14446. this.hideLoadingUI();
  14447. this.stopRenderLoop();
  14448. // Release postProcesses
  14449. while (this.postProcesses.length) {
  14450. this.postProcesses[0].dispose();
  14451. }
  14452. // Empty texture
  14453. if (this._emptyTexture) {
  14454. this._releaseTexture(this._emptyTexture);
  14455. this._emptyTexture = null;
  14456. }
  14457. if (this._emptyCubeTexture) {
  14458. this._releaseTexture(this._emptyCubeTexture);
  14459. this._emptyCubeTexture = null;
  14460. }
  14461. // Rescale PP
  14462. if (this._rescalePostProcess) {
  14463. this._rescalePostProcess.dispose();
  14464. }
  14465. // Release scenes
  14466. while (this.scenes.length) {
  14467. this.scenes[0].dispose();
  14468. }
  14469. // Release audio engine
  14470. if (Engine.audioEngine) {
  14471. Engine.audioEngine.dispose();
  14472. }
  14473. // Release effects
  14474. this.releaseEffects();
  14475. // Unbind
  14476. this.unbindAllAttributes();
  14477. if (this._dummyFramebuffer) {
  14478. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14479. }
  14480. //WebVR
  14481. this.disableVR();
  14482. // Events
  14483. if (BABYLON.Tools.IsWindowObjectExist()) {
  14484. window.removeEventListener("blur", this._onBlur);
  14485. window.removeEventListener("focus", this._onFocus);
  14486. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14487. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14488. if (this._renderingCanvas) {
  14489. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14490. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14491. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14492. if (!this._doNotHandleContextLost) {
  14493. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14494. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14495. }
  14496. }
  14497. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14498. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14499. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14500. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14501. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14502. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14503. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14504. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14505. if (this._onVrDisplayConnect) {
  14506. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14507. if (this._onVrDisplayDisconnect) {
  14508. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14509. }
  14510. if (this._onVrDisplayPresentChange) {
  14511. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14512. }
  14513. this._onVrDisplayConnect = null;
  14514. this._onVrDisplayDisconnect = null;
  14515. }
  14516. }
  14517. // Remove from Instances
  14518. var index = Engine.Instances.indexOf(this);
  14519. if (index >= 0) {
  14520. Engine.Instances.splice(index, 1);
  14521. }
  14522. this._workingCanvas = null;
  14523. this._workingContext = null;
  14524. this._currentBufferPointers = [];
  14525. this._renderingCanvas = null;
  14526. this._currentProgram = null;
  14527. this.onResizeObservable.clear();
  14528. this.onCanvasBlurObservable.clear();
  14529. this.onCanvasFocusObservable.clear();
  14530. this.onCanvasPointerOutObservable.clear();
  14531. this.onBeginFrameObservable.clear();
  14532. this.onEndFrameObservable.clear();
  14533. BABYLON.Effect.ResetCache();
  14534. // Abort active requests
  14535. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14536. var request = _a[_i];
  14537. request.abort();
  14538. }
  14539. };
  14540. // Loading screen
  14541. Engine.prototype.displayLoadingUI = function () {
  14542. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14543. return;
  14544. }
  14545. var loadingScreen = this.loadingScreen;
  14546. if (loadingScreen) {
  14547. loadingScreen.displayLoadingUI();
  14548. }
  14549. };
  14550. Engine.prototype.hideLoadingUI = function () {
  14551. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14552. return;
  14553. }
  14554. var loadingScreen = this.loadingScreen;
  14555. if (loadingScreen) {
  14556. loadingScreen.hideLoadingUI();
  14557. }
  14558. };
  14559. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14560. get: function () {
  14561. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14562. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14563. return this._loadingScreen;
  14564. },
  14565. set: function (loadingScreen) {
  14566. this._loadingScreen = loadingScreen;
  14567. },
  14568. enumerable: true,
  14569. configurable: true
  14570. });
  14571. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14572. set: function (text) {
  14573. this.loadingScreen.loadingUIText = text;
  14574. },
  14575. enumerable: true,
  14576. configurable: true
  14577. });
  14578. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14579. set: function (color) {
  14580. this.loadingScreen.loadingUIBackgroundColor = color;
  14581. },
  14582. enumerable: true,
  14583. configurable: true
  14584. });
  14585. Engine.prototype.attachContextLostEvent = function (callback) {
  14586. if (this._renderingCanvas) {
  14587. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14588. }
  14589. };
  14590. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14591. if (this._renderingCanvas) {
  14592. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14593. }
  14594. };
  14595. Engine.prototype.getVertexShaderSource = function (program) {
  14596. var shaders = this._gl.getAttachedShaders(program);
  14597. if (!shaders) {
  14598. return null;
  14599. }
  14600. return this._gl.getShaderSource(shaders[0]);
  14601. };
  14602. Engine.prototype.getFragmentShaderSource = function (program) {
  14603. var shaders = this._gl.getAttachedShaders(program);
  14604. if (!shaders) {
  14605. return null;
  14606. }
  14607. return this._gl.getShaderSource(shaders[1]);
  14608. };
  14609. Engine.prototype.getError = function () {
  14610. return this._gl.getError();
  14611. };
  14612. // FPS
  14613. Engine.prototype.getFps = function () {
  14614. return this._fps;
  14615. };
  14616. Engine.prototype.getDeltaTime = function () {
  14617. return this._deltaTime;
  14618. };
  14619. Engine.prototype._measureFps = function () {
  14620. this._performanceMonitor.sampleFrame();
  14621. this._fps = this._performanceMonitor.averageFPS;
  14622. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14623. };
  14624. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14625. if (faceIndex === void 0) { faceIndex = -1; }
  14626. var gl = this._gl;
  14627. if (!this._dummyFramebuffer) {
  14628. var dummy = gl.createFramebuffer();
  14629. if (!dummy) {
  14630. throw new Error("Unable to create dummy framebuffer");
  14631. }
  14632. this._dummyFramebuffer = dummy;
  14633. }
  14634. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14635. if (faceIndex > -1) {
  14636. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14637. }
  14638. else {
  14639. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14640. }
  14641. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14642. var buffer;
  14643. switch (readType) {
  14644. case gl.UNSIGNED_BYTE:
  14645. buffer = new Uint8Array(4 * width * height);
  14646. readType = gl.UNSIGNED_BYTE;
  14647. break;
  14648. default:
  14649. buffer = new Float32Array(4 * width * height);
  14650. readType = gl.FLOAT;
  14651. break;
  14652. }
  14653. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14654. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14655. return buffer;
  14656. };
  14657. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14658. if (this._webGLVersion > 1) {
  14659. return this._caps.colorBufferFloat;
  14660. }
  14661. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14662. };
  14663. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14664. if (this._webGLVersion > 1) {
  14665. return this._caps.colorBufferFloat;
  14666. }
  14667. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14668. };
  14669. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14670. Engine.prototype._canRenderToFramebuffer = function (type) {
  14671. var gl = this._gl;
  14672. //clear existing errors
  14673. while (gl.getError() !== gl.NO_ERROR) { }
  14674. var successful = true;
  14675. var texture = gl.createTexture();
  14676. gl.bindTexture(gl.TEXTURE_2D, texture);
  14677. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14678. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14679. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14680. var fb = gl.createFramebuffer();
  14681. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14682. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14683. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14684. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14685. successful = successful && (gl.getError() === gl.NO_ERROR);
  14686. //try render by clearing frame buffer's color buffer
  14687. if (successful) {
  14688. gl.clear(gl.COLOR_BUFFER_BIT);
  14689. successful = successful && (gl.getError() === gl.NO_ERROR);
  14690. }
  14691. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14692. if (successful) {
  14693. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14694. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14695. var readFormat = gl.RGBA;
  14696. var readType = gl.UNSIGNED_BYTE;
  14697. var buffer = new Uint8Array(4);
  14698. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14699. successful = successful && (gl.getError() === gl.NO_ERROR);
  14700. }
  14701. //clean up
  14702. gl.deleteTexture(texture);
  14703. gl.deleteFramebuffer(fb);
  14704. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14705. //clear accumulated errors
  14706. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14707. return successful;
  14708. };
  14709. Engine.prototype._getWebGLTextureType = function (type) {
  14710. if (type === Engine.TEXTURETYPE_FLOAT) {
  14711. return this._gl.FLOAT;
  14712. }
  14713. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14714. // Add Half Float Constant.
  14715. return this._gl.HALF_FLOAT_OES;
  14716. }
  14717. return this._gl.UNSIGNED_BYTE;
  14718. };
  14719. ;
  14720. /** @ignore */
  14721. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  14722. if (this._webGLVersion === 1) {
  14723. return this._gl.RGBA;
  14724. }
  14725. if (type === Engine.TEXTURETYPE_FLOAT) {
  14726. if (format) {
  14727. switch (format) {
  14728. case Engine.TEXTUREFORMAT_R32F:
  14729. return this._gl.R32F;
  14730. case Engine.TEXTUREFORMAT_RG32F:
  14731. return this._gl.RG32F;
  14732. case Engine.TEXTUREFORMAT_RGB32F:
  14733. return this._gl.RGB32F;
  14734. }
  14735. }
  14736. return this._gl.RGBA32F;
  14737. }
  14738. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14739. return this._gl.RGBA16F;
  14740. }
  14741. return this._gl.RGBA;
  14742. };
  14743. ;
  14744. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14745. if (type === Engine.TEXTURETYPE_FLOAT) {
  14746. return this._gl.RGBA32F;
  14747. }
  14748. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14749. return this._gl.RGBA16F;
  14750. }
  14751. return this._gl.RGBA8;
  14752. };
  14753. ;
  14754. Engine.prototype.createQuery = function () {
  14755. return this._gl.createQuery();
  14756. };
  14757. Engine.prototype.deleteQuery = function (query) {
  14758. this._gl.deleteQuery(query);
  14759. return this;
  14760. };
  14761. Engine.prototype.isQueryResultAvailable = function (query) {
  14762. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14763. };
  14764. Engine.prototype.getQueryResult = function (query) {
  14765. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14766. };
  14767. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14768. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14769. this._gl.beginQuery(glAlgorithm, query);
  14770. return this;
  14771. };
  14772. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14773. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14774. this._gl.endQuery(glAlgorithm);
  14775. return this;
  14776. };
  14777. /* Time queries */
  14778. Engine.prototype._createTimeQuery = function () {
  14779. var timerQuery = this._caps.timerQuery;
  14780. if (timerQuery.createQueryEXT) {
  14781. return timerQuery.createQueryEXT();
  14782. }
  14783. return this.createQuery();
  14784. };
  14785. Engine.prototype._deleteTimeQuery = function (query) {
  14786. var timerQuery = this._caps.timerQuery;
  14787. if (timerQuery.deleteQueryEXT) {
  14788. timerQuery.deleteQueryEXT(query);
  14789. return;
  14790. }
  14791. this.deleteQuery(query);
  14792. };
  14793. Engine.prototype._getTimeQueryResult = function (query) {
  14794. var timerQuery = this._caps.timerQuery;
  14795. if (timerQuery.getQueryObjectEXT) {
  14796. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14797. }
  14798. return this.getQueryResult(query);
  14799. };
  14800. Engine.prototype._getTimeQueryAvailability = function (query) {
  14801. var timerQuery = this._caps.timerQuery;
  14802. if (timerQuery.getQueryObjectEXT) {
  14803. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14804. }
  14805. return this.isQueryResultAvailable(query);
  14806. };
  14807. Engine.prototype.startTimeQuery = function () {
  14808. var timerQuery = this._caps.timerQuery;
  14809. if (!timerQuery) {
  14810. return null;
  14811. }
  14812. var token = new BABYLON._TimeToken();
  14813. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14814. if (this._caps.canUseTimestampForTimerQuery) {
  14815. token._startTimeQuery = this._createTimeQuery();
  14816. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14817. }
  14818. else {
  14819. if (this._currentNonTimestampToken) {
  14820. return this._currentNonTimestampToken;
  14821. }
  14822. token._timeElapsedQuery = this._createTimeQuery();
  14823. if (timerQuery.beginQueryEXT) {
  14824. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14825. }
  14826. else {
  14827. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14828. }
  14829. this._currentNonTimestampToken = token;
  14830. }
  14831. return token;
  14832. };
  14833. Engine.prototype.endTimeQuery = function (token) {
  14834. var timerQuery = this._caps.timerQuery;
  14835. if (!timerQuery || !token) {
  14836. return -1;
  14837. }
  14838. if (this._caps.canUseTimestampForTimerQuery) {
  14839. if (!token._startTimeQuery) {
  14840. return -1;
  14841. }
  14842. if (!token._endTimeQuery) {
  14843. token._endTimeQuery = this._createTimeQuery();
  14844. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14845. }
  14846. }
  14847. else if (!token._timeElapsedQueryEnded) {
  14848. if (!token._timeElapsedQuery) {
  14849. return -1;
  14850. }
  14851. if (timerQuery.endQueryEXT) {
  14852. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14853. }
  14854. else {
  14855. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14856. }
  14857. token._timeElapsedQueryEnded = true;
  14858. }
  14859. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14860. var available = false;
  14861. if (token._endTimeQuery) {
  14862. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14863. }
  14864. else if (token._timeElapsedQuery) {
  14865. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14866. }
  14867. if (available && !disjoint) {
  14868. var result = 0;
  14869. if (this._caps.canUseTimestampForTimerQuery) {
  14870. if (!token._startTimeQuery || !token._endTimeQuery) {
  14871. return -1;
  14872. }
  14873. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14874. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14875. result = timeEnd - timeStart;
  14876. this._deleteTimeQuery(token._startTimeQuery);
  14877. this._deleteTimeQuery(token._endTimeQuery);
  14878. token._startTimeQuery = null;
  14879. token._endTimeQuery = null;
  14880. }
  14881. else {
  14882. if (!token._timeElapsedQuery) {
  14883. return -1;
  14884. }
  14885. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14886. this._deleteTimeQuery(token._timeElapsedQuery);
  14887. token._timeElapsedQuery = null;
  14888. token._timeElapsedQueryEnded = false;
  14889. this._currentNonTimestampToken = null;
  14890. }
  14891. return result;
  14892. }
  14893. return -1;
  14894. };
  14895. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14896. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14897. };
  14898. // Transform feedback
  14899. Engine.prototype.createTransformFeedback = function () {
  14900. return this._gl.createTransformFeedback();
  14901. };
  14902. Engine.prototype.deleteTransformFeedback = function (value) {
  14903. this._gl.deleteTransformFeedback(value);
  14904. };
  14905. Engine.prototype.bindTransformFeedback = function (value) {
  14906. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14907. };
  14908. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14909. if (usePoints === void 0) { usePoints = true; }
  14910. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14911. };
  14912. Engine.prototype.endTransformFeedback = function () {
  14913. this._gl.endTransformFeedback();
  14914. };
  14915. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14916. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14917. };
  14918. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14919. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14920. };
  14921. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14922. var _this = this;
  14923. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14924. this._activeRequests.push(request);
  14925. request.onCompleteObservable.add(function (request) {
  14926. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14927. });
  14928. return request;
  14929. };
  14930. /** @ignore */
  14931. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14932. var _this = this;
  14933. return new Promise(function (resolve, reject) {
  14934. _this._loadFile(url, function (data) {
  14935. resolve(data);
  14936. }, undefined, database, useArrayBuffer, function (request, exception) {
  14937. reject(exception);
  14938. });
  14939. });
  14940. };
  14941. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14942. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14943. var onload = function (data) {
  14944. loadedFiles[index] = data;
  14945. loadedFiles._internalCount++;
  14946. if (loadedFiles._internalCount === 6) {
  14947. onfinish(loadedFiles);
  14948. }
  14949. };
  14950. var onerror = function (request, exception) {
  14951. if (onErrorCallBack && request) {
  14952. onErrorCallBack(request.status + " " + request.statusText, exception);
  14953. }
  14954. };
  14955. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14956. };
  14957. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  14958. if (onError === void 0) { onError = null; }
  14959. var loadedFiles = [];
  14960. loadedFiles._internalCount = 0;
  14961. for (var index = 0; index < 6; index++) {
  14962. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14963. }
  14964. };
  14965. // Statics
  14966. Engine.isSupported = function () {
  14967. try {
  14968. var tempcanvas = document.createElement("canvas");
  14969. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14970. return gl != null && !!window.WebGLRenderingContext;
  14971. }
  14972. catch (e) {
  14973. return false;
  14974. }
  14975. };
  14976. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14977. Engine.ExceptionList = [
  14978. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14979. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14980. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14981. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14982. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14983. ];
  14984. Engine.Instances = new Array();
  14985. // Const statics
  14986. Engine._ALPHA_DISABLE = 0;
  14987. Engine._ALPHA_ADD = 1;
  14988. Engine._ALPHA_COMBINE = 2;
  14989. Engine._ALPHA_SUBTRACT = 3;
  14990. Engine._ALPHA_MULTIPLY = 4;
  14991. Engine._ALPHA_MAXIMIZED = 5;
  14992. Engine._ALPHA_ONEONE = 6;
  14993. Engine._ALPHA_PREMULTIPLIED = 7;
  14994. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  14995. Engine._ALPHA_INTERPOLATE = 9;
  14996. Engine._ALPHA_SCREENMODE = 10;
  14997. Engine._DELAYLOADSTATE_NONE = 0;
  14998. Engine._DELAYLOADSTATE_LOADED = 1;
  14999. Engine._DELAYLOADSTATE_LOADING = 2;
  15000. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15001. Engine._TEXTUREFORMAT_ALPHA = 0;
  15002. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15003. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15004. Engine._TEXTUREFORMAT_RGB = 4;
  15005. Engine._TEXTUREFORMAT_RGBA = 5;
  15006. Engine._TEXTUREFORMAT_R32F = 6;
  15007. Engine._TEXTUREFORMAT_RG32F = 7;
  15008. Engine._TEXTUREFORMAT_RGB32F = 8;
  15009. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15010. Engine._TEXTURETYPE_FLOAT = 1;
  15011. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15012. // Depht or Stencil test Constants.
  15013. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15014. 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.
  15015. 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.
  15016. 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.
  15017. 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.
  15018. 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.
  15019. 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.
  15020. 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.
  15021. // Stencil Actions Constants.
  15022. Engine._KEEP = 0x1E00;
  15023. Engine._REPLACE = 0x1E01;
  15024. Engine._INCR = 0x1E02;
  15025. Engine._DECR = 0x1E03;
  15026. Engine._INVERT = 0x150A;
  15027. Engine._INCR_WRAP = 0x8507;
  15028. Engine._DECR_WRAP = 0x8508;
  15029. // Texture rescaling mode
  15030. Engine._SCALEMODE_FLOOR = 1;
  15031. Engine._SCALEMODE_NEAREST = 2;
  15032. Engine._SCALEMODE_CEILING = 3;
  15033. // Updatable statics so stick with vars here
  15034. Engine.CollisionsEpsilon = 0.001;
  15035. Engine.CodeRepository = "src/";
  15036. Engine.ShadersRepository = "src/Shaders/";
  15037. return Engine;
  15038. }());
  15039. BABYLON.Engine = Engine;
  15040. })(BABYLON || (BABYLON = {}));
  15041. //# sourceMappingURL=babylon.engine.js.map
  15042. var BABYLON;
  15043. (function (BABYLON) {
  15044. /**
  15045. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15046. */
  15047. var Node = /** @class */ (function () {
  15048. /**
  15049. * Creates a new Node
  15050. * @param {string} name - the name and id to be given to this node
  15051. * @param {BABYLON.Scene} the scene this node will be added to
  15052. */
  15053. function Node(name, scene) {
  15054. if (scene === void 0) { scene = null; }
  15055. /**
  15056. * Gets or sets a string used to store user defined state for the node
  15057. */
  15058. this.state = "";
  15059. /**
  15060. * Gets or sets an object used to store user defined information for the node
  15061. */
  15062. this.metadata = null;
  15063. /**
  15064. * Gets or sets a boolean used to define if the node must be serialized
  15065. */
  15066. this.doNotSerialize = false;
  15067. /** @ignore */
  15068. this._isDisposed = false;
  15069. /**
  15070. * Gets a list of {BABYLON.Animation} associated with the node
  15071. */
  15072. this.animations = new Array();
  15073. this._ranges = {};
  15074. this._isEnabled = true;
  15075. this._isReady = true;
  15076. /** @ignore */
  15077. this._currentRenderId = -1;
  15078. this._parentRenderId = -1;
  15079. /**
  15080. * An event triggered when the mesh is disposed
  15081. * @type {BABYLON.Observable}
  15082. */
  15083. this.onDisposeObservable = new BABYLON.Observable();
  15084. // Behaviors
  15085. this._behaviors = new Array();
  15086. this.name = name;
  15087. this.id = name;
  15088. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15089. this.uniqueId = this._scene.getUniqueId();
  15090. this._initCache();
  15091. }
  15092. /**
  15093. * Gets a boolean indicating if the node has been disposed
  15094. * @returns true if the node was disposed
  15095. */
  15096. Node.prototype.isDisposed = function () {
  15097. return this._isDisposed;
  15098. };
  15099. Object.defineProperty(Node.prototype, "parent", {
  15100. get: function () {
  15101. return this._parentNode;
  15102. },
  15103. /**
  15104. * Gets or sets the parent of the node
  15105. */
  15106. set: function (parent) {
  15107. if (this._parentNode === parent) {
  15108. return;
  15109. }
  15110. // Remove self from list of children of parent
  15111. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15112. var index = this._parentNode._children.indexOf(this);
  15113. if (index !== -1) {
  15114. this._parentNode._children.splice(index, 1);
  15115. }
  15116. }
  15117. // Store new parent
  15118. this._parentNode = parent;
  15119. // Add as child to new parent
  15120. if (this._parentNode) {
  15121. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15122. this._parentNode._children = new Array();
  15123. }
  15124. this._parentNode._children.push(this);
  15125. }
  15126. },
  15127. enumerable: true,
  15128. configurable: true
  15129. });
  15130. /**
  15131. * Gets a string idenfifying the name of the class
  15132. * @returns "Node" string
  15133. */
  15134. Node.prototype.getClassName = function () {
  15135. return "Node";
  15136. };
  15137. Object.defineProperty(Node.prototype, "onDispose", {
  15138. /**
  15139. * Sets a callback that will be raised when the node will be disposed
  15140. */
  15141. set: function (callback) {
  15142. if (this._onDisposeObserver) {
  15143. this.onDisposeObservable.remove(this._onDisposeObserver);
  15144. }
  15145. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15146. },
  15147. enumerable: true,
  15148. configurable: true
  15149. });
  15150. /**
  15151. * Gets the scene of the node
  15152. * @returns a {BABYLON.Scene}
  15153. */
  15154. Node.prototype.getScene = function () {
  15155. return this._scene;
  15156. };
  15157. /**
  15158. * Gets the engine of the node
  15159. * @returns a {BABYLON.Engine}
  15160. */
  15161. Node.prototype.getEngine = function () {
  15162. return this._scene.getEngine();
  15163. };
  15164. /**
  15165. * Attach a behavior to the node
  15166. * @see http://doc.babylonjs.com/features/behaviour
  15167. * @param behavior defines the behavior to attach
  15168. * @returns the current Node
  15169. */
  15170. Node.prototype.addBehavior = function (behavior) {
  15171. var _this = this;
  15172. var index = this._behaviors.indexOf(behavior);
  15173. if (index !== -1) {
  15174. return this;
  15175. }
  15176. behavior.init();
  15177. if (this._scene.isLoading) {
  15178. // We defer the attach when the scene will be loaded
  15179. var observer = this._scene.onDataLoadedObservable.add(function () {
  15180. behavior.attach(_this);
  15181. setTimeout(function () {
  15182. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15183. _this._scene.onDataLoadedObservable.remove(observer);
  15184. }, 0);
  15185. });
  15186. }
  15187. else {
  15188. behavior.attach(this);
  15189. }
  15190. this._behaviors.push(behavior);
  15191. return this;
  15192. };
  15193. /**
  15194. * Remove an attached behavior
  15195. * @see http://doc.babylonjs.com/features/behaviour
  15196. * @param behavior defines the behavior to attach
  15197. * @returns the current Node
  15198. */
  15199. Node.prototype.removeBehavior = function (behavior) {
  15200. var index = this._behaviors.indexOf(behavior);
  15201. if (index === -1) {
  15202. return this;
  15203. }
  15204. this._behaviors[index].detach();
  15205. this._behaviors.splice(index, 1);
  15206. return this;
  15207. };
  15208. Object.defineProperty(Node.prototype, "behaviors", {
  15209. /**
  15210. * Gets the list of attached behaviors
  15211. * @see http://doc.babylonjs.com/features/behaviour
  15212. */
  15213. get: function () {
  15214. return this._behaviors;
  15215. },
  15216. enumerable: true,
  15217. configurable: true
  15218. });
  15219. /**
  15220. * Gets an attached behavior by name
  15221. * @param name defines the name of the behavior to look for
  15222. * @see http://doc.babylonjs.com/features/behaviour
  15223. * @returns null if behavior was not found else the requested behavior
  15224. */
  15225. Node.prototype.getBehaviorByName = function (name) {
  15226. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15227. var behavior = _a[_i];
  15228. if (behavior.name === name) {
  15229. return behavior;
  15230. }
  15231. }
  15232. return null;
  15233. };
  15234. /**
  15235. * Returns the world matrix of the node
  15236. * @returns a matrix containing the node's world matrix
  15237. */
  15238. Node.prototype.getWorldMatrix = function () {
  15239. return BABYLON.Matrix.Identity();
  15240. };
  15241. // override it in derived class if you add new variables to the cache
  15242. // and call the parent class method
  15243. /** @ignore */
  15244. Node.prototype._initCache = function () {
  15245. this._cache = {};
  15246. this._cache.parent = undefined;
  15247. };
  15248. /** @ignore */
  15249. Node.prototype.updateCache = function (force) {
  15250. if (!force && this.isSynchronized())
  15251. return;
  15252. this._cache.parent = this.parent;
  15253. this._updateCache();
  15254. };
  15255. // override it in derived class if you add new variables to the cache
  15256. // and call the parent class method if !ignoreParentClass
  15257. /** @ignore */
  15258. Node.prototype._updateCache = function (ignoreParentClass) {
  15259. };
  15260. // override it in derived class if you add new variables to the cache
  15261. /** @ignore */
  15262. Node.prototype._isSynchronized = function () {
  15263. return true;
  15264. };
  15265. /** @ignore */
  15266. Node.prototype._markSyncedWithParent = function () {
  15267. if (this.parent) {
  15268. this._parentRenderId = this.parent._currentRenderId;
  15269. }
  15270. };
  15271. /** @ignore */
  15272. Node.prototype.isSynchronizedWithParent = function () {
  15273. if (!this.parent) {
  15274. return true;
  15275. }
  15276. if (this._parentRenderId !== this.parent._currentRenderId) {
  15277. return false;
  15278. }
  15279. return this.parent.isSynchronized();
  15280. };
  15281. /** @ignore */
  15282. Node.prototype.isSynchronized = function (updateCache) {
  15283. var check = this.hasNewParent();
  15284. check = check || !this.isSynchronizedWithParent();
  15285. check = check || !this._isSynchronized();
  15286. if (updateCache)
  15287. this.updateCache(true);
  15288. return !check;
  15289. };
  15290. /** @ignore */
  15291. Node.prototype.hasNewParent = function (update) {
  15292. if (this._cache.parent === this.parent)
  15293. return false;
  15294. if (update)
  15295. this._cache.parent = this.parent;
  15296. return true;
  15297. };
  15298. /**
  15299. * Is this node ready to be used/rendered
  15300. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15301. * @return true if the node is ready
  15302. */
  15303. Node.prototype.isReady = function (completeCheck) {
  15304. if (completeCheck === void 0) { completeCheck = false; }
  15305. return this._isReady;
  15306. };
  15307. /**
  15308. * Is this node enabled?
  15309. * 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
  15310. * @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
  15311. * @return whether this node (and its parent) is enabled
  15312. * @see setEnabled
  15313. */
  15314. Node.prototype.isEnabled = function (checkAncestors) {
  15315. if (checkAncestors === void 0) { checkAncestors = true; }
  15316. if (checkAncestors === false) {
  15317. return this._isEnabled;
  15318. }
  15319. if (this._isEnabled === false) {
  15320. return false;
  15321. }
  15322. if (this.parent !== undefined && this.parent !== null) {
  15323. return this.parent.isEnabled(checkAncestors);
  15324. }
  15325. return true;
  15326. };
  15327. /**
  15328. * Set the enabled state of this node
  15329. * @param value defines the new enabled state
  15330. * @see isEnabled
  15331. */
  15332. Node.prototype.setEnabled = function (value) {
  15333. this._isEnabled = value;
  15334. };
  15335. /**
  15336. * Is this node a descendant of the given node?
  15337. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15338. * @param ancestor defines the parent node to inspect
  15339. * @see parent
  15340. * @returns a boolean indicating if this node is a descendant of the given node
  15341. */
  15342. Node.prototype.isDescendantOf = function (ancestor) {
  15343. if (this.parent) {
  15344. if (this.parent === ancestor) {
  15345. return true;
  15346. }
  15347. return this.parent.isDescendantOf(ancestor);
  15348. }
  15349. return false;
  15350. };
  15351. /** @ignore */
  15352. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15353. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15354. if (!this._children) {
  15355. return;
  15356. }
  15357. for (var index = 0; index < this._children.length; index++) {
  15358. var item = this._children[index];
  15359. if (!predicate || predicate(item)) {
  15360. results.push(item);
  15361. }
  15362. if (!directDescendantsOnly) {
  15363. item._getDescendants(results, false, predicate);
  15364. }
  15365. }
  15366. };
  15367. /**
  15368. * Will return all nodes that have this node as ascendant
  15369. * @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
  15370. * @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
  15371. * @return all children nodes of all types
  15372. */
  15373. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15374. var results = new Array();
  15375. this._getDescendants(results, directDescendantsOnly, predicate);
  15376. return results;
  15377. };
  15378. /**
  15379. * Get all child-meshes of this node
  15380. * @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
  15381. * @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
  15382. * @returns an array of {BABYLON.AbstractMesh}
  15383. */
  15384. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15385. var results = [];
  15386. this._getDescendants(results, directDescendantsOnly, function (node) {
  15387. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15388. });
  15389. return results;
  15390. };
  15391. /**
  15392. * Get all child-transformNodes of this node
  15393. * @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
  15394. * @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
  15395. * @returns an array of {BABYLON.TransformNode}
  15396. */
  15397. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15398. var results = [];
  15399. this._getDescendants(results, directDescendantsOnly, function (node) {
  15400. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15401. });
  15402. return results;
  15403. };
  15404. /**
  15405. * Get all direct children of this node
  15406. * @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
  15407. * @returns an array of {BABYLON.Node}
  15408. */
  15409. Node.prototype.getChildren = function (predicate) {
  15410. return this.getDescendants(true, predicate);
  15411. };
  15412. /** @ignore */
  15413. Node.prototype._setReady = function (state) {
  15414. if (state === this._isReady) {
  15415. return;
  15416. }
  15417. if (!state) {
  15418. this._isReady = false;
  15419. return;
  15420. }
  15421. this._isReady = true;
  15422. if (this.onReady) {
  15423. this.onReady(this);
  15424. }
  15425. };
  15426. /**
  15427. * Get an animation by name
  15428. * @param name defines the name of the animation to look for
  15429. * @returns null if not found else the requested animation
  15430. */
  15431. Node.prototype.getAnimationByName = function (name) {
  15432. for (var i = 0; i < this.animations.length; i++) {
  15433. var animation = this.animations[i];
  15434. if (animation.name === name) {
  15435. return animation;
  15436. }
  15437. }
  15438. return null;
  15439. };
  15440. /**
  15441. * Creates an animation range for this node
  15442. * @param name defines the name of the range
  15443. * @param from defines the starting key
  15444. * @param to defines the end key
  15445. */
  15446. Node.prototype.createAnimationRange = function (name, from, to) {
  15447. // check name not already in use
  15448. if (!this._ranges[name]) {
  15449. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15450. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15451. if (this.animations[i]) {
  15452. this.animations[i].createRange(name, from, to);
  15453. }
  15454. }
  15455. }
  15456. };
  15457. /**
  15458. * Delete a specific animation range
  15459. * @param name defines the name of the range to delete
  15460. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15461. */
  15462. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15463. if (deleteFrames === void 0) { deleteFrames = true; }
  15464. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15465. if (this.animations[i]) {
  15466. this.animations[i].deleteRange(name, deleteFrames);
  15467. }
  15468. }
  15469. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15470. };
  15471. /**
  15472. * Get an animation range by name
  15473. * @param name defines the name of the animation range to look for
  15474. * @returns null if not found else the requested animation range
  15475. */
  15476. Node.prototype.getAnimationRange = function (name) {
  15477. return this._ranges[name];
  15478. };
  15479. /**
  15480. * Will start the animation sequence
  15481. * @param name defines the range frames for animation sequence
  15482. * @param loop defines if the animation should loop (false by default)
  15483. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15484. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15485. * @returns the object created for this animation. If range does not exist, it will return null
  15486. */
  15487. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15488. var range = this.getAnimationRange(name);
  15489. if (!range) {
  15490. return null;
  15491. }
  15492. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15493. };
  15494. /**
  15495. * Serialize animation ranges into a JSON compatible object
  15496. * @returns serialization object
  15497. */
  15498. Node.prototype.serializeAnimationRanges = function () {
  15499. var serializationRanges = [];
  15500. for (var name in this._ranges) {
  15501. var localRange = this._ranges[name];
  15502. if (!localRange) {
  15503. continue;
  15504. }
  15505. var range = {};
  15506. range.name = name;
  15507. range.from = localRange.from;
  15508. range.to = localRange.to;
  15509. serializationRanges.push(range);
  15510. }
  15511. return serializationRanges;
  15512. };
  15513. /**
  15514. * Computes the world matrix of the node
  15515. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15516. * @returns the world matrix
  15517. */
  15518. Node.prototype.computeWorldMatrix = function (force) {
  15519. return BABYLON.Matrix.Identity();
  15520. };
  15521. /**
  15522. * Releases all associated resources
  15523. */
  15524. Node.prototype.dispose = function () {
  15525. this.parent = null;
  15526. // Callback
  15527. this.onDisposeObservable.notifyObservers(this);
  15528. this.onDisposeObservable.clear();
  15529. // Behaviors
  15530. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15531. var behavior = _a[_i];
  15532. behavior.detach();
  15533. }
  15534. this._behaviors = [];
  15535. this._isDisposed = true;
  15536. };
  15537. /**
  15538. * Parse animation range data from a serialization object and store them into a given node
  15539. * @param node defines where to store the animation ranges
  15540. * @param parsedNode defines the serialization object to read data from
  15541. * @param scene defines the hosting scene
  15542. */
  15543. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15544. if (parsedNode.ranges) {
  15545. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15546. var data = parsedNode.ranges[index];
  15547. node.createAnimationRange(data.name, data.from, data.to);
  15548. }
  15549. }
  15550. };
  15551. __decorate([
  15552. BABYLON.serialize()
  15553. ], Node.prototype, "name", void 0);
  15554. __decorate([
  15555. BABYLON.serialize()
  15556. ], Node.prototype, "id", void 0);
  15557. __decorate([
  15558. BABYLON.serialize()
  15559. ], Node.prototype, "uniqueId", void 0);
  15560. __decorate([
  15561. BABYLON.serialize()
  15562. ], Node.prototype, "state", void 0);
  15563. __decorate([
  15564. BABYLON.serialize()
  15565. ], Node.prototype, "metadata", void 0);
  15566. return Node;
  15567. }());
  15568. BABYLON.Node = Node;
  15569. })(BABYLON || (BABYLON = {}));
  15570. //# sourceMappingURL=babylon.node.js.map
  15571. var BABYLON;
  15572. (function (BABYLON) {
  15573. var BoundingSphere = /** @class */ (function () {
  15574. function BoundingSphere(minimum, maximum) {
  15575. this.minimum = minimum;
  15576. this.maximum = maximum;
  15577. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15578. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15579. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15580. this.radius = distance * 0.5;
  15581. this.centerWorld = BABYLON.Vector3.Zero();
  15582. this._update(BABYLON.Matrix.Identity());
  15583. }
  15584. // Methods
  15585. BoundingSphere.prototype._update = function (world) {
  15586. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15587. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15588. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15589. };
  15590. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15591. for (var i = 0; i < 6; i++) {
  15592. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15593. return false;
  15594. }
  15595. return true;
  15596. };
  15597. BoundingSphere.prototype.intersectsPoint = function (point) {
  15598. var x = this.centerWorld.x - point.x;
  15599. var y = this.centerWorld.y - point.y;
  15600. var z = this.centerWorld.z - point.z;
  15601. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15602. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15603. return false;
  15604. return true;
  15605. };
  15606. // Statics
  15607. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15608. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15609. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15610. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15611. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15612. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15613. return false;
  15614. return true;
  15615. };
  15616. return BoundingSphere;
  15617. }());
  15618. BABYLON.BoundingSphere = BoundingSphere;
  15619. })(BABYLON || (BABYLON = {}));
  15620. //# sourceMappingURL=babylon.boundingSphere.js.map
  15621. var BABYLON;
  15622. (function (BABYLON) {
  15623. var BoundingBox = /** @class */ (function () {
  15624. function BoundingBox(minimum, maximum) {
  15625. this.minimum = minimum;
  15626. this.maximum = maximum;
  15627. this.vectors = new Array();
  15628. this.vectorsWorld = new Array();
  15629. // Bounding vectors
  15630. this.vectors.push(this.minimum.clone());
  15631. this.vectors.push(this.maximum.clone());
  15632. this.vectors.push(this.minimum.clone());
  15633. this.vectors[2].x = this.maximum.x;
  15634. this.vectors.push(this.minimum.clone());
  15635. this.vectors[3].y = this.maximum.y;
  15636. this.vectors.push(this.minimum.clone());
  15637. this.vectors[4].z = this.maximum.z;
  15638. this.vectors.push(this.maximum.clone());
  15639. this.vectors[5].z = this.minimum.z;
  15640. this.vectors.push(this.maximum.clone());
  15641. this.vectors[6].x = this.minimum.x;
  15642. this.vectors.push(this.maximum.clone());
  15643. this.vectors[7].y = this.minimum.y;
  15644. // OBB
  15645. this.center = this.maximum.add(this.minimum).scale(0.5);
  15646. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15647. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15648. // World
  15649. for (var index = 0; index < this.vectors.length; index++) {
  15650. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15651. }
  15652. this.minimumWorld = BABYLON.Vector3.Zero();
  15653. this.maximumWorld = BABYLON.Vector3.Zero();
  15654. this.centerWorld = BABYLON.Vector3.Zero();
  15655. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15656. this._update(BABYLON.Matrix.Identity());
  15657. }
  15658. // Methods
  15659. BoundingBox.prototype.getWorldMatrix = function () {
  15660. return this._worldMatrix;
  15661. };
  15662. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15663. this._worldMatrix.copyFrom(matrix);
  15664. return this;
  15665. };
  15666. BoundingBox.prototype._update = function (world) {
  15667. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15668. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15669. for (var index = 0; index < this.vectors.length; index++) {
  15670. var v = this.vectorsWorld[index];
  15671. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15672. if (v.x < this.minimumWorld.x)
  15673. this.minimumWorld.x = v.x;
  15674. if (v.y < this.minimumWorld.y)
  15675. this.minimumWorld.y = v.y;
  15676. if (v.z < this.minimumWorld.z)
  15677. this.minimumWorld.z = v.z;
  15678. if (v.x > this.maximumWorld.x)
  15679. this.maximumWorld.x = v.x;
  15680. if (v.y > this.maximumWorld.y)
  15681. this.maximumWorld.y = v.y;
  15682. if (v.z > this.maximumWorld.z)
  15683. this.maximumWorld.z = v.z;
  15684. }
  15685. // Extend
  15686. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15687. this.extendSizeWorld.scaleInPlace(0.5);
  15688. // OBB
  15689. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15690. this.centerWorld.scaleInPlace(0.5);
  15691. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15692. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15693. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15694. this._worldMatrix = world;
  15695. };
  15696. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15697. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15698. };
  15699. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15700. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15701. };
  15702. BoundingBox.prototype.intersectsPoint = function (point) {
  15703. var delta = -BABYLON.Epsilon;
  15704. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15705. return false;
  15706. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15707. return false;
  15708. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15709. return false;
  15710. return true;
  15711. };
  15712. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15713. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15714. };
  15715. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15716. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15717. return false;
  15718. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15719. return false;
  15720. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15721. return false;
  15722. return true;
  15723. };
  15724. // Statics
  15725. BoundingBox.Intersects = function (box0, box1) {
  15726. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15727. return false;
  15728. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15729. return false;
  15730. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15731. return false;
  15732. return true;
  15733. };
  15734. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15735. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15736. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15737. return (num <= (sphereRadius * sphereRadius));
  15738. };
  15739. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15740. for (var p = 0; p < 6; p++) {
  15741. for (var i = 0; i < 8; i++) {
  15742. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15743. return false;
  15744. }
  15745. }
  15746. }
  15747. return true;
  15748. };
  15749. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15750. for (var p = 0; p < 6; p++) {
  15751. var inCount = 8;
  15752. for (var i = 0; i < 8; i++) {
  15753. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15754. --inCount;
  15755. }
  15756. else {
  15757. break;
  15758. }
  15759. }
  15760. if (inCount === 0)
  15761. return false;
  15762. }
  15763. return true;
  15764. };
  15765. return BoundingBox;
  15766. }());
  15767. BABYLON.BoundingBox = BoundingBox;
  15768. })(BABYLON || (BABYLON = {}));
  15769. //# sourceMappingURL=babylon.boundingBox.js.map
  15770. var BABYLON;
  15771. (function (BABYLON) {
  15772. var computeBoxExtents = function (axis, box) {
  15773. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15774. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15775. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15776. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15777. var r = r0 + r1 + r2;
  15778. return {
  15779. min: p - r,
  15780. max: p + r
  15781. };
  15782. };
  15783. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15784. var axisOverlap = function (axis, box0, box1) {
  15785. var result0 = computeBoxExtents(axis, box0);
  15786. var result1 = computeBoxExtents(axis, box1);
  15787. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15788. };
  15789. var BoundingInfo = /** @class */ (function () {
  15790. function BoundingInfo(minimum, maximum) {
  15791. this.minimum = minimum;
  15792. this.maximum = maximum;
  15793. this._isLocked = false;
  15794. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15795. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15796. }
  15797. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15798. get: function () {
  15799. return this._isLocked;
  15800. },
  15801. set: function (value) {
  15802. this._isLocked = value;
  15803. },
  15804. enumerable: true,
  15805. configurable: true
  15806. });
  15807. // Methods
  15808. BoundingInfo.prototype.update = function (world) {
  15809. if (this._isLocked) {
  15810. return;
  15811. }
  15812. this.boundingBox._update(world);
  15813. this.boundingSphere._update(world);
  15814. };
  15815. /**
  15816. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15817. * @param center New center of the bounding info
  15818. * @param extend New extend of the bounding info
  15819. */
  15820. BoundingInfo.prototype.centerOn = function (center, extend) {
  15821. this.minimum = center.subtract(extend);
  15822. this.maximum = center.add(extend);
  15823. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15824. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15825. return this;
  15826. };
  15827. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15828. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15829. return false;
  15830. return this.boundingBox.isInFrustum(frustumPlanes);
  15831. };
  15832. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15833. /**
  15834. * Gets the world distance between the min and max points of the bounding box
  15835. */
  15836. get: function () {
  15837. var boundingBox = this.boundingBox;
  15838. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15839. return size.length();
  15840. },
  15841. enumerable: true,
  15842. configurable: true
  15843. });
  15844. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15845. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15846. };
  15847. BoundingInfo.prototype._checkCollision = function (collider) {
  15848. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15849. };
  15850. BoundingInfo.prototype.intersectsPoint = function (point) {
  15851. if (!this.boundingSphere.centerWorld) {
  15852. return false;
  15853. }
  15854. if (!this.boundingSphere.intersectsPoint(point)) {
  15855. return false;
  15856. }
  15857. if (!this.boundingBox.intersectsPoint(point)) {
  15858. return false;
  15859. }
  15860. return true;
  15861. };
  15862. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15863. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15864. return false;
  15865. }
  15866. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15867. return false;
  15868. }
  15869. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15870. return false;
  15871. }
  15872. if (!precise) {
  15873. return true;
  15874. }
  15875. var box0 = this.boundingBox;
  15876. var box1 = boundingInfo.boundingBox;
  15877. if (!axisOverlap(box0.directions[0], box0, box1))
  15878. return false;
  15879. if (!axisOverlap(box0.directions[1], box0, box1))
  15880. return false;
  15881. if (!axisOverlap(box0.directions[2], box0, box1))
  15882. return false;
  15883. if (!axisOverlap(box1.directions[0], box0, box1))
  15884. return false;
  15885. if (!axisOverlap(box1.directions[1], box0, box1))
  15886. return false;
  15887. if (!axisOverlap(box1.directions[2], box0, box1))
  15888. return false;
  15889. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15890. return false;
  15891. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15892. return false;
  15893. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15894. return false;
  15895. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15896. return false;
  15897. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15898. return false;
  15899. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15900. return false;
  15901. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15902. return false;
  15903. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15904. return false;
  15905. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15906. return false;
  15907. return true;
  15908. };
  15909. return BoundingInfo;
  15910. }());
  15911. BABYLON.BoundingInfo = BoundingInfo;
  15912. })(BABYLON || (BABYLON = {}));
  15913. //# sourceMappingURL=babylon.boundingInfo.js.map
  15914. var BABYLON;
  15915. (function (BABYLON) {
  15916. var TransformNode = /** @class */ (function (_super) {
  15917. __extends(TransformNode, _super);
  15918. function TransformNode(name, scene, isPure) {
  15919. if (scene === void 0) { scene = null; }
  15920. if (isPure === void 0) { isPure = true; }
  15921. var _this = _super.call(this, name, scene) || this;
  15922. // Properties
  15923. _this._rotation = BABYLON.Vector3.Zero();
  15924. _this._scaling = BABYLON.Vector3.One();
  15925. _this._isDirty = false;
  15926. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15927. _this.scalingDeterminant = 1;
  15928. _this.infiniteDistance = false;
  15929. _this.position = BABYLON.Vector3.Zero();
  15930. _this._localWorld = BABYLON.Matrix.Zero();
  15931. _this._worldMatrix = BABYLON.Matrix.Zero();
  15932. _this._worldMatrixDeterminant = 0;
  15933. _this._absolutePosition = BABYLON.Vector3.Zero();
  15934. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15935. _this._postMultiplyPivotMatrix = false;
  15936. _this._isWorldMatrixFrozen = false;
  15937. /**
  15938. * An event triggered after the world matrix is updated
  15939. * @type {BABYLON.Observable}
  15940. */
  15941. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15942. _this._nonUniformScaling = false;
  15943. if (isPure) {
  15944. _this.getScene().addTransformNode(_this);
  15945. }
  15946. return _this;
  15947. }
  15948. Object.defineProperty(TransformNode.prototype, "rotation", {
  15949. /**
  15950. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15951. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15952. * Default : (0.0, 0.0, 0.0)
  15953. */
  15954. get: function () {
  15955. return this._rotation;
  15956. },
  15957. set: function (newRotation) {
  15958. this._rotation = newRotation;
  15959. },
  15960. enumerable: true,
  15961. configurable: true
  15962. });
  15963. Object.defineProperty(TransformNode.prototype, "scaling", {
  15964. /**
  15965. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15966. * Default : (1.0, 1.0, 1.0)
  15967. */
  15968. get: function () {
  15969. return this._scaling;
  15970. },
  15971. /**
  15972. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15973. * Default : (1.0, 1.0, 1.0)
  15974. */
  15975. set: function (newScaling) {
  15976. this._scaling = newScaling;
  15977. },
  15978. enumerable: true,
  15979. configurable: true
  15980. });
  15981. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15982. /**
  15983. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15984. * It's null by default.
  15985. * 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)
  15986. */
  15987. get: function () {
  15988. return this._rotationQuaternion;
  15989. },
  15990. set: function (quaternion) {
  15991. this._rotationQuaternion = quaternion;
  15992. //reset the rotation vector.
  15993. if (quaternion && this.rotation.length()) {
  15994. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  15995. }
  15996. },
  15997. enumerable: true,
  15998. configurable: true
  15999. });
  16000. /**
  16001. * Returns the latest update of the World matrix
  16002. * Returns a Matrix.
  16003. */
  16004. TransformNode.prototype.getWorldMatrix = function () {
  16005. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16006. this.computeWorldMatrix();
  16007. }
  16008. return this._worldMatrix;
  16009. };
  16010. /**
  16011. * Returns the latest update of the World matrix determinant.
  16012. */
  16013. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16014. return this._worldMatrixDeterminant;
  16015. };
  16016. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16017. /**
  16018. * Returns directly the latest state of the mesh World matrix.
  16019. * A Matrix is returned.
  16020. */
  16021. get: function () {
  16022. return this._worldMatrix;
  16023. },
  16024. enumerable: true,
  16025. configurable: true
  16026. });
  16027. /**
  16028. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16029. * Returns the AbstractMesh.
  16030. */
  16031. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16032. this._poseMatrix.copyFrom(matrix);
  16033. return this;
  16034. };
  16035. /**
  16036. * Returns the mesh Pose matrix.
  16037. * Returned object : Matrix
  16038. */
  16039. TransformNode.prototype.getPoseMatrix = function () {
  16040. return this._poseMatrix;
  16041. };
  16042. TransformNode.prototype._isSynchronized = function () {
  16043. if (this._isDirty) {
  16044. return false;
  16045. }
  16046. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16047. return false;
  16048. if (this._cache.pivotMatrixUpdated) {
  16049. return false;
  16050. }
  16051. if (this.infiniteDistance) {
  16052. return false;
  16053. }
  16054. if (!this._cache.position.equals(this.position))
  16055. return false;
  16056. if (this.rotationQuaternion) {
  16057. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16058. return false;
  16059. }
  16060. if (!this._cache.rotation.equals(this.rotation))
  16061. return false;
  16062. if (!this._cache.scaling.equals(this.scaling))
  16063. return false;
  16064. return true;
  16065. };
  16066. TransformNode.prototype._initCache = function () {
  16067. _super.prototype._initCache.call(this);
  16068. this._cache.localMatrixUpdated = false;
  16069. this._cache.position = BABYLON.Vector3.Zero();
  16070. this._cache.scaling = BABYLON.Vector3.Zero();
  16071. this._cache.rotation = BABYLON.Vector3.Zero();
  16072. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16073. this._cache.billboardMode = -1;
  16074. };
  16075. TransformNode.prototype.markAsDirty = function (property) {
  16076. if (property === "rotation") {
  16077. this.rotationQuaternion = null;
  16078. }
  16079. this._currentRenderId = Number.MAX_VALUE;
  16080. this._isDirty = true;
  16081. return this;
  16082. };
  16083. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16084. /**
  16085. * Returns the current mesh absolute position.
  16086. * Retuns a Vector3.
  16087. */
  16088. get: function () {
  16089. return this._absolutePosition;
  16090. },
  16091. enumerable: true,
  16092. configurable: true
  16093. });
  16094. /**
  16095. * Sets a new matrix to apply before all other transformation
  16096. * @param matrix defines the transform matrix
  16097. * @returns the current TransformNode
  16098. */
  16099. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16100. return this.setPivotMatrix(matrix, false);
  16101. };
  16102. /**
  16103. * Sets a new pivot matrix to the current node
  16104. * @param matrix defines the new pivot matrix to use
  16105. * @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
  16106. * @returns the current TransformNode
  16107. */
  16108. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16109. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16110. this._pivotMatrix = matrix.clone();
  16111. this._cache.pivotMatrixUpdated = true;
  16112. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16113. if (this._postMultiplyPivotMatrix) {
  16114. if (!this._pivotMatrixInverse) {
  16115. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16116. }
  16117. else {
  16118. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16119. }
  16120. }
  16121. return this;
  16122. };
  16123. /**
  16124. * Returns the mesh pivot matrix.
  16125. * Default : Identity.
  16126. * A Matrix is returned.
  16127. */
  16128. TransformNode.prototype.getPivotMatrix = function () {
  16129. return this._pivotMatrix;
  16130. };
  16131. /**
  16132. * Prevents the World matrix to be computed any longer.
  16133. * Returns the AbstractMesh.
  16134. */
  16135. TransformNode.prototype.freezeWorldMatrix = function () {
  16136. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16137. this.computeWorldMatrix(true);
  16138. this._isWorldMatrixFrozen = true;
  16139. return this;
  16140. };
  16141. /**
  16142. * Allows back the World matrix computation.
  16143. * Returns the AbstractMesh.
  16144. */
  16145. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16146. this._isWorldMatrixFrozen = false;
  16147. this.computeWorldMatrix(true);
  16148. return this;
  16149. };
  16150. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16151. /**
  16152. * True if the World matrix has been frozen.
  16153. * Returns a boolean.
  16154. */
  16155. get: function () {
  16156. return this._isWorldMatrixFrozen;
  16157. },
  16158. enumerable: true,
  16159. configurable: true
  16160. });
  16161. /**
  16162. * Retuns the mesh absolute position in the World.
  16163. * Returns a Vector3.
  16164. */
  16165. TransformNode.prototype.getAbsolutePosition = function () {
  16166. this.computeWorldMatrix();
  16167. return this._absolutePosition;
  16168. };
  16169. /**
  16170. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16171. * Returns the AbstractMesh.
  16172. */
  16173. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16174. if (!absolutePosition) {
  16175. return this;
  16176. }
  16177. var absolutePositionX;
  16178. var absolutePositionY;
  16179. var absolutePositionZ;
  16180. if (absolutePosition.x === undefined) {
  16181. if (arguments.length < 3) {
  16182. return this;
  16183. }
  16184. absolutePositionX = arguments[0];
  16185. absolutePositionY = arguments[1];
  16186. absolutePositionZ = arguments[2];
  16187. }
  16188. else {
  16189. absolutePositionX = absolutePosition.x;
  16190. absolutePositionY = absolutePosition.y;
  16191. absolutePositionZ = absolutePosition.z;
  16192. }
  16193. if (this.parent) {
  16194. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16195. invertParentWorldMatrix.invert();
  16196. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16197. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16198. }
  16199. else {
  16200. this.position.x = absolutePositionX;
  16201. this.position.y = absolutePositionY;
  16202. this.position.z = absolutePositionZ;
  16203. }
  16204. return this;
  16205. };
  16206. /**
  16207. * Sets the mesh position in its local space.
  16208. * Returns the AbstractMesh.
  16209. */
  16210. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16211. this.computeWorldMatrix();
  16212. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16213. return this;
  16214. };
  16215. /**
  16216. * Returns the mesh position in the local space from the current World matrix values.
  16217. * Returns a new Vector3.
  16218. */
  16219. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16220. this.computeWorldMatrix();
  16221. var invLocalWorldMatrix = this._localWorld.clone();
  16222. invLocalWorldMatrix.invert();
  16223. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16224. };
  16225. /**
  16226. * Translates the mesh along the passed Vector3 in its local space.
  16227. * Returns the AbstractMesh.
  16228. */
  16229. TransformNode.prototype.locallyTranslate = function (vector3) {
  16230. this.computeWorldMatrix(true);
  16231. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16232. return this;
  16233. };
  16234. /**
  16235. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16236. * @param targetPoint the position (must be in same space as current mesh) to look at
  16237. * @param yawCor optional yaw (y-axis) correction in radians
  16238. * @param pitchCor optional pitch (x-axis) correction in radians
  16239. * @param rollCor optional roll (z-axis) correction in radians
  16240. * @param space the choosen space of the target
  16241. * @returns the TransformNode.
  16242. */
  16243. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16244. if (yawCor === void 0) { yawCor = 0; }
  16245. if (pitchCor === void 0) { pitchCor = 0; }
  16246. if (rollCor === void 0) { rollCor = 0; }
  16247. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16248. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16249. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16250. targetPoint.subtractToRef(pos, dv);
  16251. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16252. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16253. var pitch = Math.atan2(dv.y, len);
  16254. if (this.rotationQuaternion) {
  16255. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16256. }
  16257. else {
  16258. this.rotation.x = pitch + pitchCor;
  16259. this.rotation.y = yaw + yawCor;
  16260. this.rotation.z = rollCor;
  16261. }
  16262. return this;
  16263. };
  16264. /**
  16265. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16266. * This Vector3 is expressed in the World space.
  16267. */
  16268. TransformNode.prototype.getDirection = function (localAxis) {
  16269. var result = BABYLON.Vector3.Zero();
  16270. this.getDirectionToRef(localAxis, result);
  16271. return result;
  16272. };
  16273. /**
  16274. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16275. * localAxis is expressed in the mesh local space.
  16276. * result is computed in the Wordl space from the mesh World matrix.
  16277. * Returns the AbstractMesh.
  16278. */
  16279. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16280. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16281. return this;
  16282. };
  16283. /**
  16284. * Sets a new pivot point to the current node
  16285. * @param point defines the new pivot point to use
  16286. * @param space defines if the point is in world or local space (local by default)
  16287. * @returns the current TransformNode
  16288. */
  16289. TransformNode.prototype.setPivotPoint = function (point, space) {
  16290. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16291. if (this.getScene().getRenderId() == 0) {
  16292. this.computeWorldMatrix(true);
  16293. }
  16294. var wm = this.getWorldMatrix();
  16295. if (space == BABYLON.Space.WORLD) {
  16296. var tmat = BABYLON.Tmp.Matrix[0];
  16297. wm.invertToRef(tmat);
  16298. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16299. }
  16300. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16301. };
  16302. /**
  16303. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16304. */
  16305. TransformNode.prototype.getPivotPoint = function () {
  16306. var point = BABYLON.Vector3.Zero();
  16307. this.getPivotPointToRef(point);
  16308. return point;
  16309. };
  16310. /**
  16311. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16312. * Returns the AbstractMesh.
  16313. */
  16314. TransformNode.prototype.getPivotPointToRef = function (result) {
  16315. result.x = -this._pivotMatrix.m[12];
  16316. result.y = -this._pivotMatrix.m[13];
  16317. result.z = -this._pivotMatrix.m[14];
  16318. return this;
  16319. };
  16320. /**
  16321. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16322. */
  16323. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16324. var point = BABYLON.Vector3.Zero();
  16325. this.getAbsolutePivotPointToRef(point);
  16326. return point;
  16327. };
  16328. /**
  16329. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16330. * Returns the AbstractMesh.
  16331. */
  16332. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16333. result.x = this._pivotMatrix.m[12];
  16334. result.y = this._pivotMatrix.m[13];
  16335. result.z = this._pivotMatrix.m[14];
  16336. this.getPivotPointToRef(result);
  16337. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16338. return this;
  16339. };
  16340. /**
  16341. * Defines the passed node as the parent of the current node.
  16342. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16343. * Returns the TransformNode.
  16344. */
  16345. TransformNode.prototype.setParent = function (node) {
  16346. if (node === null) {
  16347. var rotation = BABYLON.Tmp.Quaternion[0];
  16348. var position = BABYLON.Tmp.Vector3[0];
  16349. var scale = BABYLON.Tmp.Vector3[1];
  16350. if (this.parent && this.parent.computeWorldMatrix) {
  16351. this.parent.computeWorldMatrix(true);
  16352. }
  16353. this.computeWorldMatrix(true);
  16354. this.getWorldMatrix().decompose(scale, rotation, position);
  16355. if (this.rotationQuaternion) {
  16356. this.rotationQuaternion.copyFrom(rotation);
  16357. }
  16358. else {
  16359. rotation.toEulerAnglesToRef(this.rotation);
  16360. }
  16361. this.scaling.x = scale.x;
  16362. this.scaling.y = scale.y;
  16363. this.scaling.z = scale.z;
  16364. this.position.x = position.x;
  16365. this.position.y = position.y;
  16366. this.position.z = position.z;
  16367. }
  16368. else {
  16369. var rotation = BABYLON.Tmp.Quaternion[0];
  16370. var position = BABYLON.Tmp.Vector3[0];
  16371. var scale = BABYLON.Tmp.Vector3[1];
  16372. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16373. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16374. this.computeWorldMatrix(true);
  16375. node.computeWorldMatrix(true);
  16376. node.getWorldMatrix().invertToRef(invParentMatrix);
  16377. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16378. diffMatrix.decompose(scale, rotation, position);
  16379. if (this.rotationQuaternion) {
  16380. this.rotationQuaternion.copyFrom(rotation);
  16381. }
  16382. else {
  16383. rotation.toEulerAnglesToRef(this.rotation);
  16384. }
  16385. this.position.x = position.x;
  16386. this.position.y = position.y;
  16387. this.position.z = position.z;
  16388. this.scaling.x = scale.x;
  16389. this.scaling.y = scale.y;
  16390. this.scaling.z = scale.z;
  16391. }
  16392. this.parent = node;
  16393. return this;
  16394. };
  16395. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16396. get: function () {
  16397. return this._nonUniformScaling;
  16398. },
  16399. enumerable: true,
  16400. configurable: true
  16401. });
  16402. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16403. if (this._nonUniformScaling === value) {
  16404. return false;
  16405. }
  16406. this._nonUniformScaling = true;
  16407. return true;
  16408. };
  16409. /**
  16410. * Attach the current TransformNode to another TransformNode associated with a bone
  16411. * @param bone Bone affecting the TransformNode
  16412. * @param affectedTransformNode TransformNode associated with the bone
  16413. */
  16414. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16415. this._transformToBoneReferal = affectedTransformNode;
  16416. this.parent = bone;
  16417. if (bone.getWorldMatrix().determinant() < 0) {
  16418. this.scalingDeterminant *= -1;
  16419. }
  16420. return this;
  16421. };
  16422. TransformNode.prototype.detachFromBone = function () {
  16423. if (!this.parent) {
  16424. return this;
  16425. }
  16426. if (this.parent.getWorldMatrix().determinant() < 0) {
  16427. this.scalingDeterminant *= -1;
  16428. }
  16429. this._transformToBoneReferal = null;
  16430. this.parent = null;
  16431. return this;
  16432. };
  16433. /**
  16434. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16435. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16436. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16437. * The passed axis is also normalized.
  16438. * Returns the AbstractMesh.
  16439. */
  16440. TransformNode.prototype.rotate = function (axis, amount, space) {
  16441. axis.normalize();
  16442. if (!this.rotationQuaternion) {
  16443. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16444. this.rotation = BABYLON.Vector3.Zero();
  16445. }
  16446. var rotationQuaternion;
  16447. if (!space || space === BABYLON.Space.LOCAL) {
  16448. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16449. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16450. }
  16451. else {
  16452. if (this.parent) {
  16453. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16454. invertParentWorldMatrix.invert();
  16455. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16456. }
  16457. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16458. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16459. }
  16460. return this;
  16461. };
  16462. /**
  16463. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16464. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16465. * The passed axis is also normalized.
  16466. * Returns the AbstractMesh.
  16467. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16468. */
  16469. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16470. axis.normalize();
  16471. if (!this.rotationQuaternion) {
  16472. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16473. this.rotation.copyFromFloats(0, 0, 0);
  16474. }
  16475. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16476. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16477. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16478. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16479. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16480. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16481. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16482. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16483. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16484. return this;
  16485. };
  16486. /**
  16487. * Translates the mesh along the axis vector for the passed distance in the given space.
  16488. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16489. * Returns the AbstractMesh.
  16490. */
  16491. TransformNode.prototype.translate = function (axis, distance, space) {
  16492. var displacementVector = axis.scale(distance);
  16493. if (!space || space === BABYLON.Space.LOCAL) {
  16494. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16495. this.setPositionWithLocalVector(tempV3);
  16496. }
  16497. else {
  16498. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16499. }
  16500. return this;
  16501. };
  16502. /**
  16503. * Adds a rotation step to the mesh current rotation.
  16504. * x, y, z are Euler angles expressed in radians.
  16505. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16506. * This means this rotation is made in the mesh local space only.
  16507. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16508. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16509. * ```javascript
  16510. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16511. * ```
  16512. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16513. * 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.
  16514. * Returns the AbstractMesh.
  16515. */
  16516. TransformNode.prototype.addRotation = function (x, y, z) {
  16517. var rotationQuaternion;
  16518. if (this.rotationQuaternion) {
  16519. rotationQuaternion = this.rotationQuaternion;
  16520. }
  16521. else {
  16522. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16523. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16524. }
  16525. var accumulation = BABYLON.Tmp.Quaternion[0];
  16526. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16527. rotationQuaternion.multiplyInPlace(accumulation);
  16528. if (!this.rotationQuaternion) {
  16529. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16530. }
  16531. return this;
  16532. };
  16533. /**
  16534. * Computes the mesh World matrix and returns it.
  16535. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16536. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16537. * If the parameter `force`is set to `true`, the actual computation is done.
  16538. * Returns the mesh World Matrix.
  16539. */
  16540. TransformNode.prototype.computeWorldMatrix = function (force) {
  16541. if (this._isWorldMatrixFrozen) {
  16542. return this._worldMatrix;
  16543. }
  16544. if (!force && this.isSynchronized(true)) {
  16545. return this._worldMatrix;
  16546. }
  16547. this._cache.position.copyFrom(this.position);
  16548. this._cache.scaling.copyFrom(this.scaling);
  16549. this._cache.pivotMatrixUpdated = false;
  16550. this._cache.billboardMode = this.billboardMode;
  16551. this._currentRenderId = this.getScene().getRenderId();
  16552. this._isDirty = false;
  16553. // Scaling
  16554. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16555. // Rotation
  16556. //rotate, if quaternion is set and rotation was used
  16557. if (this.rotationQuaternion) {
  16558. var len = this.rotation.length();
  16559. if (len) {
  16560. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16561. this.rotation.copyFromFloats(0, 0, 0);
  16562. }
  16563. }
  16564. if (this.rotationQuaternion) {
  16565. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16566. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16567. }
  16568. else {
  16569. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16570. this._cache.rotation.copyFrom(this.rotation);
  16571. }
  16572. // Translation
  16573. var camera = this.getScene().activeCamera;
  16574. if (this.infiniteDistance && !this.parent && camera) {
  16575. var cameraWorldMatrix = camera.getWorldMatrix();
  16576. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16577. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16578. }
  16579. else {
  16580. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16581. }
  16582. // Composing transformations
  16583. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16584. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16585. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16586. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16587. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16588. // Need to decompose each rotation here
  16589. var currentPosition = BABYLON.Tmp.Vector3[3];
  16590. if (this.parent && this.parent.getWorldMatrix) {
  16591. if (this._transformToBoneReferal) {
  16592. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16593. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16594. }
  16595. else {
  16596. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16597. }
  16598. }
  16599. else {
  16600. currentPosition.copyFrom(this.position);
  16601. }
  16602. currentPosition.subtractInPlace(camera.globalPosition);
  16603. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16604. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16605. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16606. }
  16607. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16608. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16609. }
  16610. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16611. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16612. }
  16613. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16614. }
  16615. else {
  16616. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16617. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16618. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16619. }
  16620. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16621. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16622. }
  16623. // Local world
  16624. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16625. // Parent
  16626. if (this.parent && this.parent.getWorldMatrix) {
  16627. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16628. if (this._transformToBoneReferal) {
  16629. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16630. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16631. }
  16632. else {
  16633. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16634. }
  16635. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16636. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16637. this._worldMatrix.copyFrom(this._localWorld);
  16638. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16639. }
  16640. else {
  16641. if (this._transformToBoneReferal) {
  16642. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16643. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16644. }
  16645. else {
  16646. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16647. }
  16648. }
  16649. this._markSyncedWithParent();
  16650. }
  16651. else {
  16652. this._worldMatrix.copyFrom(this._localWorld);
  16653. }
  16654. // Post multiply inverse of pivotMatrix
  16655. if (this._postMultiplyPivotMatrix) {
  16656. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16657. }
  16658. // Normal matrix
  16659. if (this.scaling.isNonUniform) {
  16660. this._updateNonUniformScalingState(true);
  16661. }
  16662. else if (this.parent && this.parent._nonUniformScaling) {
  16663. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16664. }
  16665. else {
  16666. this._updateNonUniformScalingState(false);
  16667. }
  16668. this._afterComputeWorldMatrix();
  16669. // Absolute position
  16670. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16671. // Callbacks
  16672. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16673. if (!this._poseMatrix) {
  16674. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16675. }
  16676. // Cache the determinant
  16677. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16678. return this._worldMatrix;
  16679. };
  16680. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16681. };
  16682. /**
  16683. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16684. * @param func: callback function to add
  16685. *
  16686. * Returns the TransformNode.
  16687. */
  16688. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16689. this.onAfterWorldMatrixUpdateObservable.add(func);
  16690. return this;
  16691. };
  16692. /**
  16693. * Removes a registered callback function.
  16694. * Returns the TransformNode.
  16695. */
  16696. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16697. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16698. return this;
  16699. };
  16700. /**
  16701. * Clone the current transform node
  16702. * Returns the new transform node
  16703. * @param name Name of the new clone
  16704. * @param newParent New parent for the clone
  16705. * @param doNotCloneChildren Do not clone children hierarchy
  16706. */
  16707. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16708. var _this = this;
  16709. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16710. result.name = name;
  16711. result.id = name;
  16712. if (newParent) {
  16713. result.parent = newParent;
  16714. }
  16715. if (!doNotCloneChildren) {
  16716. // Children
  16717. var directDescendants = this.getDescendants(true);
  16718. for (var index = 0; index < directDescendants.length; index++) {
  16719. var child = directDescendants[index];
  16720. if (child.clone) {
  16721. child.clone(name + "." + child.name, result);
  16722. }
  16723. }
  16724. }
  16725. return result;
  16726. };
  16727. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16728. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16729. serializationObject.type = this.getClassName();
  16730. // Parent
  16731. if (this.parent) {
  16732. serializationObject.parentId = this.parent.id;
  16733. }
  16734. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16735. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16736. }
  16737. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16738. serializationObject.isEnabled = this.isEnabled();
  16739. // Parent
  16740. if (this.parent) {
  16741. serializationObject.parentId = this.parent.id;
  16742. }
  16743. return serializationObject;
  16744. };
  16745. // Statics
  16746. /**
  16747. * Returns a new TransformNode object parsed from the source provided.
  16748. * The parameter `parsedMesh` is the source.
  16749. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16750. */
  16751. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16752. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16753. if (BABYLON.Tags) {
  16754. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16755. }
  16756. if (parsedTransformNode.localMatrix) {
  16757. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16758. }
  16759. else if (parsedTransformNode.pivotMatrix) {
  16760. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16761. }
  16762. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16763. // Parent
  16764. if (parsedTransformNode.parentId) {
  16765. transformNode._waitingParentId = parsedTransformNode.parentId;
  16766. }
  16767. return transformNode;
  16768. };
  16769. /**
  16770. * Disposes the TransformNode.
  16771. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16772. * Returns nothing.
  16773. */
  16774. TransformNode.prototype.dispose = function (doNotRecurse) {
  16775. // Animations
  16776. this.getScene().stopAnimation(this);
  16777. // Remove from scene
  16778. this.getScene().removeTransformNode(this);
  16779. if (!doNotRecurse) {
  16780. // Children
  16781. var objects = this.getDescendants(true);
  16782. for (var index = 0; index < objects.length; index++) {
  16783. objects[index].dispose();
  16784. }
  16785. }
  16786. else {
  16787. var childMeshes = this.getChildMeshes(true);
  16788. for (index = 0; index < childMeshes.length; index++) {
  16789. var child = childMeshes[index];
  16790. child.parent = null;
  16791. child.computeWorldMatrix(true);
  16792. }
  16793. }
  16794. this.onAfterWorldMatrixUpdateObservable.clear();
  16795. _super.prototype.dispose.call(this);
  16796. };
  16797. // Statics
  16798. TransformNode.BILLBOARDMODE_NONE = 0;
  16799. TransformNode.BILLBOARDMODE_X = 1;
  16800. TransformNode.BILLBOARDMODE_Y = 2;
  16801. TransformNode.BILLBOARDMODE_Z = 4;
  16802. TransformNode.BILLBOARDMODE_ALL = 7;
  16803. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16804. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16805. __decorate([
  16806. BABYLON.serializeAsVector3()
  16807. ], TransformNode.prototype, "_rotation", void 0);
  16808. __decorate([
  16809. BABYLON.serializeAsQuaternion()
  16810. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16811. __decorate([
  16812. BABYLON.serializeAsVector3()
  16813. ], TransformNode.prototype, "_scaling", void 0);
  16814. __decorate([
  16815. BABYLON.serialize()
  16816. ], TransformNode.prototype, "billboardMode", void 0);
  16817. __decorate([
  16818. BABYLON.serialize()
  16819. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16820. __decorate([
  16821. BABYLON.serialize()
  16822. ], TransformNode.prototype, "infiniteDistance", void 0);
  16823. __decorate([
  16824. BABYLON.serializeAsVector3()
  16825. ], TransformNode.prototype, "position", void 0);
  16826. return TransformNode;
  16827. }(BABYLON.Node));
  16828. BABYLON.TransformNode = TransformNode;
  16829. })(BABYLON || (BABYLON = {}));
  16830. //# sourceMappingURL=babylon.transformNode.js.map
  16831. var BABYLON;
  16832. (function (BABYLON) {
  16833. var AbstractMesh = /** @class */ (function (_super) {
  16834. __extends(AbstractMesh, _super);
  16835. // Constructor
  16836. function AbstractMesh(name, scene) {
  16837. if (scene === void 0) { scene = null; }
  16838. var _this = _super.call(this, name, scene, false) || this;
  16839. _this._facetNb = 0; // facet number
  16840. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16841. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16842. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16843. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16844. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16845. _this._subDiv = {
  16846. max: 1,
  16847. X: 1,
  16848. Y: 1,
  16849. Z: 1
  16850. };
  16851. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16852. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16853. // Events
  16854. /**
  16855. * An event triggered when this mesh collides with another one
  16856. * @type {BABYLON.Observable}
  16857. */
  16858. _this.onCollideObservable = new BABYLON.Observable();
  16859. /**
  16860. * An event triggered when the collision's position changes
  16861. * @type {BABYLON.Observable}
  16862. */
  16863. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16864. /**
  16865. * An event triggered when material is changed
  16866. * @type {BABYLON.Observable}
  16867. */
  16868. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16869. // Properties
  16870. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16871. /**
  16872. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16873. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16874. * or
  16875. * 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.
  16876. * for more info check WebGl documentations
  16877. */
  16878. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16879. /**
  16880. * 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:
  16881. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16882. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16883. * 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.
  16884. */
  16885. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16886. /**
  16887. * 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.
  16888. * The default value is -1 which means don't break the query and wait till the result.
  16889. */
  16890. _this.occlusionRetryCount = -1;
  16891. _this._occlusionInternalRetryCounter = 0;
  16892. _this._isOccluded = false;
  16893. _this._isOcclusionQueryInProgress = false;
  16894. _this._visibility = 1.0;
  16895. _this.alphaIndex = Number.MAX_VALUE;
  16896. _this.isVisible = true;
  16897. _this.isPickable = true;
  16898. _this.showBoundingBox = false;
  16899. _this.showSubMeshesBoundingBox = false;
  16900. _this.isBlocker = false;
  16901. _this.enablePointerMoveEvents = false;
  16902. _this.renderingGroupId = 0;
  16903. _this._receiveShadows = false;
  16904. _this.renderOutline = false;
  16905. _this.outlineColor = BABYLON.Color3.Red();
  16906. _this.outlineWidth = 0.02;
  16907. _this.renderOverlay = false;
  16908. _this.overlayColor = BABYLON.Color3.Red();
  16909. _this.overlayAlpha = 0.5;
  16910. _this._hasVertexAlpha = false;
  16911. _this._useVertexColors = true;
  16912. _this._computeBonesUsingShaders = true;
  16913. _this._numBoneInfluencers = 4;
  16914. _this._applyFog = true;
  16915. _this.useOctreeForRenderingSelection = true;
  16916. _this.useOctreeForPicking = true;
  16917. _this.useOctreeForCollisions = true;
  16918. _this._layerMask = 0x0FFFFFFF;
  16919. /**
  16920. * True if the mesh must be rendered in any case.
  16921. */
  16922. _this.alwaysSelectAsActiveMesh = false;
  16923. /**
  16924. * This scene's action manager
  16925. * @type {BABYLON.ActionManager}
  16926. */
  16927. _this.actionManager = null;
  16928. // Physics
  16929. _this.physicsImpostor = null;
  16930. // Collisions
  16931. _this._checkCollisions = false;
  16932. _this._collisionMask = -1;
  16933. _this._collisionGroup = -1;
  16934. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16935. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16936. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16937. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16938. // Edges
  16939. _this.edgesWidth = 1;
  16940. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16941. // Cache
  16942. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16943. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16944. _this._renderId = 0;
  16945. _this._intersectionsInProgress = new Array();
  16946. _this._unIndexed = false;
  16947. _this._lightSources = new Array();
  16948. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16949. if (collidedMesh === void 0) { collidedMesh = null; }
  16950. //TODO move this to the collision coordinator!
  16951. if (_this.getScene().workerCollisions)
  16952. newPosition.multiplyInPlace(_this._collider._radius);
  16953. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16954. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16955. _this.position.addInPlace(_this._diffPositionForCollisions);
  16956. }
  16957. if (collidedMesh) {
  16958. _this.onCollideObservable.notifyObservers(collidedMesh);
  16959. }
  16960. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16961. };
  16962. _this.getScene().addMesh(_this);
  16963. _this._resyncLightSources();
  16964. return _this;
  16965. }
  16966. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16967. get: function () {
  16968. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16969. },
  16970. enumerable: true,
  16971. configurable: true
  16972. });
  16973. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16974. get: function () {
  16975. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16976. },
  16977. enumerable: true,
  16978. configurable: true
  16979. });
  16980. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16981. get: function () {
  16982. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16983. },
  16984. enumerable: true,
  16985. configurable: true
  16986. });
  16987. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16988. get: function () {
  16989. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16990. },
  16991. enumerable: true,
  16992. configurable: true
  16993. });
  16994. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  16995. get: function () {
  16996. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  16997. },
  16998. enumerable: true,
  16999. configurable: true
  17000. });
  17001. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17002. /**
  17003. * Read-only : the number of facets in the mesh
  17004. */
  17005. get: function () {
  17006. return this._facetNb;
  17007. },
  17008. enumerable: true,
  17009. configurable: true
  17010. });
  17011. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17012. /**
  17013. * The number (integer) of subdivisions per axis in the partioning space
  17014. */
  17015. get: function () {
  17016. return this._partitioningSubdivisions;
  17017. },
  17018. set: function (nb) {
  17019. this._partitioningSubdivisions = nb;
  17020. },
  17021. enumerable: true,
  17022. configurable: true
  17023. });
  17024. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17025. /**
  17026. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17027. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17028. */
  17029. get: function () {
  17030. return this._partitioningBBoxRatio;
  17031. },
  17032. set: function (ratio) {
  17033. this._partitioningBBoxRatio = ratio;
  17034. },
  17035. enumerable: true,
  17036. configurable: true
  17037. });
  17038. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17039. /**
  17040. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17041. * Works only for updatable meshes.
  17042. * Doesn't work with multi-materials.
  17043. */
  17044. get: function () {
  17045. return this._facetDepthSort;
  17046. },
  17047. set: function (sort) {
  17048. this._facetDepthSort = sort;
  17049. },
  17050. enumerable: true,
  17051. configurable: true
  17052. });
  17053. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17054. /**
  17055. * The location (Vector3) where the facet depth sort must be computed from.
  17056. * By default, the active camera position.
  17057. * Used only when facet depth sort is enabled.
  17058. */
  17059. get: function () {
  17060. return this._facetDepthSortFrom;
  17061. },
  17062. set: function (location) {
  17063. this._facetDepthSortFrom = location;
  17064. },
  17065. enumerable: true,
  17066. configurable: true
  17067. });
  17068. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17069. /**
  17070. * Read-only boolean : is the feature facetData enabled ?
  17071. */
  17072. get: function () {
  17073. return this._facetDataEnabled;
  17074. },
  17075. enumerable: true,
  17076. configurable: true
  17077. });
  17078. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17079. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17080. return false;
  17081. }
  17082. this._markSubMeshesAsMiscDirty();
  17083. return true;
  17084. };
  17085. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17086. set: function (callback) {
  17087. if (this._onCollideObserver) {
  17088. this.onCollideObservable.remove(this._onCollideObserver);
  17089. }
  17090. this._onCollideObserver = this.onCollideObservable.add(callback);
  17091. },
  17092. enumerable: true,
  17093. configurable: true
  17094. });
  17095. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17096. set: function (callback) {
  17097. if (this._onCollisionPositionChangeObserver) {
  17098. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17099. }
  17100. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17101. },
  17102. enumerable: true,
  17103. configurable: true
  17104. });
  17105. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17106. /**
  17107. * 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.
  17108. */
  17109. get: function () {
  17110. return this._isOccluded;
  17111. },
  17112. set: function (value) {
  17113. this._isOccluded = value;
  17114. },
  17115. enumerable: true,
  17116. configurable: true
  17117. });
  17118. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17119. /**
  17120. * Flag to check the progress status of the query
  17121. */
  17122. get: function () {
  17123. return this._isOcclusionQueryInProgress;
  17124. },
  17125. enumerable: true,
  17126. configurable: true
  17127. });
  17128. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17129. /**
  17130. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17131. */
  17132. get: function () {
  17133. return this._visibility;
  17134. },
  17135. /**
  17136. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17137. */
  17138. set: function (value) {
  17139. if (this._visibility === value) {
  17140. return;
  17141. }
  17142. this._visibility = value;
  17143. this._markSubMeshesAsMiscDirty();
  17144. },
  17145. enumerable: true,
  17146. configurable: true
  17147. });
  17148. Object.defineProperty(AbstractMesh.prototype, "material", {
  17149. get: function () {
  17150. return this._material;
  17151. },
  17152. set: function (value) {
  17153. if (this._material === value) {
  17154. return;
  17155. }
  17156. this._material = value;
  17157. if (this.onMaterialChangedObservable.hasObservers) {
  17158. this.onMaterialChangedObservable.notifyObservers(this);
  17159. }
  17160. if (!this.subMeshes) {
  17161. return;
  17162. }
  17163. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17164. var subMesh = _a[_i];
  17165. subMesh.setEffect(null);
  17166. }
  17167. },
  17168. enumerable: true,
  17169. configurable: true
  17170. });
  17171. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17172. get: function () {
  17173. return this._receiveShadows;
  17174. },
  17175. set: function (value) {
  17176. if (this._receiveShadows === value) {
  17177. return;
  17178. }
  17179. this._receiveShadows = value;
  17180. this._markSubMeshesAsLightDirty();
  17181. },
  17182. enumerable: true,
  17183. configurable: true
  17184. });
  17185. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17186. get: function () {
  17187. return this._hasVertexAlpha;
  17188. },
  17189. set: function (value) {
  17190. if (this._hasVertexAlpha === value) {
  17191. return;
  17192. }
  17193. this._hasVertexAlpha = value;
  17194. this._markSubMeshesAsAttributesDirty();
  17195. this._markSubMeshesAsMiscDirty();
  17196. },
  17197. enumerable: true,
  17198. configurable: true
  17199. });
  17200. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17201. get: function () {
  17202. return this._useVertexColors;
  17203. },
  17204. set: function (value) {
  17205. if (this._useVertexColors === value) {
  17206. return;
  17207. }
  17208. this._useVertexColors = value;
  17209. this._markSubMeshesAsAttributesDirty();
  17210. },
  17211. enumerable: true,
  17212. configurable: true
  17213. });
  17214. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17215. get: function () {
  17216. return this._computeBonesUsingShaders;
  17217. },
  17218. set: function (value) {
  17219. if (this._computeBonesUsingShaders === value) {
  17220. return;
  17221. }
  17222. this._computeBonesUsingShaders = value;
  17223. this._markSubMeshesAsAttributesDirty();
  17224. },
  17225. enumerable: true,
  17226. configurable: true
  17227. });
  17228. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17229. get: function () {
  17230. return this._numBoneInfluencers;
  17231. },
  17232. set: function (value) {
  17233. if (this._numBoneInfluencers === value) {
  17234. return;
  17235. }
  17236. this._numBoneInfluencers = value;
  17237. this._markSubMeshesAsAttributesDirty();
  17238. },
  17239. enumerable: true,
  17240. configurable: true
  17241. });
  17242. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17243. get: function () {
  17244. return this._applyFog;
  17245. },
  17246. set: function (value) {
  17247. if (this._applyFog === value) {
  17248. return;
  17249. }
  17250. this._applyFog = value;
  17251. this._markSubMeshesAsMiscDirty();
  17252. },
  17253. enumerable: true,
  17254. configurable: true
  17255. });
  17256. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17257. get: function () {
  17258. return this._layerMask;
  17259. },
  17260. set: function (value) {
  17261. if (value === this._layerMask) {
  17262. return;
  17263. }
  17264. this._layerMask = value;
  17265. this._resyncLightSources();
  17266. },
  17267. enumerable: true,
  17268. configurable: true
  17269. });
  17270. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17271. get: function () {
  17272. return this._collisionMask;
  17273. },
  17274. set: function (mask) {
  17275. this._collisionMask = !isNaN(mask) ? mask : -1;
  17276. },
  17277. enumerable: true,
  17278. configurable: true
  17279. });
  17280. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17281. get: function () {
  17282. return this._collisionGroup;
  17283. },
  17284. set: function (mask) {
  17285. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17286. },
  17287. enumerable: true,
  17288. configurable: true
  17289. });
  17290. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17291. get: function () {
  17292. return null;
  17293. },
  17294. enumerable: true,
  17295. configurable: true
  17296. });
  17297. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17298. get: function () {
  17299. return this._skeleton;
  17300. },
  17301. set: function (value) {
  17302. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17303. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17304. }
  17305. if (value && value.needInitialSkinMatrix) {
  17306. value._registerMeshWithPoseMatrix(this);
  17307. }
  17308. this._skeleton = value;
  17309. if (!this._skeleton) {
  17310. this._bonesTransformMatrices = null;
  17311. }
  17312. this._markSubMeshesAsAttributesDirty();
  17313. },
  17314. enumerable: true,
  17315. configurable: true
  17316. });
  17317. /**
  17318. * Returns the string "AbstractMesh"
  17319. */
  17320. AbstractMesh.prototype.getClassName = function () {
  17321. return "AbstractMesh";
  17322. };
  17323. /**
  17324. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17325. */
  17326. AbstractMesh.prototype.toString = function (fullDetails) {
  17327. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17328. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17329. if (this._skeleton) {
  17330. ret += ", skeleton: " + this._skeleton.name;
  17331. }
  17332. if (fullDetails) {
  17333. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17334. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17335. }
  17336. return ret;
  17337. };
  17338. AbstractMesh.prototype._rebuild = function () {
  17339. if (this._occlusionQuery) {
  17340. this._occlusionQuery = null;
  17341. }
  17342. if (this._edgesRenderer) {
  17343. this._edgesRenderer._rebuild();
  17344. }
  17345. if (!this.subMeshes) {
  17346. return;
  17347. }
  17348. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17349. var subMesh = _a[_i];
  17350. subMesh._rebuild();
  17351. }
  17352. };
  17353. AbstractMesh.prototype._resyncLightSources = function () {
  17354. this._lightSources.length = 0;
  17355. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17356. var light = _a[_i];
  17357. if (!light.isEnabled()) {
  17358. continue;
  17359. }
  17360. if (light.canAffectMesh(this)) {
  17361. this._lightSources.push(light);
  17362. }
  17363. }
  17364. this._markSubMeshesAsLightDirty();
  17365. };
  17366. AbstractMesh.prototype._resyncLighSource = function (light) {
  17367. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17368. var index = this._lightSources.indexOf(light);
  17369. if (index === -1) {
  17370. if (!isIn) {
  17371. return;
  17372. }
  17373. this._lightSources.push(light);
  17374. }
  17375. else {
  17376. if (isIn) {
  17377. return;
  17378. }
  17379. this._lightSources.splice(index, 1);
  17380. }
  17381. this._markSubMeshesAsLightDirty();
  17382. };
  17383. AbstractMesh.prototype._removeLightSource = function (light) {
  17384. var index = this._lightSources.indexOf(light);
  17385. if (index === -1) {
  17386. return;
  17387. }
  17388. this._lightSources.splice(index, 1);
  17389. this._markSubMeshesAsLightDirty();
  17390. };
  17391. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17392. if (!this.subMeshes) {
  17393. return;
  17394. }
  17395. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17396. var subMesh = _a[_i];
  17397. if (subMesh._materialDefines) {
  17398. func(subMesh._materialDefines);
  17399. }
  17400. }
  17401. };
  17402. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17403. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17404. };
  17405. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17406. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17407. };
  17408. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17409. if (!this.subMeshes) {
  17410. return;
  17411. }
  17412. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17413. var subMesh = _a[_i];
  17414. var material = subMesh.getMaterial();
  17415. if (material) {
  17416. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17417. }
  17418. }
  17419. };
  17420. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17421. /**
  17422. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17423. * Default : (1.0, 1.0, 1.0)
  17424. */
  17425. get: function () {
  17426. return this._scaling;
  17427. },
  17428. /**
  17429. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17430. * Default : (1.0, 1.0, 1.0)
  17431. */
  17432. set: function (newScaling) {
  17433. this._scaling = newScaling;
  17434. if (this.physicsImpostor) {
  17435. this.physicsImpostor.forceUpdate();
  17436. }
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. // Methods
  17442. /**
  17443. * Disables the mesh edger rendering mode.
  17444. * Returns the AbstractMesh.
  17445. */
  17446. AbstractMesh.prototype.disableEdgesRendering = function () {
  17447. if (this._edgesRenderer) {
  17448. this._edgesRenderer.dispose();
  17449. this._edgesRenderer = null;
  17450. }
  17451. return this;
  17452. };
  17453. /**
  17454. * Enables the edge rendering mode on the mesh.
  17455. * This mode makes the mesh edges visible.
  17456. * Returns the AbstractMesh.
  17457. */
  17458. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17459. if (epsilon === void 0) { epsilon = 0.95; }
  17460. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17461. this.disableEdgesRendering();
  17462. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17463. return this;
  17464. };
  17465. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17466. /**
  17467. * Returns true if the mesh is blocked. Used by the class Mesh.
  17468. * Returns the boolean `false` by default.
  17469. */
  17470. get: function () {
  17471. return false;
  17472. },
  17473. enumerable: true,
  17474. configurable: true
  17475. });
  17476. /**
  17477. * Returns the mesh itself by default, used by the class Mesh.
  17478. * Returned type : AbstractMesh
  17479. */
  17480. AbstractMesh.prototype.getLOD = function (camera) {
  17481. return this;
  17482. };
  17483. /**
  17484. * Returns 0 by default, used by the class Mesh.
  17485. * Returns an integer.
  17486. */
  17487. AbstractMesh.prototype.getTotalVertices = function () {
  17488. return 0;
  17489. };
  17490. /**
  17491. * Returns null by default, used by the class Mesh.
  17492. * Returned type : integer array
  17493. */
  17494. AbstractMesh.prototype.getIndices = function () {
  17495. return null;
  17496. };
  17497. /**
  17498. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17499. * Returned type : float array or Float32Array
  17500. */
  17501. AbstractMesh.prototype.getVerticesData = function (kind) {
  17502. return null;
  17503. };
  17504. /**
  17505. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17506. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17507. * The `data` are either a numeric array either a Float32Array.
  17508. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17509. * 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).
  17510. * Note that a new underlying VertexBuffer object is created each call.
  17511. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17512. *
  17513. * Possible `kind` values :
  17514. * - BABYLON.VertexBuffer.PositionKind
  17515. * - BABYLON.VertexBuffer.UVKind
  17516. * - BABYLON.VertexBuffer.UV2Kind
  17517. * - BABYLON.VertexBuffer.UV3Kind
  17518. * - BABYLON.VertexBuffer.UV4Kind
  17519. * - BABYLON.VertexBuffer.UV5Kind
  17520. * - BABYLON.VertexBuffer.UV6Kind
  17521. * - BABYLON.VertexBuffer.ColorKind
  17522. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17523. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17524. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17525. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17526. *
  17527. * Returns the Mesh.
  17528. */
  17529. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17530. return this;
  17531. };
  17532. /**
  17533. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17534. * If the mesh has no geometry, it is simply returned as it is.
  17535. * The `data` are either a numeric array either a Float32Array.
  17536. * No new underlying VertexBuffer object is created.
  17537. * 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.
  17538. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17539. *
  17540. * Possible `kind` values :
  17541. * - BABYLON.VertexBuffer.PositionKind
  17542. * - BABYLON.VertexBuffer.UVKind
  17543. * - BABYLON.VertexBuffer.UV2Kind
  17544. * - BABYLON.VertexBuffer.UV3Kind
  17545. * - BABYLON.VertexBuffer.UV4Kind
  17546. * - BABYLON.VertexBuffer.UV5Kind
  17547. * - BABYLON.VertexBuffer.UV6Kind
  17548. * - BABYLON.VertexBuffer.ColorKind
  17549. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17550. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17551. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17552. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17553. *
  17554. * Returns the Mesh.
  17555. */
  17556. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17557. return this;
  17558. };
  17559. /**
  17560. * Sets the mesh indices.
  17561. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17562. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17563. * This method creates a new index buffer each call.
  17564. * Returns the Mesh.
  17565. */
  17566. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17567. return this;
  17568. };
  17569. /** Returns false by default, used by the class Mesh.
  17570. * Returns a boolean
  17571. */
  17572. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17573. return false;
  17574. };
  17575. /**
  17576. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17577. * Returns a BoundingInfo
  17578. */
  17579. AbstractMesh.prototype.getBoundingInfo = function () {
  17580. if (this._masterMesh) {
  17581. return this._masterMesh.getBoundingInfo();
  17582. }
  17583. if (!this._boundingInfo) {
  17584. // this._boundingInfo is being created here
  17585. this._updateBoundingInfo();
  17586. }
  17587. // cannot be null.
  17588. return this._boundingInfo;
  17589. };
  17590. /**
  17591. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17592. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17593. */
  17594. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17595. if (includeDescendants === void 0) { includeDescendants = true; }
  17596. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17597. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17598. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17599. if (maxDimension === 0) {
  17600. return this;
  17601. }
  17602. var scale = 1 / maxDimension;
  17603. this.scaling.scaleInPlace(scale);
  17604. return this;
  17605. };
  17606. /**
  17607. * Sets a mesh new object BoundingInfo.
  17608. * Returns the AbstractMesh.
  17609. */
  17610. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17611. this._boundingInfo = boundingInfo;
  17612. return this;
  17613. };
  17614. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17615. get: function () {
  17616. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17617. },
  17618. enumerable: true,
  17619. configurable: true
  17620. });
  17621. AbstractMesh.prototype._preActivate = function () {
  17622. };
  17623. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17624. };
  17625. AbstractMesh.prototype._activate = function (renderId) {
  17626. this._renderId = renderId;
  17627. };
  17628. /**
  17629. * Returns the latest update of the World matrix
  17630. * Returns a Matrix.
  17631. */
  17632. AbstractMesh.prototype.getWorldMatrix = function () {
  17633. if (this._masterMesh) {
  17634. return this._masterMesh.getWorldMatrix();
  17635. }
  17636. return _super.prototype.getWorldMatrix.call(this);
  17637. };
  17638. /**
  17639. * Returns the latest update of the World matrix determinant.
  17640. */
  17641. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17642. if (this._masterMesh) {
  17643. return this._masterMesh._getWorldMatrixDeterminant();
  17644. }
  17645. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17646. };
  17647. // ================================== Point of View Movement =================================
  17648. /**
  17649. * Perform relative position change from the point of view of behind the front of the mesh.
  17650. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17651. * Supports definition of mesh facing forward or backward.
  17652. * @param {number} amountRight
  17653. * @param {number} amountUp
  17654. * @param {number} amountForward
  17655. *
  17656. * Returns the AbstractMesh.
  17657. */
  17658. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17659. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17660. return this;
  17661. };
  17662. /**
  17663. * Calculate relative position change from the point of view of behind the front of the mesh.
  17664. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17665. * Supports definition of mesh facing forward or backward.
  17666. * @param {number} amountRight
  17667. * @param {number} amountUp
  17668. * @param {number} amountForward
  17669. *
  17670. * Returns a new Vector3.
  17671. */
  17672. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17673. var rotMatrix = new BABYLON.Matrix();
  17674. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17675. rotQuaternion.toRotationMatrix(rotMatrix);
  17676. var translationDelta = BABYLON.Vector3.Zero();
  17677. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17678. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17679. return translationDelta;
  17680. };
  17681. // ================================== Point of View Rotation =================================
  17682. /**
  17683. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17684. * Supports definition of mesh facing forward or backward.
  17685. * @param {number} flipBack
  17686. * @param {number} twirlClockwise
  17687. * @param {number} tiltRight
  17688. *
  17689. * Returns the AbstractMesh.
  17690. */
  17691. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17692. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17693. return this;
  17694. };
  17695. /**
  17696. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17697. * Supports definition of mesh facing forward or backward.
  17698. * @param {number} flipBack
  17699. * @param {number} twirlClockwise
  17700. * @param {number} tiltRight
  17701. *
  17702. * Returns a new Vector3.
  17703. */
  17704. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17705. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17706. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17707. };
  17708. /**
  17709. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17710. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17711. */
  17712. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17713. if (includeDescendants === void 0) { includeDescendants = true; }
  17714. this.computeWorldMatrix(true);
  17715. var min;
  17716. var max;
  17717. var boundingInfo = this.getBoundingInfo();
  17718. if (!this.subMeshes) {
  17719. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17720. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17721. }
  17722. else {
  17723. min = boundingInfo.boundingBox.minimumWorld;
  17724. max = boundingInfo.boundingBox.maximumWorld;
  17725. }
  17726. if (includeDescendants) {
  17727. var descendants = this.getDescendants(false);
  17728. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17729. var descendant = descendants_1[_i];
  17730. var childMesh = descendant;
  17731. childMesh.computeWorldMatrix(true);
  17732. //make sure we have the needed params to get mix and max
  17733. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17734. continue;
  17735. }
  17736. var childBoundingInfo = childMesh.getBoundingInfo();
  17737. var boundingBox = childBoundingInfo.boundingBox;
  17738. var minBox = boundingBox.minimumWorld;
  17739. var maxBox = boundingBox.maximumWorld;
  17740. BABYLON.Tools.CheckExtends(minBox, min, max);
  17741. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17742. }
  17743. }
  17744. return {
  17745. min: min,
  17746. max: max
  17747. };
  17748. };
  17749. /**
  17750. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17751. * Returns the AbstractMesh.
  17752. */
  17753. AbstractMesh.prototype._updateBoundingInfo = function () {
  17754. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17755. this._boundingInfo.update(this.worldMatrixFromCache);
  17756. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17757. return this;
  17758. };
  17759. /**
  17760. * Update a mesh's children BoundingInfo objects only.
  17761. * Returns the AbstractMesh.
  17762. */
  17763. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17764. if (!this.subMeshes) {
  17765. return this;
  17766. }
  17767. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17768. var subMesh = this.subMeshes[subIndex];
  17769. if (!subMesh.IsGlobal) {
  17770. subMesh.updateBoundingInfo(matrix);
  17771. }
  17772. }
  17773. return this;
  17774. };
  17775. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17776. // Bounding info
  17777. this._updateBoundingInfo();
  17778. };
  17779. /**
  17780. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17781. * A mesh is in the frustum if its bounding box intersects the frustum.
  17782. * Boolean returned.
  17783. */
  17784. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17785. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17786. };
  17787. /**
  17788. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17789. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17790. * Boolean returned.
  17791. */
  17792. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17793. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17794. ;
  17795. };
  17796. /**
  17797. * True if the mesh intersects another mesh or a SolidParticle object.
  17798. * 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)
  17799. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17800. * Returns a boolean.
  17801. */
  17802. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17803. if (precise === void 0) { precise = false; }
  17804. if (!this._boundingInfo || !mesh._boundingInfo) {
  17805. return false;
  17806. }
  17807. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17808. return true;
  17809. }
  17810. if (includeDescendants) {
  17811. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17812. var child = _a[_i];
  17813. if (child.intersectsMesh(mesh, precise, true)) {
  17814. return true;
  17815. }
  17816. }
  17817. }
  17818. return false;
  17819. };
  17820. /**
  17821. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17822. * Returns a boolean.
  17823. */
  17824. AbstractMesh.prototype.intersectsPoint = function (point) {
  17825. if (!this._boundingInfo) {
  17826. return false;
  17827. }
  17828. return this._boundingInfo.intersectsPoint(point);
  17829. };
  17830. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17831. return this.physicsImpostor;
  17832. };
  17833. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17834. if (camera === void 0) { camera = null; }
  17835. if (!camera) {
  17836. camera = this.getScene().activeCamera;
  17837. }
  17838. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17839. };
  17840. /**
  17841. * Returns the distance from the mesh to the active camera.
  17842. * Returns a float.
  17843. */
  17844. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17845. if (camera === void 0) { camera = null; }
  17846. if (!camera) {
  17847. camera = this.getScene().activeCamera;
  17848. }
  17849. return this.absolutePosition.subtract(camera.position).length();
  17850. };
  17851. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17852. if (!this.physicsImpostor) {
  17853. return this;
  17854. }
  17855. this.physicsImpostor.applyImpulse(force, contactPoint);
  17856. return this;
  17857. };
  17858. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17859. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17860. return this;
  17861. }
  17862. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17863. mainPivot: pivot1,
  17864. connectedPivot: pivot2,
  17865. nativeParams: options
  17866. });
  17867. return this;
  17868. };
  17869. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17870. // Collisions
  17871. /**
  17872. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17873. * Default `false`.
  17874. */
  17875. get: function () {
  17876. return this._checkCollisions;
  17877. },
  17878. set: function (collisionEnabled) {
  17879. this._checkCollisions = collisionEnabled;
  17880. if (this.getScene().workerCollisions) {
  17881. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17882. }
  17883. },
  17884. enumerable: true,
  17885. configurable: true
  17886. });
  17887. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17888. /**
  17889. * Gets Collider object used to compute collisions (not physics)
  17890. */
  17891. get: function () {
  17892. return this._collider;
  17893. },
  17894. enumerable: true,
  17895. configurable: true
  17896. });
  17897. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17898. var globalPosition = this.getAbsolutePosition();
  17899. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17900. if (!this._collider) {
  17901. this._collider = new BABYLON.Collider();
  17902. }
  17903. this._collider._radius = this.ellipsoid;
  17904. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17905. return this;
  17906. };
  17907. // Submeshes octree
  17908. /**
  17909. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17910. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17911. * Returns an Octree of submeshes.
  17912. */
  17913. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17914. if (maxCapacity === void 0) { maxCapacity = 64; }
  17915. if (maxDepth === void 0) { maxDepth = 2; }
  17916. if (!this._submeshesOctree) {
  17917. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17918. }
  17919. this.computeWorldMatrix(true);
  17920. var boundingInfo = this.getBoundingInfo();
  17921. // Update octree
  17922. var bbox = boundingInfo.boundingBox;
  17923. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17924. return this._submeshesOctree;
  17925. };
  17926. // Collisions
  17927. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17928. this._generatePointsArray();
  17929. if (!this._positions) {
  17930. return this;
  17931. }
  17932. // Transformation
  17933. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17934. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17935. subMesh._lastColliderWorldVertices = [];
  17936. subMesh._trianglePlanes = [];
  17937. var start = subMesh.verticesStart;
  17938. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17939. for (var i = start; i < end; i++) {
  17940. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17941. }
  17942. }
  17943. // Collide
  17944. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17945. if (collider.collisionFound) {
  17946. collider.collidedMesh = this;
  17947. }
  17948. return this;
  17949. };
  17950. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17951. var subMeshes;
  17952. var len;
  17953. // Octrees
  17954. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17955. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17956. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17957. len = intersections.length;
  17958. subMeshes = intersections.data;
  17959. }
  17960. else {
  17961. subMeshes = this.subMeshes;
  17962. len = subMeshes.length;
  17963. }
  17964. for (var index = 0; index < len; index++) {
  17965. var subMesh = subMeshes[index];
  17966. // Bounding test
  17967. if (len > 1 && !subMesh._checkCollision(collider))
  17968. continue;
  17969. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17970. }
  17971. return this;
  17972. };
  17973. AbstractMesh.prototype._checkCollision = function (collider) {
  17974. // Bounding box test
  17975. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17976. return this;
  17977. // Transformation matrix
  17978. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17979. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17980. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17981. return this;
  17982. };
  17983. // Picking
  17984. AbstractMesh.prototype._generatePointsArray = function () {
  17985. return false;
  17986. };
  17987. /**
  17988. * Checks if the passed Ray intersects with the mesh.
  17989. * Returns an object PickingInfo.
  17990. */
  17991. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17992. var pickingInfo = new BABYLON.PickingInfo();
  17993. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  17994. return pickingInfo;
  17995. }
  17996. if (!this._generatePointsArray()) {
  17997. return pickingInfo;
  17998. }
  17999. var intersectInfo = null;
  18000. // Octrees
  18001. var subMeshes;
  18002. var len;
  18003. if (this._submeshesOctree && this.useOctreeForPicking) {
  18004. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18005. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18006. len = intersections.length;
  18007. subMeshes = intersections.data;
  18008. }
  18009. else {
  18010. subMeshes = this.subMeshes;
  18011. len = subMeshes.length;
  18012. }
  18013. for (var index = 0; index < len; index++) {
  18014. var subMesh = subMeshes[index];
  18015. // Bounding test
  18016. if (len > 1 && !subMesh.canIntersects(ray))
  18017. continue;
  18018. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18019. if (currentIntersectInfo) {
  18020. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18021. intersectInfo = currentIntersectInfo;
  18022. intersectInfo.subMeshId = index;
  18023. if (fastCheck) {
  18024. break;
  18025. }
  18026. }
  18027. }
  18028. }
  18029. if (intersectInfo) {
  18030. // Get picked point
  18031. var world = this.getWorldMatrix();
  18032. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18033. var direction = ray.direction.clone();
  18034. direction = direction.scale(intersectInfo.distance);
  18035. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18036. var pickedPoint = worldOrigin.add(worldDirection);
  18037. // Return result
  18038. pickingInfo.hit = true;
  18039. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18040. pickingInfo.pickedPoint = pickedPoint;
  18041. pickingInfo.pickedMesh = this;
  18042. pickingInfo.bu = intersectInfo.bu || 0;
  18043. pickingInfo.bv = intersectInfo.bv || 0;
  18044. pickingInfo.faceId = intersectInfo.faceId;
  18045. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18046. return pickingInfo;
  18047. }
  18048. return pickingInfo;
  18049. };
  18050. /**
  18051. * Clones the mesh, used by the class Mesh.
  18052. * Just returns `null` for an AbstractMesh.
  18053. */
  18054. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18055. return null;
  18056. };
  18057. /**
  18058. * Disposes all the mesh submeshes.
  18059. * Returns the AbstractMesh.
  18060. */
  18061. AbstractMesh.prototype.releaseSubMeshes = function () {
  18062. if (this.subMeshes) {
  18063. while (this.subMeshes.length) {
  18064. this.subMeshes[0].dispose();
  18065. }
  18066. }
  18067. else {
  18068. this.subMeshes = new Array();
  18069. }
  18070. return this;
  18071. };
  18072. /**
  18073. * Disposes the AbstractMesh.
  18074. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18075. * Returns nothing.
  18076. */
  18077. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18078. var _this = this;
  18079. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18080. var index;
  18081. // Action manager
  18082. if (this.actionManager !== undefined && this.actionManager !== null) {
  18083. this.actionManager.dispose();
  18084. this.actionManager = null;
  18085. }
  18086. // Skeleton
  18087. this.skeleton = null;
  18088. // Physics
  18089. if (this.physicsImpostor) {
  18090. this.physicsImpostor.dispose();
  18091. }
  18092. // Intersections in progress
  18093. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18094. var other = this._intersectionsInProgress[index];
  18095. var pos = other._intersectionsInProgress.indexOf(this);
  18096. other._intersectionsInProgress.splice(pos, 1);
  18097. }
  18098. this._intersectionsInProgress = [];
  18099. // Lights
  18100. var lights = this.getScene().lights;
  18101. lights.forEach(function (light) {
  18102. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18103. if (meshIndex !== -1) {
  18104. light.includedOnlyMeshes.splice(meshIndex, 1);
  18105. }
  18106. meshIndex = light.excludedMeshes.indexOf(_this);
  18107. if (meshIndex !== -1) {
  18108. light.excludedMeshes.splice(meshIndex, 1);
  18109. }
  18110. // Shadow generators
  18111. var generator = light.getShadowGenerator();
  18112. if (generator) {
  18113. var shadowMap = generator.getShadowMap();
  18114. if (shadowMap && shadowMap.renderList) {
  18115. meshIndex = shadowMap.renderList.indexOf(_this);
  18116. if (meshIndex !== -1) {
  18117. shadowMap.renderList.splice(meshIndex, 1);
  18118. }
  18119. }
  18120. }
  18121. });
  18122. // Edges
  18123. if (this._edgesRenderer) {
  18124. this._edgesRenderer.dispose();
  18125. this._edgesRenderer = null;
  18126. }
  18127. // SubMeshes
  18128. if (this.getClassName() !== "InstancedMesh") {
  18129. this.releaseSubMeshes();
  18130. }
  18131. // Octree
  18132. var sceneOctree = this.getScene().selectionOctree;
  18133. if (sceneOctree !== undefined && sceneOctree !== null) {
  18134. var index = sceneOctree.dynamicContent.indexOf(this);
  18135. if (index !== -1) {
  18136. sceneOctree.dynamicContent.splice(index, 1);
  18137. }
  18138. }
  18139. // Query
  18140. var engine = this.getScene().getEngine();
  18141. if (this._occlusionQuery) {
  18142. this._isOcclusionQueryInProgress = false;
  18143. engine.deleteQuery(this._occlusionQuery);
  18144. this._occlusionQuery = null;
  18145. }
  18146. // Engine
  18147. engine.wipeCaches();
  18148. // Remove from scene
  18149. this.getScene().removeMesh(this);
  18150. if (disposeMaterialAndTextures) {
  18151. if (this.material) {
  18152. this.material.dispose(false, true);
  18153. }
  18154. }
  18155. if (!doNotRecurse) {
  18156. // Particles
  18157. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18158. if (this.getScene().particleSystems[index].emitter === this) {
  18159. this.getScene().particleSystems[index].dispose();
  18160. index--;
  18161. }
  18162. }
  18163. }
  18164. // facet data
  18165. if (this._facetDataEnabled) {
  18166. this.disableFacetData();
  18167. }
  18168. this.onAfterWorldMatrixUpdateObservable.clear();
  18169. this.onCollideObservable.clear();
  18170. this.onCollisionPositionChangeObservable.clear();
  18171. _super.prototype.dispose.call(this, doNotRecurse);
  18172. };
  18173. /**
  18174. * Adds the passed mesh as a child to the current mesh.
  18175. * Returns the AbstractMesh.
  18176. */
  18177. AbstractMesh.prototype.addChild = function (mesh) {
  18178. mesh.setParent(this);
  18179. return this;
  18180. };
  18181. /**
  18182. * Removes the passed mesh from the current mesh children list.
  18183. * Returns the AbstractMesh.
  18184. */
  18185. AbstractMesh.prototype.removeChild = function (mesh) {
  18186. mesh.setParent(null);
  18187. return this;
  18188. };
  18189. // Facet data
  18190. /**
  18191. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18192. * Returns the AbstractMesh.
  18193. */
  18194. AbstractMesh.prototype._initFacetData = function () {
  18195. if (!this._facetNormals) {
  18196. this._facetNormals = new Array();
  18197. }
  18198. if (!this._facetPositions) {
  18199. this._facetPositions = new Array();
  18200. }
  18201. if (!this._facetPartitioning) {
  18202. this._facetPartitioning = new Array();
  18203. }
  18204. this._facetNb = (this.getIndices().length / 3) | 0;
  18205. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18206. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18207. for (var f = 0; f < this._facetNb; f++) {
  18208. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18209. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18210. }
  18211. this._facetDataEnabled = true;
  18212. return this;
  18213. };
  18214. /**
  18215. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18216. * This method can be called within the render loop.
  18217. * 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.
  18218. * Returns the AbstractMesh.
  18219. */
  18220. AbstractMesh.prototype.updateFacetData = function () {
  18221. if (!this._facetDataEnabled) {
  18222. this._initFacetData();
  18223. }
  18224. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18225. var indices = this.getIndices();
  18226. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18227. var bInfo = this.getBoundingInfo();
  18228. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18229. // init arrays, matrix and sort function on first call
  18230. this._facetDepthSortEnabled = true;
  18231. if (indices instanceof Uint16Array) {
  18232. this._depthSortedIndices = new Uint16Array(indices);
  18233. }
  18234. else if (indices instanceof Uint32Array) {
  18235. this._depthSortedIndices = new Uint32Array(indices);
  18236. }
  18237. else {
  18238. var needs32bits = false;
  18239. for (var i = 0; i < indices.length; i++) {
  18240. if (indices[i] > 65535) {
  18241. needs32bits = true;
  18242. break;
  18243. }
  18244. }
  18245. if (needs32bits) {
  18246. this._depthSortedIndices = new Uint32Array(indices);
  18247. }
  18248. else {
  18249. this._depthSortedIndices = new Uint16Array(indices);
  18250. }
  18251. }
  18252. this._facetDepthSortFunction = function (f1, f2) {
  18253. return (f2.sqDistance - f1.sqDistance);
  18254. };
  18255. if (!this._facetDepthSortFrom) {
  18256. var camera = this.getScene().activeCamera;
  18257. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18258. }
  18259. this._depthSortedFacets = [];
  18260. for (var f = 0; f < this._facetNb; f++) {
  18261. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18262. this._depthSortedFacets.push(depthSortedFacet);
  18263. }
  18264. this._invertedMatrix = BABYLON.Matrix.Identity();
  18265. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18266. }
  18267. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18268. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18269. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18270. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18271. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18272. this._subDiv.max = this._partitioningSubdivisions;
  18273. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18274. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18275. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18276. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18277. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18278. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18279. // set the parameters for ComputeNormals()
  18280. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18281. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18282. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18283. this._facetParameters.bInfo = bInfo;
  18284. this._facetParameters.bbSize = this._bbSize;
  18285. this._facetParameters.subDiv = this._subDiv;
  18286. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18287. this._facetParameters.depthSort = this._facetDepthSort;
  18288. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18289. this.computeWorldMatrix(true);
  18290. this._worldMatrix.invertToRef(this._invertedMatrix);
  18291. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18292. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18293. }
  18294. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18295. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18296. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18297. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18298. var l = (this._depthSortedIndices.length / 3) | 0;
  18299. for (var f = 0; f < l; f++) {
  18300. var sind = this._depthSortedFacets[f].ind;
  18301. this._depthSortedIndices[f * 3] = indices[sind];
  18302. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18303. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18304. }
  18305. this.updateIndices(this._depthSortedIndices);
  18306. }
  18307. return this;
  18308. };
  18309. /**
  18310. * Returns the facetLocalNormals array.
  18311. * The normals are expressed in the mesh local space.
  18312. */
  18313. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18314. if (!this._facetNormals) {
  18315. this.updateFacetData();
  18316. }
  18317. return this._facetNormals;
  18318. };
  18319. /**
  18320. * Returns the facetLocalPositions array.
  18321. * The facet positions are expressed in the mesh local space.
  18322. */
  18323. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18324. if (!this._facetPositions) {
  18325. this.updateFacetData();
  18326. }
  18327. return this._facetPositions;
  18328. };
  18329. /**
  18330. * Returns the facetLocalPartioning array.
  18331. */
  18332. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18333. if (!this._facetPartitioning) {
  18334. this.updateFacetData();
  18335. }
  18336. return this._facetPartitioning;
  18337. };
  18338. /**
  18339. * Returns the i-th facet position in the world system.
  18340. * This method allocates a new Vector3 per call.
  18341. */
  18342. AbstractMesh.prototype.getFacetPosition = function (i) {
  18343. var pos = BABYLON.Vector3.Zero();
  18344. this.getFacetPositionToRef(i, pos);
  18345. return pos;
  18346. };
  18347. /**
  18348. * Sets the reference Vector3 with the i-th facet position in the world system.
  18349. * Returns the AbstractMesh.
  18350. */
  18351. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18352. var localPos = (this.getFacetLocalPositions())[i];
  18353. var world = this.getWorldMatrix();
  18354. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18355. return this;
  18356. };
  18357. /**
  18358. * Returns the i-th facet normal in the world system.
  18359. * This method allocates a new Vector3 per call.
  18360. */
  18361. AbstractMesh.prototype.getFacetNormal = function (i) {
  18362. var norm = BABYLON.Vector3.Zero();
  18363. this.getFacetNormalToRef(i, norm);
  18364. return norm;
  18365. };
  18366. /**
  18367. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18368. * Returns the AbstractMesh.
  18369. */
  18370. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18371. var localNorm = (this.getFacetLocalNormals())[i];
  18372. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18373. return this;
  18374. };
  18375. /**
  18376. * 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).
  18377. */
  18378. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18379. var bInfo = this.getBoundingInfo();
  18380. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18381. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18382. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18383. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18384. return null;
  18385. }
  18386. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18387. };
  18388. /**
  18389. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18390. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18391. * 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.
  18392. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18393. * 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.
  18394. */
  18395. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18396. if (checkFace === void 0) { checkFace = false; }
  18397. if (facing === void 0) { facing = true; }
  18398. var world = this.getWorldMatrix();
  18399. var invMat = BABYLON.Tmp.Matrix[5];
  18400. world.invertToRef(invMat);
  18401. var invVect = BABYLON.Tmp.Vector3[8];
  18402. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18403. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18404. if (projected) {
  18405. // tranform the local computed projected vector to world coordinates
  18406. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18407. }
  18408. return closest;
  18409. };
  18410. /**
  18411. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18412. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18413. * 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.
  18414. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18415. * 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.
  18416. */
  18417. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18418. if (checkFace === void 0) { checkFace = false; }
  18419. if (facing === void 0) { facing = true; }
  18420. var closest = null;
  18421. var tmpx = 0.0;
  18422. var tmpy = 0.0;
  18423. var tmpz = 0.0;
  18424. var d = 0.0; // tmp dot facet normal * facet position
  18425. var t0 = 0.0;
  18426. var projx = 0.0;
  18427. var projy = 0.0;
  18428. var projz = 0.0;
  18429. // Get all the facets in the same partitioning block than (x, y, z)
  18430. var facetPositions = this.getFacetLocalPositions();
  18431. var facetNormals = this.getFacetLocalNormals();
  18432. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18433. if (!facetsInBlock) {
  18434. return null;
  18435. }
  18436. // Get the closest facet to (x, y, z)
  18437. var shortest = Number.MAX_VALUE; // init distance vars
  18438. var tmpDistance = shortest;
  18439. var fib; // current facet in the block
  18440. var norm; // current facet normal
  18441. var p0; // current facet barycenter position
  18442. // loop on all the facets in the current partitioning block
  18443. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18444. fib = facetsInBlock[idx];
  18445. norm = facetNormals[fib];
  18446. p0 = facetPositions[fib];
  18447. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18448. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18449. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18450. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18451. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18452. projx = x + norm.x * t0;
  18453. projy = y + norm.y * t0;
  18454. projz = z + norm.z * t0;
  18455. tmpx = projx - x;
  18456. tmpy = projy - y;
  18457. tmpz = projz - z;
  18458. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18459. if (tmpDistance < shortest) {
  18460. shortest = tmpDistance;
  18461. closest = fib;
  18462. if (projected) {
  18463. projected.x = projx;
  18464. projected.y = projy;
  18465. projected.z = projz;
  18466. }
  18467. }
  18468. }
  18469. }
  18470. return closest;
  18471. };
  18472. /**
  18473. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18474. */
  18475. AbstractMesh.prototype.getFacetDataParameters = function () {
  18476. return this._facetParameters;
  18477. };
  18478. /**
  18479. * Disables the feature FacetData and frees the related memory.
  18480. * Returns the AbstractMesh.
  18481. */
  18482. AbstractMesh.prototype.disableFacetData = function () {
  18483. if (this._facetDataEnabled) {
  18484. this._facetDataEnabled = false;
  18485. this._facetPositions = new Array();
  18486. this._facetNormals = new Array();
  18487. this._facetPartitioning = new Array();
  18488. this._facetParameters = null;
  18489. this._depthSortedIndices = new Uint32Array(0);
  18490. }
  18491. return this;
  18492. };
  18493. /**
  18494. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18495. * Returns the mesh.
  18496. */
  18497. AbstractMesh.prototype.updateIndices = function (indices) {
  18498. return this;
  18499. };
  18500. /**
  18501. * The mesh Geometry. Actually used by the Mesh object.
  18502. * Returns a blank geometry object.
  18503. */
  18504. /**
  18505. * Creates new normals data for the mesh.
  18506. * @param updatable.
  18507. */
  18508. AbstractMesh.prototype.createNormals = function (updatable) {
  18509. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18510. var indices = this.getIndices();
  18511. var normals;
  18512. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18513. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18514. }
  18515. else {
  18516. normals = [];
  18517. }
  18518. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18519. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18520. };
  18521. /**
  18522. * Align the mesh with a normal.
  18523. * Returns the mesh.
  18524. */
  18525. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18526. if (!upDirection) {
  18527. upDirection = BABYLON.Axis.Y;
  18528. }
  18529. var axisX = BABYLON.Tmp.Vector3[0];
  18530. var axisZ = BABYLON.Tmp.Vector3[1];
  18531. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18532. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18533. if (this.rotationQuaternion) {
  18534. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18535. }
  18536. else {
  18537. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18538. }
  18539. return this;
  18540. };
  18541. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18542. var engine = this.getEngine();
  18543. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18544. this._isOccluded = false;
  18545. return;
  18546. }
  18547. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18548. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18549. if (isOcclusionQueryAvailable) {
  18550. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18551. this._isOcclusionQueryInProgress = false;
  18552. this._occlusionInternalRetryCounter = 0;
  18553. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18554. }
  18555. else {
  18556. this._occlusionInternalRetryCounter++;
  18557. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18558. this._isOcclusionQueryInProgress = false;
  18559. this._occlusionInternalRetryCounter = 0;
  18560. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18561. // if strict continue the last state of the object.
  18562. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18563. }
  18564. else {
  18565. return;
  18566. }
  18567. }
  18568. }
  18569. var scene = this.getScene();
  18570. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18571. if (!this._occlusionQuery) {
  18572. this._occlusionQuery = engine.createQuery();
  18573. }
  18574. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18575. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18576. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18577. this._isOcclusionQueryInProgress = true;
  18578. };
  18579. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18580. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18581. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18582. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18583. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18584. return AbstractMesh;
  18585. }(BABYLON.TransformNode));
  18586. BABYLON.AbstractMesh = AbstractMesh;
  18587. })(BABYLON || (BABYLON = {}));
  18588. //# sourceMappingURL=babylon.abstractMesh.js.map
  18589. var BABYLON;
  18590. (function (BABYLON) {
  18591. /**
  18592. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18593. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18594. * 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.
  18595. */
  18596. var Light = /** @class */ (function (_super) {
  18597. __extends(Light, _super);
  18598. /**
  18599. * Creates a Light object in the scene.
  18600. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18601. * @param name The firendly name of the light
  18602. * @param scene The scene the light belongs too
  18603. */
  18604. function Light(name, scene) {
  18605. var _this = _super.call(this, name, scene) || this;
  18606. /**
  18607. * Diffuse gives the basic color to an object.
  18608. */
  18609. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18610. /**
  18611. * Specular produces a highlight color on an object.
  18612. * Note: This is note affecting PBR materials.
  18613. */
  18614. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18615. /**
  18616. * Strength of the light.
  18617. * Note: By default it is define in the framework own unit.
  18618. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18619. */
  18620. _this.intensity = 1.0;
  18621. /**
  18622. * Defines how far from the source the light is impacting in scene units.
  18623. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18624. */
  18625. _this.range = Number.MAX_VALUE;
  18626. /**
  18627. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18628. * of light.
  18629. */
  18630. _this._photometricScale = 1.0;
  18631. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18632. _this._radius = 0.00001;
  18633. /**
  18634. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18635. * exceeding the number allowed of the materials.
  18636. */
  18637. _this.renderPriority = 0;
  18638. /**
  18639. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18640. * the current shadow generator.
  18641. */
  18642. _this.shadowEnabled = true;
  18643. _this._excludeWithLayerMask = 0;
  18644. _this._includeOnlyWithLayerMask = 0;
  18645. _this._lightmapMode = 0;
  18646. /**
  18647. * @ignore Internal use only.
  18648. */
  18649. _this._excludedMeshesIds = new Array();
  18650. /**
  18651. * @ignore Internal use only.
  18652. */
  18653. _this._includedOnlyMeshesIds = new Array();
  18654. _this.getScene().addLight(_this);
  18655. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18656. _this._buildUniformLayout();
  18657. _this.includedOnlyMeshes = new Array();
  18658. _this.excludedMeshes = new Array();
  18659. _this._resyncMeshes();
  18660. return _this;
  18661. }
  18662. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18663. /**
  18664. * If every light affecting the material is in this lightmapMode,
  18665. * material.lightmapTexture adds or multiplies
  18666. * (depends on material.useLightmapAsShadowmap)
  18667. * after every other light calculations.
  18668. */
  18669. get: function () {
  18670. return Light._LIGHTMAP_DEFAULT;
  18671. },
  18672. enumerable: true,
  18673. configurable: true
  18674. });
  18675. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18676. /**
  18677. * material.lightmapTexture as only diffuse lighting from this light
  18678. * adds only specular lighting from this light
  18679. * adds dynamic shadows
  18680. */
  18681. get: function () {
  18682. return Light._LIGHTMAP_SPECULAR;
  18683. },
  18684. enumerable: true,
  18685. configurable: true
  18686. });
  18687. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18688. /**
  18689. * material.lightmapTexture as only lighting
  18690. * no light calculation from this light
  18691. * only adds dynamic shadows from this light
  18692. */
  18693. get: function () {
  18694. return Light._LIGHTMAP_SHADOWSONLY;
  18695. },
  18696. enumerable: true,
  18697. configurable: true
  18698. });
  18699. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18700. /**
  18701. * Each light type uses the default quantity according to its type:
  18702. * point/spot lights use luminous intensity
  18703. * directional lights use illuminance
  18704. */
  18705. get: function () {
  18706. return Light._INTENSITYMODE_AUTOMATIC;
  18707. },
  18708. enumerable: true,
  18709. configurable: true
  18710. });
  18711. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18712. /**
  18713. * lumen (lm)
  18714. */
  18715. get: function () {
  18716. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18717. },
  18718. enumerable: true,
  18719. configurable: true
  18720. });
  18721. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18722. /**
  18723. * candela (lm/sr)
  18724. */
  18725. get: function () {
  18726. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18727. },
  18728. enumerable: true,
  18729. configurable: true
  18730. });
  18731. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18732. /**
  18733. * lux (lm/m^2)
  18734. */
  18735. get: function () {
  18736. return Light._INTENSITYMODE_ILLUMINANCE;
  18737. },
  18738. enumerable: true,
  18739. configurable: true
  18740. });
  18741. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18742. /**
  18743. * nit (cd/m^2)
  18744. */
  18745. get: function () {
  18746. return Light._INTENSITYMODE_LUMINANCE;
  18747. },
  18748. enumerable: true,
  18749. configurable: true
  18750. });
  18751. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18752. /**
  18753. * Light type const id of the point light.
  18754. */
  18755. get: function () {
  18756. return Light._LIGHTTYPEID_POINTLIGHT;
  18757. },
  18758. enumerable: true,
  18759. configurable: true
  18760. });
  18761. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18762. /**
  18763. * Light type const id of the directional light.
  18764. */
  18765. get: function () {
  18766. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18767. },
  18768. enumerable: true,
  18769. configurable: true
  18770. });
  18771. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18772. /**
  18773. * Light type const id of the spot light.
  18774. */
  18775. get: function () {
  18776. return Light._LIGHTTYPEID_SPOTLIGHT;
  18777. },
  18778. enumerable: true,
  18779. configurable: true
  18780. });
  18781. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18782. /**
  18783. * Light type const id of the hemispheric light.
  18784. */
  18785. get: function () {
  18786. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. Object.defineProperty(Light.prototype, "intensityMode", {
  18792. /**
  18793. * Gets the photometric scale used to interpret the intensity.
  18794. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18795. */
  18796. get: function () {
  18797. return this._intensityMode;
  18798. },
  18799. /**
  18800. * Sets the photometric scale used to interpret the intensity.
  18801. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18802. */
  18803. set: function (value) {
  18804. this._intensityMode = value;
  18805. this._computePhotometricScale();
  18806. },
  18807. enumerable: true,
  18808. configurable: true
  18809. });
  18810. ;
  18811. ;
  18812. Object.defineProperty(Light.prototype, "radius", {
  18813. /**
  18814. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18815. */
  18816. get: function () {
  18817. return this._radius;
  18818. },
  18819. /**
  18820. * sets the light radius used by PBR Materials to simulate soft area lights.
  18821. */
  18822. set: function (value) {
  18823. this._radius = value;
  18824. this._computePhotometricScale();
  18825. },
  18826. enumerable: true,
  18827. configurable: true
  18828. });
  18829. ;
  18830. ;
  18831. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18832. /**
  18833. * Gets the only meshes impacted by this light.
  18834. */
  18835. get: function () {
  18836. return this._includedOnlyMeshes;
  18837. },
  18838. /**
  18839. * Sets the only meshes impacted by this light.
  18840. */
  18841. set: function (value) {
  18842. this._includedOnlyMeshes = value;
  18843. this._hookArrayForIncludedOnly(value);
  18844. },
  18845. enumerable: true,
  18846. configurable: true
  18847. });
  18848. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18849. /**
  18850. * Gets the meshes not impacted by this light.
  18851. */
  18852. get: function () {
  18853. return this._excludedMeshes;
  18854. },
  18855. /**
  18856. * Sets the meshes not impacted by this light.
  18857. */
  18858. set: function (value) {
  18859. this._excludedMeshes = value;
  18860. this._hookArrayForExcluded(value);
  18861. },
  18862. enumerable: true,
  18863. configurable: true
  18864. });
  18865. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18866. /**
  18867. * Gets the layer id use to find what meshes are not impacted by the light.
  18868. * Inactive if 0
  18869. */
  18870. get: function () {
  18871. return this._excludeWithLayerMask;
  18872. },
  18873. /**
  18874. * Sets the layer id use to find what meshes are not impacted by the light.
  18875. * Inactive if 0
  18876. */
  18877. set: function (value) {
  18878. this._excludeWithLayerMask = value;
  18879. this._resyncMeshes();
  18880. },
  18881. enumerable: true,
  18882. configurable: true
  18883. });
  18884. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18885. /**
  18886. * Gets the layer id use to find what meshes are impacted by the light.
  18887. * Inactive if 0
  18888. */
  18889. get: function () {
  18890. return this._includeOnlyWithLayerMask;
  18891. },
  18892. /**
  18893. * Sets the layer id use to find what meshes are impacted by the light.
  18894. * Inactive if 0
  18895. */
  18896. set: function (value) {
  18897. this._includeOnlyWithLayerMask = value;
  18898. this._resyncMeshes();
  18899. },
  18900. enumerable: true,
  18901. configurable: true
  18902. });
  18903. Object.defineProperty(Light.prototype, "lightmapMode", {
  18904. /**
  18905. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18906. */
  18907. get: function () {
  18908. return this._lightmapMode;
  18909. },
  18910. /**
  18911. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18912. */
  18913. set: function (value) {
  18914. if (this._lightmapMode === value) {
  18915. return;
  18916. }
  18917. this._lightmapMode = value;
  18918. this._markMeshesAsLightDirty();
  18919. },
  18920. enumerable: true,
  18921. configurable: true
  18922. });
  18923. /**
  18924. * Returns the string "Light".
  18925. * @returns the class name
  18926. */
  18927. Light.prototype.getClassName = function () {
  18928. return "Light";
  18929. };
  18930. /**
  18931. * Converts the light information to a readable string for debug purpose.
  18932. * @param fullDetails Supports for multiple levels of logging within scene loading
  18933. * @returns the human readable light info
  18934. */
  18935. Light.prototype.toString = function (fullDetails) {
  18936. var ret = "Name: " + this.name;
  18937. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18938. if (this.animations) {
  18939. for (var i = 0; i < this.animations.length; i++) {
  18940. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18941. }
  18942. }
  18943. if (fullDetails) {
  18944. }
  18945. return ret;
  18946. };
  18947. /**
  18948. * Set the enabled state of this node.
  18949. * @param value - the new enabled state
  18950. * @see isEnabled
  18951. */
  18952. Light.prototype.setEnabled = function (value) {
  18953. _super.prototype.setEnabled.call(this, value);
  18954. this._resyncMeshes();
  18955. };
  18956. /**
  18957. * Returns the Light associated shadow generator if any.
  18958. * @return the associated shadow generator.
  18959. */
  18960. Light.prototype.getShadowGenerator = function () {
  18961. return this._shadowGenerator;
  18962. };
  18963. /**
  18964. * Returns a Vector3, the absolute light position in the World.
  18965. * @returns the world space position of the light
  18966. */
  18967. Light.prototype.getAbsolutePosition = function () {
  18968. return BABYLON.Vector3.Zero();
  18969. };
  18970. /**
  18971. * Specifies if the light will affect the passed mesh.
  18972. * @param mesh The mesh to test against the light
  18973. * @return true the mesh is affected otherwise, false.
  18974. */
  18975. Light.prototype.canAffectMesh = function (mesh) {
  18976. if (!mesh) {
  18977. return true;
  18978. }
  18979. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18980. return false;
  18981. }
  18982. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18983. return false;
  18984. }
  18985. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18986. return false;
  18987. }
  18988. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18989. return false;
  18990. }
  18991. return true;
  18992. };
  18993. /**
  18994. * Computes and Returns the light World matrix.
  18995. * @returns the world matrix
  18996. */
  18997. Light.prototype.getWorldMatrix = function () {
  18998. this._currentRenderId = this.getScene().getRenderId();
  18999. var worldMatrix = this._getWorldMatrix();
  19000. if (this.parent && this.parent.getWorldMatrix) {
  19001. if (!this._parentedWorldMatrix) {
  19002. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19003. }
  19004. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19005. this._markSyncedWithParent();
  19006. return this._parentedWorldMatrix;
  19007. }
  19008. return worldMatrix;
  19009. };
  19010. /**
  19011. * Sort function to order lights for rendering.
  19012. * @param a First Light object to compare to second.
  19013. * @param b Second Light object to compare first.
  19014. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19015. */
  19016. Light.CompareLightsPriority = function (a, b) {
  19017. //shadow-casting lights have priority over non-shadow-casting lights
  19018. //the renderPrioirty is a secondary sort criterion
  19019. if (a.shadowEnabled !== b.shadowEnabled) {
  19020. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19021. }
  19022. return b.renderPriority - a.renderPriority;
  19023. };
  19024. /**
  19025. * Disposes the light.
  19026. */
  19027. Light.prototype.dispose = function () {
  19028. if (this._shadowGenerator) {
  19029. this._shadowGenerator.dispose();
  19030. this._shadowGenerator = null;
  19031. }
  19032. // Animations
  19033. this.getScene().stopAnimation(this);
  19034. // Remove from meshes
  19035. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19036. var mesh = _a[_i];
  19037. mesh._removeLightSource(this);
  19038. }
  19039. this._uniformBuffer.dispose();
  19040. // Remove from scene
  19041. this.getScene().removeLight(this);
  19042. _super.prototype.dispose.call(this);
  19043. };
  19044. /**
  19045. * Returns the light type ID (integer).
  19046. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19047. */
  19048. Light.prototype.getTypeID = function () {
  19049. return 0;
  19050. };
  19051. /**
  19052. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19053. * @returns the scaled intensity in intensity mode unit
  19054. */
  19055. Light.prototype.getScaledIntensity = function () {
  19056. return this._photometricScale * this.intensity;
  19057. };
  19058. /**
  19059. * Returns a new Light object, named "name", from the current one.
  19060. * @param name The name of the cloned light
  19061. * @returns the new created light
  19062. */
  19063. Light.prototype.clone = function (name) {
  19064. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19065. if (!constructor) {
  19066. return null;
  19067. }
  19068. return BABYLON.SerializationHelper.Clone(constructor, this);
  19069. };
  19070. /**
  19071. * Serializes the current light into a Serialization object.
  19072. * @returns the serialized object.
  19073. */
  19074. Light.prototype.serialize = function () {
  19075. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19076. // Type
  19077. serializationObject.type = this.getTypeID();
  19078. // Parent
  19079. if (this.parent) {
  19080. serializationObject.parentId = this.parent.id;
  19081. }
  19082. // Inclusion / exclusions
  19083. if (this.excludedMeshes.length > 0) {
  19084. serializationObject.excludedMeshesIds = [];
  19085. this.excludedMeshes.forEach(function (mesh) {
  19086. serializationObject.excludedMeshesIds.push(mesh.id);
  19087. });
  19088. }
  19089. if (this.includedOnlyMeshes.length > 0) {
  19090. serializationObject.includedOnlyMeshesIds = [];
  19091. this.includedOnlyMeshes.forEach(function (mesh) {
  19092. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19093. });
  19094. }
  19095. // Animations
  19096. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19097. serializationObject.ranges = this.serializeAnimationRanges();
  19098. return serializationObject;
  19099. };
  19100. /**
  19101. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19102. * This new light is named "name" and added to the passed scene.
  19103. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19104. * @param name The friendly name of the light
  19105. * @param scene The scene the new light will belong to
  19106. * @returns the constructor function
  19107. */
  19108. Light.GetConstructorFromName = function (type, name, scene) {
  19109. switch (type) {
  19110. case 0:
  19111. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19112. case 1:
  19113. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19114. case 2:
  19115. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19116. case 3:
  19117. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19118. }
  19119. return null;
  19120. };
  19121. /**
  19122. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19123. * @param parsedLight The JSON representation of the light
  19124. * @param scene The scene to create the parsed light in
  19125. * @returns the created light after parsing
  19126. */
  19127. Light.Parse = function (parsedLight, scene) {
  19128. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19129. if (!constructor) {
  19130. return null;
  19131. }
  19132. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19133. // Inclusion / exclusions
  19134. if (parsedLight.excludedMeshesIds) {
  19135. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19136. }
  19137. if (parsedLight.includedOnlyMeshesIds) {
  19138. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19139. }
  19140. // Parent
  19141. if (parsedLight.parentId) {
  19142. light._waitingParentId = parsedLight.parentId;
  19143. }
  19144. // Animations
  19145. if (parsedLight.animations) {
  19146. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19147. var parsedAnimation = parsedLight.animations[animationIndex];
  19148. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19149. }
  19150. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19151. }
  19152. if (parsedLight.autoAnimate) {
  19153. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19154. }
  19155. return light;
  19156. };
  19157. Light.prototype._hookArrayForExcluded = function (array) {
  19158. var _this = this;
  19159. var oldPush = array.push;
  19160. array.push = function () {
  19161. var items = [];
  19162. for (var _i = 0; _i < arguments.length; _i++) {
  19163. items[_i] = arguments[_i];
  19164. }
  19165. var result = oldPush.apply(array, items);
  19166. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19167. var item = items_1[_a];
  19168. item._resyncLighSource(_this);
  19169. }
  19170. return result;
  19171. };
  19172. var oldSplice = array.splice;
  19173. array.splice = function (index, deleteCount) {
  19174. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19175. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19176. var item = deleted_1[_i];
  19177. item._resyncLighSource(_this);
  19178. }
  19179. return deleted;
  19180. };
  19181. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19182. var item = array_1[_i];
  19183. item._resyncLighSource(this);
  19184. }
  19185. };
  19186. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19187. var _this = this;
  19188. var oldPush = array.push;
  19189. array.push = function () {
  19190. var items = [];
  19191. for (var _i = 0; _i < arguments.length; _i++) {
  19192. items[_i] = arguments[_i];
  19193. }
  19194. var result = oldPush.apply(array, items);
  19195. _this._resyncMeshes();
  19196. return result;
  19197. };
  19198. var oldSplice = array.splice;
  19199. array.splice = function (index, deleteCount) {
  19200. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19201. _this._resyncMeshes();
  19202. return deleted;
  19203. };
  19204. this._resyncMeshes();
  19205. };
  19206. Light.prototype._resyncMeshes = function () {
  19207. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19208. var mesh = _a[_i];
  19209. mesh._resyncLighSource(this);
  19210. }
  19211. };
  19212. /**
  19213. * Forces the meshes to update their light related information in their rendering used effects
  19214. * @ignore Internal Use Only
  19215. */
  19216. Light.prototype._markMeshesAsLightDirty = function () {
  19217. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19218. var mesh = _a[_i];
  19219. if (mesh._lightSources.indexOf(this) !== -1) {
  19220. mesh._markSubMeshesAsLightDirty();
  19221. }
  19222. }
  19223. };
  19224. /**
  19225. * Recomputes the cached photometric scale if needed.
  19226. */
  19227. Light.prototype._computePhotometricScale = function () {
  19228. this._photometricScale = this._getPhotometricScale();
  19229. this.getScene().resetCachedMaterial();
  19230. };
  19231. /**
  19232. * Returns the Photometric Scale according to the light type and intensity mode.
  19233. */
  19234. Light.prototype._getPhotometricScale = function () {
  19235. var photometricScale = 0.0;
  19236. var lightTypeID = this.getTypeID();
  19237. //get photometric mode
  19238. var photometricMode = this.intensityMode;
  19239. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19240. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19241. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19242. }
  19243. else {
  19244. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19245. }
  19246. }
  19247. //compute photometric scale
  19248. switch (lightTypeID) {
  19249. case Light.LIGHTTYPEID_POINTLIGHT:
  19250. case Light.LIGHTTYPEID_SPOTLIGHT:
  19251. switch (photometricMode) {
  19252. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19253. photometricScale = 1.0 / (4.0 * Math.PI);
  19254. break;
  19255. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19256. photometricScale = 1.0;
  19257. break;
  19258. case Light.INTENSITYMODE_LUMINANCE:
  19259. photometricScale = this.radius * this.radius;
  19260. break;
  19261. }
  19262. break;
  19263. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19264. switch (photometricMode) {
  19265. case Light.INTENSITYMODE_ILLUMINANCE:
  19266. photometricScale = 1.0;
  19267. break;
  19268. case Light.INTENSITYMODE_LUMINANCE:
  19269. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19270. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19271. var apexAngleRadians = this.radius;
  19272. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19273. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19274. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19275. photometricScale = solidAngle;
  19276. break;
  19277. }
  19278. break;
  19279. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19280. // No fall off in hemisperic light.
  19281. photometricScale = 1.0;
  19282. break;
  19283. }
  19284. return photometricScale;
  19285. };
  19286. /**
  19287. * Reorder the light in the scene according to their defined priority.
  19288. * @ignore Internal Use Only
  19289. */
  19290. Light.prototype._reorderLightsInScene = function () {
  19291. var scene = this.getScene();
  19292. if (this._renderPriority != 0) {
  19293. scene.requireLightSorting = true;
  19294. }
  19295. this.getScene().sortLightsByPriority();
  19296. };
  19297. //lightmapMode Consts
  19298. Light._LIGHTMAP_DEFAULT = 0;
  19299. Light._LIGHTMAP_SPECULAR = 1;
  19300. Light._LIGHTMAP_SHADOWSONLY = 2;
  19301. // Intensity Mode Consts
  19302. Light._INTENSITYMODE_AUTOMATIC = 0;
  19303. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19304. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19305. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19306. Light._INTENSITYMODE_LUMINANCE = 4;
  19307. // Light types ids const.
  19308. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19309. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19310. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19311. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19312. __decorate([
  19313. BABYLON.serializeAsColor3()
  19314. ], Light.prototype, "diffuse", void 0);
  19315. __decorate([
  19316. BABYLON.serializeAsColor3()
  19317. ], Light.prototype, "specular", void 0);
  19318. __decorate([
  19319. BABYLON.serialize()
  19320. ], Light.prototype, "intensity", void 0);
  19321. __decorate([
  19322. BABYLON.serialize()
  19323. ], Light.prototype, "range", void 0);
  19324. __decorate([
  19325. BABYLON.serialize()
  19326. ], Light.prototype, "intensityMode", null);
  19327. __decorate([
  19328. BABYLON.serialize()
  19329. ], Light.prototype, "radius", null);
  19330. __decorate([
  19331. BABYLON.serialize()
  19332. ], Light.prototype, "_renderPriority", void 0);
  19333. __decorate([
  19334. BABYLON.expandToProperty("_reorderLightsInScene")
  19335. ], Light.prototype, "renderPriority", void 0);
  19336. __decorate([
  19337. BABYLON.serialize()
  19338. ], Light.prototype, "shadowEnabled", void 0);
  19339. __decorate([
  19340. BABYLON.serialize("excludeWithLayerMask")
  19341. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19342. __decorate([
  19343. BABYLON.serialize("includeOnlyWithLayerMask")
  19344. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19345. __decorate([
  19346. BABYLON.serialize("lightmapMode")
  19347. ], Light.prototype, "_lightmapMode", void 0);
  19348. return Light;
  19349. }(BABYLON.Node));
  19350. BABYLON.Light = Light;
  19351. })(BABYLON || (BABYLON = {}));
  19352. //# sourceMappingURL=babylon.light.js.map
  19353. var BABYLON;
  19354. (function (BABYLON) {
  19355. var Camera = /** @class */ (function (_super) {
  19356. __extends(Camera, _super);
  19357. function Camera(name, position, scene) {
  19358. var _this = _super.call(this, name, scene) || this;
  19359. /**
  19360. * The vector the camera should consider as up.
  19361. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19362. */
  19363. _this.upVector = BABYLON.Vector3.Up();
  19364. _this.orthoLeft = null;
  19365. _this.orthoRight = null;
  19366. _this.orthoBottom = null;
  19367. _this.orthoTop = null;
  19368. /**
  19369. * FOV is set in Radians. (default is 0.8)
  19370. */
  19371. _this.fov = 0.8;
  19372. _this.minZ = 1;
  19373. _this.maxZ = 10000.0;
  19374. _this.inertia = 0.9;
  19375. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19376. _this.isIntermediate = false;
  19377. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19378. /**
  19379. * Restricts the camera to viewing objects with the same layerMask.
  19380. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19381. */
  19382. _this.layerMask = 0x0FFFFFFF;
  19383. /**
  19384. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19385. */
  19386. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19387. // Camera rig members
  19388. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19389. _this._rigCameras = new Array();
  19390. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19391. _this._skipRendering = false;
  19392. _this.customRenderTargets = new Array();
  19393. // Observables
  19394. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19395. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19396. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19397. _this.onRestoreStateObservable = new BABYLON.Observable();
  19398. // Cache
  19399. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19400. _this._projectionMatrix = new BABYLON.Matrix();
  19401. _this._doNotComputeProjectionMatrix = false;
  19402. _this._postProcesses = new Array();
  19403. _this._transformMatrix = BABYLON.Matrix.Zero();
  19404. _this._activeMeshes = new BABYLON.SmartArray(256);
  19405. _this._globalPosition = BABYLON.Vector3.Zero();
  19406. _this._refreshFrustumPlanes = true;
  19407. _this.getScene().addCamera(_this);
  19408. if (!_this.getScene().activeCamera) {
  19409. _this.getScene().activeCamera = _this;
  19410. }
  19411. _this.position = position;
  19412. return _this;
  19413. }
  19414. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19415. get: function () {
  19416. return Camera._PERSPECTIVE_CAMERA;
  19417. },
  19418. enumerable: true,
  19419. configurable: true
  19420. });
  19421. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19422. get: function () {
  19423. return Camera._ORTHOGRAPHIC_CAMERA;
  19424. },
  19425. enumerable: true,
  19426. configurable: true
  19427. });
  19428. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19429. /**
  19430. * This is the default FOV mode for perspective cameras.
  19431. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19432. *
  19433. */
  19434. get: function () {
  19435. return Camera._FOVMODE_VERTICAL_FIXED;
  19436. },
  19437. enumerable: true,
  19438. configurable: true
  19439. });
  19440. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19441. /**
  19442. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19443. *
  19444. */
  19445. get: function () {
  19446. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19447. },
  19448. enumerable: true,
  19449. configurable: true
  19450. });
  19451. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19452. get: function () {
  19453. return Camera._RIG_MODE_NONE;
  19454. },
  19455. enumerable: true,
  19456. configurable: true
  19457. });
  19458. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19459. get: function () {
  19460. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19461. },
  19462. enumerable: true,
  19463. configurable: true
  19464. });
  19465. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19466. get: function () {
  19467. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19468. },
  19469. enumerable: true,
  19470. configurable: true
  19471. });
  19472. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19473. get: function () {
  19474. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19475. },
  19476. enumerable: true,
  19477. configurable: true
  19478. });
  19479. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19480. get: function () {
  19481. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19487. get: function () {
  19488. return Camera._RIG_MODE_VR;
  19489. },
  19490. enumerable: true,
  19491. configurable: true
  19492. });
  19493. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19494. get: function () {
  19495. return Camera._RIG_MODE_WEBVR;
  19496. },
  19497. enumerable: true,
  19498. configurable: true
  19499. });
  19500. /**
  19501. * Store current camera state (fov, position, etc..)
  19502. */
  19503. Camera.prototype.storeState = function () {
  19504. this._stateStored = true;
  19505. this._storedFov = this.fov;
  19506. return this;
  19507. };
  19508. /**
  19509. * Restores the camera state values if it has been stored. You must call storeState() first
  19510. */
  19511. Camera.prototype._restoreStateValues = function () {
  19512. if (!this._stateStored) {
  19513. return false;
  19514. }
  19515. this.fov = this._storedFov;
  19516. return true;
  19517. };
  19518. /**
  19519. * Restored camera state. You must call storeState() first
  19520. */
  19521. Camera.prototype.restoreState = function () {
  19522. if (this._restoreStateValues()) {
  19523. this.onRestoreStateObservable.notifyObservers(this);
  19524. return true;
  19525. }
  19526. return false;
  19527. };
  19528. Camera.prototype.getClassName = function () {
  19529. return "Camera";
  19530. };
  19531. /**
  19532. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19533. */
  19534. Camera.prototype.toString = function (fullDetails) {
  19535. var ret = "Name: " + this.name;
  19536. ret += ", type: " + this.getClassName();
  19537. if (this.animations) {
  19538. for (var i = 0; i < this.animations.length; i++) {
  19539. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19540. }
  19541. }
  19542. if (fullDetails) {
  19543. }
  19544. return ret;
  19545. };
  19546. Object.defineProperty(Camera.prototype, "globalPosition", {
  19547. get: function () {
  19548. return this._globalPosition;
  19549. },
  19550. enumerable: true,
  19551. configurable: true
  19552. });
  19553. Camera.prototype.getActiveMeshes = function () {
  19554. return this._activeMeshes;
  19555. };
  19556. Camera.prototype.isActiveMesh = function (mesh) {
  19557. return (this._activeMeshes.indexOf(mesh) !== -1);
  19558. };
  19559. //Cache
  19560. Camera.prototype._initCache = function () {
  19561. _super.prototype._initCache.call(this);
  19562. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19563. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19564. this._cache.mode = undefined;
  19565. this._cache.minZ = undefined;
  19566. this._cache.maxZ = undefined;
  19567. this._cache.fov = undefined;
  19568. this._cache.fovMode = undefined;
  19569. this._cache.aspectRatio = undefined;
  19570. this._cache.orthoLeft = undefined;
  19571. this._cache.orthoRight = undefined;
  19572. this._cache.orthoBottom = undefined;
  19573. this._cache.orthoTop = undefined;
  19574. this._cache.renderWidth = undefined;
  19575. this._cache.renderHeight = undefined;
  19576. };
  19577. Camera.prototype._updateCache = function (ignoreParentClass) {
  19578. if (!ignoreParentClass) {
  19579. _super.prototype._updateCache.call(this);
  19580. }
  19581. this._cache.position.copyFrom(this.position);
  19582. this._cache.upVector.copyFrom(this.upVector);
  19583. };
  19584. // Synchronized
  19585. Camera.prototype._isSynchronized = function () {
  19586. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19587. };
  19588. Camera.prototype._isSynchronizedViewMatrix = function () {
  19589. if (!_super.prototype._isSynchronized.call(this))
  19590. return false;
  19591. return this._cache.position.equals(this.position)
  19592. && this._cache.upVector.equals(this.upVector)
  19593. && this.isSynchronizedWithParent();
  19594. };
  19595. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19596. var check = this._cache.mode === this.mode
  19597. && this._cache.minZ === this.minZ
  19598. && this._cache.maxZ === this.maxZ;
  19599. if (!check) {
  19600. return false;
  19601. }
  19602. var engine = this.getEngine();
  19603. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19604. check = this._cache.fov === this.fov
  19605. && this._cache.fovMode === this.fovMode
  19606. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19607. }
  19608. else {
  19609. check = this._cache.orthoLeft === this.orthoLeft
  19610. && this._cache.orthoRight === this.orthoRight
  19611. && this._cache.orthoBottom === this.orthoBottom
  19612. && this._cache.orthoTop === this.orthoTop
  19613. && this._cache.renderWidth === engine.getRenderWidth()
  19614. && this._cache.renderHeight === engine.getRenderHeight();
  19615. }
  19616. return check;
  19617. };
  19618. // Controls
  19619. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19620. };
  19621. Camera.prototype.detachControl = function (element) {
  19622. };
  19623. Camera.prototype.update = function () {
  19624. this._checkInputs();
  19625. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19626. this._updateRigCameras();
  19627. }
  19628. };
  19629. Camera.prototype._checkInputs = function () {
  19630. this.onAfterCheckInputsObservable.notifyObservers(this);
  19631. };
  19632. Object.defineProperty(Camera.prototype, "rigCameras", {
  19633. get: function () {
  19634. return this._rigCameras;
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19640. get: function () {
  19641. return this._rigPostProcess;
  19642. },
  19643. enumerable: true,
  19644. configurable: true
  19645. });
  19646. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19647. // invalidate framebuffer
  19648. if (this._postProcesses.length > 0) {
  19649. this._postProcesses[0].markTextureDirty();
  19650. }
  19651. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19652. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19653. var cam = this._rigCameras[i];
  19654. var rigPostProcess = cam._rigPostProcess;
  19655. // for VR rig, there does not have to be a post process
  19656. if (rigPostProcess) {
  19657. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19658. if (isPass) {
  19659. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19660. cam.isIntermediate = this._postProcesses.length === 0;
  19661. }
  19662. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19663. rigPostProcess.markTextureDirty();
  19664. }
  19665. else {
  19666. cam._postProcesses = this._postProcesses.slice(0);
  19667. }
  19668. }
  19669. };
  19670. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19671. if (insertAt === void 0) { insertAt = null; }
  19672. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19673. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19674. return 0;
  19675. }
  19676. if (insertAt == null || insertAt < 0) {
  19677. this._postProcesses.push(postProcess);
  19678. }
  19679. else {
  19680. this._postProcesses.splice(insertAt, 0, postProcess);
  19681. }
  19682. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19683. return this._postProcesses.indexOf(postProcess);
  19684. };
  19685. Camera.prototype.detachPostProcess = function (postProcess) {
  19686. var idx = this._postProcesses.indexOf(postProcess);
  19687. if (idx !== -1) {
  19688. this._postProcesses.splice(idx, 1);
  19689. }
  19690. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19691. };
  19692. Camera.prototype.getWorldMatrix = function () {
  19693. if (!this._worldMatrix) {
  19694. this._worldMatrix = BABYLON.Matrix.Identity();
  19695. }
  19696. var viewMatrix = this.getViewMatrix();
  19697. viewMatrix.invertToRef(this._worldMatrix);
  19698. return this._worldMatrix;
  19699. };
  19700. Camera.prototype._getViewMatrix = function () {
  19701. return BABYLON.Matrix.Identity();
  19702. };
  19703. Camera.prototype.getViewMatrix = function (force) {
  19704. if (!force && this._isSynchronizedViewMatrix()) {
  19705. return this._computedViewMatrix;
  19706. }
  19707. this.updateCache();
  19708. this._computedViewMatrix = this._getViewMatrix();
  19709. this._currentRenderId = this.getScene().getRenderId();
  19710. this._refreshFrustumPlanes = true;
  19711. if (!this.parent || !this.parent.getWorldMatrix) {
  19712. this._globalPosition.copyFrom(this.position);
  19713. }
  19714. else {
  19715. if (!this._worldMatrix) {
  19716. this._worldMatrix = BABYLON.Matrix.Identity();
  19717. }
  19718. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19719. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19720. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19721. this._computedViewMatrix.invert();
  19722. this._markSyncedWithParent();
  19723. }
  19724. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19725. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19726. }
  19727. this.onViewMatrixChangedObservable.notifyObservers(this);
  19728. return this._computedViewMatrix;
  19729. };
  19730. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19731. this._doNotComputeProjectionMatrix = true;
  19732. if (projection !== undefined) {
  19733. this._projectionMatrix = projection;
  19734. }
  19735. };
  19736. ;
  19737. Camera.prototype.unfreezeProjectionMatrix = function () {
  19738. this._doNotComputeProjectionMatrix = false;
  19739. };
  19740. ;
  19741. Camera.prototype.getProjectionMatrix = function (force) {
  19742. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19743. return this._projectionMatrix;
  19744. }
  19745. // Cache
  19746. this._cache.mode = this.mode;
  19747. this._cache.minZ = this.minZ;
  19748. this._cache.maxZ = this.maxZ;
  19749. // Matrix
  19750. this._refreshFrustumPlanes = true;
  19751. var engine = this.getEngine();
  19752. var scene = this.getScene();
  19753. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19754. this._cache.fov = this.fov;
  19755. this._cache.fovMode = this.fovMode;
  19756. this._cache.aspectRatio = engine.getAspectRatio(this);
  19757. if (this.minZ <= 0) {
  19758. this.minZ = 0.1;
  19759. }
  19760. if (scene.useRightHandedSystem) {
  19761. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19762. }
  19763. else {
  19764. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19765. }
  19766. }
  19767. else {
  19768. var halfWidth = engine.getRenderWidth() / 2.0;
  19769. var halfHeight = engine.getRenderHeight() / 2.0;
  19770. if (scene.useRightHandedSystem) {
  19771. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19772. }
  19773. else {
  19774. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19775. }
  19776. this._cache.orthoLeft = this.orthoLeft;
  19777. this._cache.orthoRight = this.orthoRight;
  19778. this._cache.orthoBottom = this.orthoBottom;
  19779. this._cache.orthoTop = this.orthoTop;
  19780. this._cache.renderWidth = engine.getRenderWidth();
  19781. this._cache.renderHeight = engine.getRenderHeight();
  19782. }
  19783. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19784. return this._projectionMatrix;
  19785. };
  19786. Camera.prototype.getTranformationMatrix = function () {
  19787. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19788. return this._transformMatrix;
  19789. };
  19790. Camera.prototype.updateFrustumPlanes = function () {
  19791. if (!this._refreshFrustumPlanes) {
  19792. return;
  19793. }
  19794. this.getTranformationMatrix();
  19795. if (!this._frustumPlanes) {
  19796. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19797. }
  19798. else {
  19799. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19800. }
  19801. this._refreshFrustumPlanes = false;
  19802. };
  19803. Camera.prototype.isInFrustum = function (target) {
  19804. this.updateFrustumPlanes();
  19805. return target.isInFrustum(this._frustumPlanes);
  19806. };
  19807. Camera.prototype.isCompletelyInFrustum = function (target) {
  19808. this.updateFrustumPlanes();
  19809. return target.isCompletelyInFrustum(this._frustumPlanes);
  19810. };
  19811. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19812. if (length === void 0) { length = 100; }
  19813. if (!transform) {
  19814. transform = this.getWorldMatrix();
  19815. }
  19816. if (!origin) {
  19817. origin = this.position;
  19818. }
  19819. var forward = new BABYLON.Vector3(0, 0, 1);
  19820. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19821. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19822. return new BABYLON.Ray(origin, direction, length);
  19823. };
  19824. Camera.prototype.dispose = function () {
  19825. // Observables
  19826. this.onViewMatrixChangedObservable.clear();
  19827. this.onProjectionMatrixChangedObservable.clear();
  19828. this.onAfterCheckInputsObservable.clear();
  19829. this.onRestoreStateObservable.clear();
  19830. // Inputs
  19831. if (this.inputs) {
  19832. this.inputs.clear();
  19833. }
  19834. // Animations
  19835. this.getScene().stopAnimation(this);
  19836. // Remove from scene
  19837. this.getScene().removeCamera(this);
  19838. while (this._rigCameras.length > 0) {
  19839. var camera = this._rigCameras.pop();
  19840. if (camera) {
  19841. camera.dispose();
  19842. }
  19843. }
  19844. // Postprocesses
  19845. if (this._rigPostProcess) {
  19846. this._rigPostProcess.dispose(this);
  19847. this._rigPostProcess = null;
  19848. this._postProcesses = [];
  19849. }
  19850. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19851. this._rigPostProcess = null;
  19852. this._postProcesses = [];
  19853. }
  19854. else {
  19855. var i = this._postProcesses.length;
  19856. while (--i >= 0) {
  19857. this._postProcesses[i].dispose(this);
  19858. }
  19859. }
  19860. // Render targets
  19861. var i = this.customRenderTargets.length;
  19862. while (--i >= 0) {
  19863. this.customRenderTargets[i].dispose();
  19864. }
  19865. this.customRenderTargets = [];
  19866. // Active Meshes
  19867. this._activeMeshes.dispose();
  19868. _super.prototype.dispose.call(this);
  19869. };
  19870. Object.defineProperty(Camera.prototype, "leftCamera", {
  19871. // ---- Camera rigs section ----
  19872. get: function () {
  19873. if (this._rigCameras.length < 1) {
  19874. return null;
  19875. }
  19876. return this._rigCameras[0];
  19877. },
  19878. enumerable: true,
  19879. configurable: true
  19880. });
  19881. Object.defineProperty(Camera.prototype, "rightCamera", {
  19882. get: function () {
  19883. if (this._rigCameras.length < 2) {
  19884. return null;
  19885. }
  19886. return this._rigCameras[1];
  19887. },
  19888. enumerable: true,
  19889. configurable: true
  19890. });
  19891. Camera.prototype.getLeftTarget = function () {
  19892. if (this._rigCameras.length < 1) {
  19893. return null;
  19894. }
  19895. return this._rigCameras[0].getTarget();
  19896. };
  19897. Camera.prototype.getRightTarget = function () {
  19898. if (this._rigCameras.length < 2) {
  19899. return null;
  19900. }
  19901. return this._rigCameras[1].getTarget();
  19902. };
  19903. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19904. if (this.cameraRigMode === mode) {
  19905. return;
  19906. }
  19907. while (this._rigCameras.length > 0) {
  19908. var camera = this._rigCameras.pop();
  19909. if (camera) {
  19910. camera.dispose();
  19911. }
  19912. }
  19913. this.cameraRigMode = mode;
  19914. this._cameraRigParams = {};
  19915. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19916. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19917. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19918. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19919. // create the rig cameras, unless none
  19920. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19921. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19922. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19923. if (leftCamera && rightCamera) {
  19924. this._rigCameras.push(leftCamera);
  19925. this._rigCameras.push(rightCamera);
  19926. }
  19927. }
  19928. switch (this.cameraRigMode) {
  19929. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19930. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19931. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19932. break;
  19933. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19934. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19935. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19936. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19937. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19938. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19939. break;
  19940. case Camera.RIG_MODE_VR:
  19941. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19942. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19943. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19944. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19945. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19946. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19947. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19948. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19949. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19950. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19951. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19952. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19953. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19954. if (metrics.compensateDistortion) {
  19955. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19956. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19957. }
  19958. break;
  19959. case Camera.RIG_MODE_WEBVR:
  19960. if (rigParams.vrDisplay) {
  19961. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19962. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19963. //Left eye
  19964. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19965. this._rigCameras[0].setCameraRigParameter("left", true);
  19966. //leaving this for future reference
  19967. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19968. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19969. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19970. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19971. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19972. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19973. this._rigCameras[0].parent = this;
  19974. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19975. //Right eye
  19976. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19977. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19978. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19979. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19980. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19981. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19982. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19983. this._rigCameras[1].parent = this;
  19984. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19985. if (Camera.UseAlternateWebVRRendering) {
  19986. this._rigCameras[1]._skipRendering = true;
  19987. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19988. }
  19989. }
  19990. break;
  19991. }
  19992. this._cascadePostProcessesToRigCams();
  19993. this.update();
  19994. };
  19995. Camera.prototype._getVRProjectionMatrix = function () {
  19996. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  19997. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  19998. return this._projectionMatrix;
  19999. };
  20000. Camera.prototype._updateCameraRotationMatrix = function () {
  20001. //Here for WebVR
  20002. };
  20003. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20004. //Here for WebVR
  20005. };
  20006. /**
  20007. * This function MUST be overwritten by the different WebVR cameras available.
  20008. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20009. */
  20010. Camera.prototype._getWebVRProjectionMatrix = function () {
  20011. return BABYLON.Matrix.Identity();
  20012. };
  20013. /**
  20014. * This function MUST be overwritten by the different WebVR cameras available.
  20015. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20016. */
  20017. Camera.prototype._getWebVRViewMatrix = function () {
  20018. return BABYLON.Matrix.Identity();
  20019. };
  20020. Camera.prototype.setCameraRigParameter = function (name, value) {
  20021. if (!this._cameraRigParams) {
  20022. this._cameraRigParams = {};
  20023. }
  20024. this._cameraRigParams[name] = value;
  20025. //provisionnally:
  20026. if (name === "interaxialDistance") {
  20027. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20028. }
  20029. };
  20030. /**
  20031. * needs to be overridden by children so sub has required properties to be copied
  20032. */
  20033. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20034. return null;
  20035. };
  20036. /**
  20037. * May need to be overridden by children
  20038. */
  20039. Camera.prototype._updateRigCameras = function () {
  20040. for (var i = 0; i < this._rigCameras.length; i++) {
  20041. this._rigCameras[i].minZ = this.minZ;
  20042. this._rigCameras[i].maxZ = this.maxZ;
  20043. this._rigCameras[i].fov = this.fov;
  20044. }
  20045. // only update viewport when ANAGLYPH
  20046. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20047. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20048. }
  20049. };
  20050. Camera.prototype._setupInputs = function () {
  20051. };
  20052. Camera.prototype.serialize = function () {
  20053. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20054. // Type
  20055. serializationObject.type = this.getClassName();
  20056. // Parent
  20057. if (this.parent) {
  20058. serializationObject.parentId = this.parent.id;
  20059. }
  20060. if (this.inputs) {
  20061. this.inputs.serialize(serializationObject);
  20062. }
  20063. // Animations
  20064. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20065. serializationObject.ranges = this.serializeAnimationRanges();
  20066. return serializationObject;
  20067. };
  20068. Camera.prototype.clone = function (name) {
  20069. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20070. };
  20071. Camera.prototype.getDirection = function (localAxis) {
  20072. var result = BABYLON.Vector3.Zero();
  20073. this.getDirectionToRef(localAxis, result);
  20074. return result;
  20075. };
  20076. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20077. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20078. };
  20079. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20080. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20081. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20082. switch (type) {
  20083. case "ArcRotateCamera":
  20084. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20085. case "DeviceOrientationCamera":
  20086. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20087. case "FollowCamera":
  20088. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20089. case "ArcFollowCamera":
  20090. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20091. case "GamepadCamera":
  20092. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20093. case "TouchCamera":
  20094. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20095. case "VirtualJoysticksCamera":
  20096. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20097. case "WebVRFreeCamera":
  20098. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20099. case "WebVRGamepadCamera":
  20100. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20101. case "VRDeviceOrientationFreeCamera":
  20102. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20103. case "VRDeviceOrientationGamepadCamera":
  20104. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20105. case "AnaglyphArcRotateCamera":
  20106. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20107. case "AnaglyphFreeCamera":
  20108. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20109. case "AnaglyphGamepadCamera":
  20110. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20111. case "AnaglyphUniversalCamera":
  20112. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20113. case "StereoscopicArcRotateCamera":
  20114. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20115. case "StereoscopicFreeCamera":
  20116. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20117. case "StereoscopicGamepadCamera":
  20118. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20119. case "StereoscopicUniversalCamera":
  20120. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20121. case "FreeCamera":// Forcing Universal here
  20122. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20123. default:// Universal Camera is the default value
  20124. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20125. }
  20126. };
  20127. Camera.prototype.computeWorldMatrix = function () {
  20128. return this.getWorldMatrix();
  20129. };
  20130. Camera.Parse = function (parsedCamera, scene) {
  20131. var type = parsedCamera.type;
  20132. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20133. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20134. // Parent
  20135. if (parsedCamera.parentId) {
  20136. camera._waitingParentId = parsedCamera.parentId;
  20137. }
  20138. //If camera has an input manager, let it parse inputs settings
  20139. if (camera.inputs) {
  20140. camera.inputs.parse(parsedCamera);
  20141. camera._setupInputs();
  20142. }
  20143. if (camera.setPosition) {
  20144. camera.position.copyFromFloats(0, 0, 0);
  20145. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20146. }
  20147. // Target
  20148. if (parsedCamera.target) {
  20149. if (camera.setTarget) {
  20150. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20151. }
  20152. }
  20153. // Apply 3d rig, when found
  20154. if (parsedCamera.cameraRigMode) {
  20155. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20156. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20157. }
  20158. // Animations
  20159. if (parsedCamera.animations) {
  20160. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20161. var parsedAnimation = parsedCamera.animations[animationIndex];
  20162. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20163. }
  20164. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20165. }
  20166. if (parsedCamera.autoAnimate) {
  20167. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20168. }
  20169. return camera;
  20170. };
  20171. // Statics
  20172. Camera._PERSPECTIVE_CAMERA = 0;
  20173. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20174. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20175. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20176. Camera._RIG_MODE_NONE = 0;
  20177. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20178. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20179. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20180. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20181. Camera._RIG_MODE_VR = 20;
  20182. Camera._RIG_MODE_WEBVR = 21;
  20183. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20184. Camera.UseAlternateWebVRRendering = false;
  20185. __decorate([
  20186. BABYLON.serializeAsVector3()
  20187. ], Camera.prototype, "position", void 0);
  20188. __decorate([
  20189. BABYLON.serializeAsVector3()
  20190. ], Camera.prototype, "upVector", void 0);
  20191. __decorate([
  20192. BABYLON.serialize()
  20193. ], Camera.prototype, "orthoLeft", void 0);
  20194. __decorate([
  20195. BABYLON.serialize()
  20196. ], Camera.prototype, "orthoRight", void 0);
  20197. __decorate([
  20198. BABYLON.serialize()
  20199. ], Camera.prototype, "orthoBottom", void 0);
  20200. __decorate([
  20201. BABYLON.serialize()
  20202. ], Camera.prototype, "orthoTop", void 0);
  20203. __decorate([
  20204. BABYLON.serialize()
  20205. ], Camera.prototype, "fov", void 0);
  20206. __decorate([
  20207. BABYLON.serialize()
  20208. ], Camera.prototype, "minZ", void 0);
  20209. __decorate([
  20210. BABYLON.serialize()
  20211. ], Camera.prototype, "maxZ", void 0);
  20212. __decorate([
  20213. BABYLON.serialize()
  20214. ], Camera.prototype, "inertia", void 0);
  20215. __decorate([
  20216. BABYLON.serialize()
  20217. ], Camera.prototype, "mode", void 0);
  20218. __decorate([
  20219. BABYLON.serialize()
  20220. ], Camera.prototype, "layerMask", void 0);
  20221. __decorate([
  20222. BABYLON.serialize()
  20223. ], Camera.prototype, "fovMode", void 0);
  20224. __decorate([
  20225. BABYLON.serialize()
  20226. ], Camera.prototype, "cameraRigMode", void 0);
  20227. __decorate([
  20228. BABYLON.serialize()
  20229. ], Camera.prototype, "interaxialDistance", void 0);
  20230. __decorate([
  20231. BABYLON.serialize()
  20232. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20233. return Camera;
  20234. }(BABYLON.Node));
  20235. BABYLON.Camera = Camera;
  20236. })(BABYLON || (BABYLON = {}));
  20237. //# sourceMappingURL=babylon.camera.js.map
  20238. var BABYLON;
  20239. (function (BABYLON) {
  20240. var RenderingManager = /** @class */ (function () {
  20241. function RenderingManager(scene) {
  20242. this._renderingGroups = new Array();
  20243. this._autoClearDepthStencil = {};
  20244. this._customOpaqueSortCompareFn = {};
  20245. this._customAlphaTestSortCompareFn = {};
  20246. this._customTransparentSortCompareFn = {};
  20247. this._renderinGroupInfo = null;
  20248. this._scene = scene;
  20249. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20250. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20251. }
  20252. }
  20253. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20254. if (depth === void 0) { depth = true; }
  20255. if (stencil === void 0) { stencil = true; }
  20256. if (this._depthStencilBufferAlreadyCleaned) {
  20257. return;
  20258. }
  20259. this._scene.getEngine().clear(null, false, depth, stencil);
  20260. this._depthStencilBufferAlreadyCleaned = true;
  20261. };
  20262. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20263. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20264. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20265. var info = null;
  20266. if (observable) {
  20267. if (!this._renderinGroupInfo) {
  20268. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20269. }
  20270. info = this._renderinGroupInfo;
  20271. info.scene = this._scene;
  20272. info.camera = this._scene.activeCamera;
  20273. }
  20274. // Dispatch sprites
  20275. if (renderSprites) {
  20276. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20277. var manager = this._scene.spriteManagers[index];
  20278. this.dispatchSprites(manager);
  20279. }
  20280. }
  20281. // Render
  20282. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20283. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20284. var renderingGroup = this._renderingGroups[index];
  20285. if (!renderingGroup && !observable)
  20286. continue;
  20287. var renderingGroupMask = 0;
  20288. // Fire PRECLEAR stage
  20289. if (observable && info) {
  20290. renderingGroupMask = Math.pow(2, index);
  20291. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20292. info.renderingGroupId = index;
  20293. observable.notifyObservers(info, renderingGroupMask);
  20294. }
  20295. // Clear depth/stencil if needed
  20296. if (RenderingManager.AUTOCLEAR) {
  20297. var autoClear = this._autoClearDepthStencil[index];
  20298. if (autoClear && autoClear.autoClear) {
  20299. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20300. }
  20301. }
  20302. if (observable && info) {
  20303. // Fire PREOPAQUE stage
  20304. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20305. observable.notifyObservers(info, renderingGroupMask);
  20306. // Fire PRETRANSPARENT stage
  20307. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20308. observable.notifyObservers(info, renderingGroupMask);
  20309. }
  20310. if (renderingGroup)
  20311. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20312. // Fire POSTTRANSPARENT stage
  20313. if (observable && info) {
  20314. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20315. observable.notifyObservers(info, renderingGroupMask);
  20316. }
  20317. }
  20318. };
  20319. RenderingManager.prototype.reset = function () {
  20320. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20321. var renderingGroup = this._renderingGroups[index];
  20322. if (renderingGroup) {
  20323. renderingGroup.prepare();
  20324. }
  20325. }
  20326. };
  20327. RenderingManager.prototype.dispose = function () {
  20328. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20329. var renderingGroup = this._renderingGroups[index];
  20330. if (renderingGroup) {
  20331. renderingGroup.dispose();
  20332. }
  20333. }
  20334. this._renderingGroups.length = 0;
  20335. };
  20336. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20337. if (this._renderingGroups[renderingGroupId] === undefined) {
  20338. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20339. }
  20340. };
  20341. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20342. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20343. this._prepareRenderingGroup(renderingGroupId);
  20344. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20345. };
  20346. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20347. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20348. this._prepareRenderingGroup(renderingGroupId);
  20349. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20350. };
  20351. /**
  20352. * @param subMesh The submesh to dispatch
  20353. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20354. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20355. */
  20356. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20357. if (mesh === undefined) {
  20358. mesh = subMesh.getMesh();
  20359. }
  20360. var renderingGroupId = mesh.renderingGroupId || 0;
  20361. this._prepareRenderingGroup(renderingGroupId);
  20362. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20363. };
  20364. /**
  20365. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20366. * This allowed control for front to back rendering or reversly depending of the special needs.
  20367. *
  20368. * @param renderingGroupId The rendering group id corresponding to its index
  20369. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20370. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20371. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20372. */
  20373. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20374. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20375. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20376. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20377. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20378. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20379. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20380. if (this._renderingGroups[renderingGroupId]) {
  20381. var group = this._renderingGroups[renderingGroupId];
  20382. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20383. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20384. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20385. }
  20386. };
  20387. /**
  20388. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20389. *
  20390. * @param renderingGroupId The rendering group id corresponding to its index
  20391. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20392. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20393. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20394. */
  20395. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20396. if (depth === void 0) { depth = true; }
  20397. if (stencil === void 0) { stencil = true; }
  20398. this._autoClearDepthStencil[renderingGroupId] = {
  20399. autoClear: autoClearDepthStencil,
  20400. depth: depth,
  20401. stencil: stencil
  20402. };
  20403. };
  20404. /**
  20405. * The max id used for rendering groups (not included)
  20406. */
  20407. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20408. /**
  20409. * The min id used for rendering groups (included)
  20410. */
  20411. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20412. /**
  20413. * Used to globally prevent autoclearing scenes.
  20414. */
  20415. RenderingManager.AUTOCLEAR = true;
  20416. return RenderingManager;
  20417. }());
  20418. BABYLON.RenderingManager = RenderingManager;
  20419. })(BABYLON || (BABYLON = {}));
  20420. //# sourceMappingURL=babylon.renderingManager.js.map
  20421. var BABYLON;
  20422. (function (BABYLON) {
  20423. var RenderingGroup = /** @class */ (function () {
  20424. /**
  20425. * Creates a new rendering group.
  20426. * @param index The rendering group index
  20427. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20428. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20429. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20430. */
  20431. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20432. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20433. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20434. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20435. this.index = index;
  20436. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20437. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20438. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20439. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20440. this._particleSystems = new BABYLON.SmartArray(256);
  20441. this._spriteManagers = new BABYLON.SmartArray(256);
  20442. this._edgesRenderers = new BABYLON.SmartArray(16);
  20443. this._scene = scene;
  20444. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20445. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20446. this.transparentSortCompareFn = transparentSortCompareFn;
  20447. }
  20448. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20449. /**
  20450. * Set the opaque sort comparison function.
  20451. * If null the sub meshes will be render in the order they were created
  20452. */
  20453. set: function (value) {
  20454. this._opaqueSortCompareFn = value;
  20455. if (value) {
  20456. this._renderOpaque = this.renderOpaqueSorted;
  20457. }
  20458. else {
  20459. this._renderOpaque = RenderingGroup.renderUnsorted;
  20460. }
  20461. },
  20462. enumerable: true,
  20463. configurable: true
  20464. });
  20465. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20466. /**
  20467. * Set the alpha test sort comparison function.
  20468. * If null the sub meshes will be render in the order they were created
  20469. */
  20470. set: function (value) {
  20471. this._alphaTestSortCompareFn = value;
  20472. if (value) {
  20473. this._renderAlphaTest = this.renderAlphaTestSorted;
  20474. }
  20475. else {
  20476. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20477. }
  20478. },
  20479. enumerable: true,
  20480. configurable: true
  20481. });
  20482. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20483. /**
  20484. * Set the transparent sort comparison function.
  20485. * If null the sub meshes will be render in the order they were created
  20486. */
  20487. set: function (value) {
  20488. if (value) {
  20489. this._transparentSortCompareFn = value;
  20490. }
  20491. else {
  20492. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20493. }
  20494. this._renderTransparent = this.renderTransparentSorted;
  20495. },
  20496. enumerable: true,
  20497. configurable: true
  20498. });
  20499. /**
  20500. * Render all the sub meshes contained in the group.
  20501. * @param customRenderFunction Used to override the default render behaviour of the group.
  20502. * @returns true if rendered some submeshes.
  20503. */
  20504. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20505. if (customRenderFunction) {
  20506. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20507. return;
  20508. }
  20509. var engine = this._scene.getEngine();
  20510. // Depth only
  20511. if (this._depthOnlySubMeshes.length !== 0) {
  20512. engine.setColorWrite(false);
  20513. this._renderAlphaTest(this._depthOnlySubMeshes);
  20514. engine.setColorWrite(true);
  20515. }
  20516. // Opaque
  20517. if (this._opaqueSubMeshes.length !== 0) {
  20518. this._renderOpaque(this._opaqueSubMeshes);
  20519. }
  20520. // Alpha test
  20521. if (this._alphaTestSubMeshes.length !== 0) {
  20522. this._renderAlphaTest(this._alphaTestSubMeshes);
  20523. }
  20524. var stencilState = engine.getStencilBuffer();
  20525. engine.setStencilBuffer(false);
  20526. // Sprites
  20527. if (renderSprites) {
  20528. this._renderSprites();
  20529. }
  20530. // Particles
  20531. if (renderParticles) {
  20532. this._renderParticles(activeMeshes);
  20533. }
  20534. if (this.onBeforeTransparentRendering) {
  20535. this.onBeforeTransparentRendering();
  20536. }
  20537. // Transparent
  20538. if (this._transparentSubMeshes.length !== 0) {
  20539. this._renderTransparent(this._transparentSubMeshes);
  20540. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20541. }
  20542. // Set back stencil to false in case it changes before the edge renderer.
  20543. engine.setStencilBuffer(false);
  20544. // Edges
  20545. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20546. this._edgesRenderers.data[edgesRendererIndex].render();
  20547. }
  20548. // Restore Stencil state.
  20549. engine.setStencilBuffer(stencilState);
  20550. };
  20551. /**
  20552. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20553. * @param subMeshes The submeshes to render
  20554. */
  20555. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20556. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20557. };
  20558. /**
  20559. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20560. * @param subMeshes The submeshes to render
  20561. */
  20562. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20563. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20564. };
  20565. /**
  20566. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20567. * @param subMeshes The submeshes to render
  20568. */
  20569. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20570. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20571. };
  20572. /**
  20573. * Renders the submeshes in a specified order.
  20574. * @param subMeshes The submeshes to sort before render
  20575. * @param sortCompareFn The comparison function use to sort
  20576. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20577. * @param transparent Specifies to activate blending if true
  20578. */
  20579. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20580. var subIndex = 0;
  20581. var subMesh;
  20582. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20583. for (; subIndex < subMeshes.length; subIndex++) {
  20584. subMesh = subMeshes.data[subIndex];
  20585. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20586. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20587. }
  20588. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20589. if (sortCompareFn) {
  20590. sortedArray.sort(sortCompareFn);
  20591. }
  20592. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20593. subMesh = sortedArray[subIndex];
  20594. if (transparent) {
  20595. var material = subMesh.getMaterial();
  20596. if (material && material.needDepthPrePass) {
  20597. var engine = material.getScene().getEngine();
  20598. engine.setColorWrite(false);
  20599. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20600. subMesh.render(false);
  20601. engine.setColorWrite(true);
  20602. }
  20603. }
  20604. subMesh.render(transparent);
  20605. }
  20606. };
  20607. /**
  20608. * Renders the submeshes in the order they were dispatched (no sort applied).
  20609. * @param subMeshes The submeshes to render
  20610. */
  20611. RenderingGroup.renderUnsorted = function (subMeshes) {
  20612. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20613. var submesh = subMeshes.data[subIndex];
  20614. submesh.render(false);
  20615. }
  20616. };
  20617. /**
  20618. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20619. * are rendered back to front if in the same alpha index.
  20620. *
  20621. * @param a The first submesh
  20622. * @param b The second submesh
  20623. * @returns The result of the comparison
  20624. */
  20625. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20626. // Alpha index first
  20627. if (a._alphaIndex > b._alphaIndex) {
  20628. return 1;
  20629. }
  20630. if (a._alphaIndex < b._alphaIndex) {
  20631. return -1;
  20632. }
  20633. // Then distance to camera
  20634. return RenderingGroup.backToFrontSortCompare(a, b);
  20635. };
  20636. /**
  20637. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20638. * are rendered back to front.
  20639. *
  20640. * @param a The first submesh
  20641. * @param b The second submesh
  20642. * @returns The result of the comparison
  20643. */
  20644. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20645. // Then distance to camera
  20646. if (a._distanceToCamera < b._distanceToCamera) {
  20647. return 1;
  20648. }
  20649. if (a._distanceToCamera > b._distanceToCamera) {
  20650. return -1;
  20651. }
  20652. return 0;
  20653. };
  20654. /**
  20655. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20656. * are rendered front to back (prevent overdraw).
  20657. *
  20658. * @param a The first submesh
  20659. * @param b The second submesh
  20660. * @returns The result of the comparison
  20661. */
  20662. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20663. // Then distance to camera
  20664. if (a._distanceToCamera < b._distanceToCamera) {
  20665. return -1;
  20666. }
  20667. if (a._distanceToCamera > b._distanceToCamera) {
  20668. return 1;
  20669. }
  20670. return 0;
  20671. };
  20672. /**
  20673. * Resets the different lists of submeshes to prepare a new frame.
  20674. */
  20675. RenderingGroup.prototype.prepare = function () {
  20676. this._opaqueSubMeshes.reset();
  20677. this._transparentSubMeshes.reset();
  20678. this._alphaTestSubMeshes.reset();
  20679. this._depthOnlySubMeshes.reset();
  20680. this._particleSystems.reset();
  20681. this._spriteManagers.reset();
  20682. this._edgesRenderers.reset();
  20683. };
  20684. RenderingGroup.prototype.dispose = function () {
  20685. this._opaqueSubMeshes.dispose();
  20686. this._transparentSubMeshes.dispose();
  20687. this._alphaTestSubMeshes.dispose();
  20688. this._depthOnlySubMeshes.dispose();
  20689. this._particleSystems.dispose();
  20690. this._spriteManagers.dispose();
  20691. this._edgesRenderers.dispose();
  20692. };
  20693. /**
  20694. * Inserts the submesh in its correct queue depending on its material.
  20695. * @param subMesh The submesh to dispatch
  20696. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20697. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20698. */
  20699. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20700. // Get mesh and materials if not provided
  20701. if (mesh === undefined) {
  20702. mesh = subMesh.getMesh();
  20703. }
  20704. if (material === undefined) {
  20705. material = subMesh.getMaterial();
  20706. }
  20707. if (material === null || material === undefined) {
  20708. return;
  20709. }
  20710. if (material.needAlphaBlendingForMesh(mesh)) {
  20711. this._transparentSubMeshes.push(subMesh);
  20712. }
  20713. else if (material.needAlphaTesting()) {
  20714. if (material.needDepthPrePass) {
  20715. this._depthOnlySubMeshes.push(subMesh);
  20716. }
  20717. this._alphaTestSubMeshes.push(subMesh);
  20718. }
  20719. else {
  20720. if (material.needDepthPrePass) {
  20721. this._depthOnlySubMeshes.push(subMesh);
  20722. }
  20723. this._opaqueSubMeshes.push(subMesh); // Opaque
  20724. }
  20725. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20726. this._edgesRenderers.push(mesh._edgesRenderer);
  20727. }
  20728. };
  20729. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20730. this._spriteManagers.push(spriteManager);
  20731. };
  20732. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20733. this._particleSystems.push(particleSystem);
  20734. };
  20735. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20736. if (this._particleSystems.length === 0) {
  20737. return;
  20738. }
  20739. // Particles
  20740. var activeCamera = this._scene.activeCamera;
  20741. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20742. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20743. var particleSystem = this._particleSystems.data[particleIndex];
  20744. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20745. continue;
  20746. }
  20747. var emitter = particleSystem.emitter;
  20748. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20749. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20750. }
  20751. }
  20752. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20753. };
  20754. RenderingGroup.prototype._renderSprites = function () {
  20755. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20756. return;
  20757. }
  20758. // Sprites
  20759. var activeCamera = this._scene.activeCamera;
  20760. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20761. for (var id = 0; id < this._spriteManagers.length; id++) {
  20762. var spriteManager = this._spriteManagers.data[id];
  20763. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20764. spriteManager.render();
  20765. }
  20766. }
  20767. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20768. };
  20769. return RenderingGroup;
  20770. }());
  20771. BABYLON.RenderingGroup = RenderingGroup;
  20772. })(BABYLON || (BABYLON = {}));
  20773. //# sourceMappingURL=babylon.renderingGroup.js.map
  20774. var BABYLON;
  20775. (function (BABYLON) {
  20776. var ClickInfo = /** @class */ (function () {
  20777. function ClickInfo() {
  20778. this._singleClick = false;
  20779. this._doubleClick = false;
  20780. this._hasSwiped = false;
  20781. this._ignore = false;
  20782. }
  20783. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20784. get: function () {
  20785. return this._singleClick;
  20786. },
  20787. set: function (b) {
  20788. this._singleClick = b;
  20789. },
  20790. enumerable: true,
  20791. configurable: true
  20792. });
  20793. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20794. get: function () {
  20795. return this._doubleClick;
  20796. },
  20797. set: function (b) {
  20798. this._doubleClick = b;
  20799. },
  20800. enumerable: true,
  20801. configurable: true
  20802. });
  20803. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20804. get: function () {
  20805. return this._hasSwiped;
  20806. },
  20807. set: function (b) {
  20808. this._hasSwiped = b;
  20809. },
  20810. enumerable: true,
  20811. configurable: true
  20812. });
  20813. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20814. get: function () {
  20815. return this._ignore;
  20816. },
  20817. set: function (b) {
  20818. this._ignore = b;
  20819. },
  20820. enumerable: true,
  20821. configurable: true
  20822. });
  20823. return ClickInfo;
  20824. }());
  20825. /**
  20826. * This class is used by the onRenderingGroupObservable
  20827. */
  20828. var RenderingGroupInfo = /** @class */ (function () {
  20829. function RenderingGroupInfo() {
  20830. }
  20831. /**
  20832. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20833. * This stage will be fired no matter what
  20834. */
  20835. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20836. /**
  20837. * Called before opaque object are rendered.
  20838. * This stage will be fired only if there's 3D Opaque content to render
  20839. */
  20840. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20841. /**
  20842. * Called after the opaque objects are rendered and before the transparent ones
  20843. * This stage will be fired only if there's 3D transparent content to render
  20844. */
  20845. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20846. /**
  20847. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20848. * This stage will be fired no matter what
  20849. */
  20850. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20851. return RenderingGroupInfo;
  20852. }());
  20853. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20854. /**
  20855. * Represents a scene to be rendered by the engine.
  20856. * @see http://doc.babylonjs.com/page.php?p=21911
  20857. */
  20858. var Scene = /** @class */ (function () {
  20859. /**
  20860. * @constructor
  20861. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20862. */
  20863. function Scene(engine) {
  20864. // Members
  20865. this.autoClear = true;
  20866. this.autoClearDepthAndStencil = true;
  20867. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20868. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20869. this.forceWireframe = false;
  20870. this._forcePointsCloud = false;
  20871. this.forceShowBoundingBoxes = false;
  20872. this.animationsEnabled = true;
  20873. this.useConstantAnimationDeltaTime = false;
  20874. this.constantlyUpdateMeshUnderPointer = false;
  20875. this.hoverCursor = "pointer";
  20876. this.defaultCursor = "";
  20877. /**
  20878. * This is used to call preventDefault() on pointer down
  20879. * in order to block unwanted artifacts like system double clicks
  20880. */
  20881. this.preventDefaultOnPointerDown = true;
  20882. // Metadata
  20883. this.metadata = null;
  20884. /**
  20885. * An event triggered when the scene is disposed.
  20886. * @type {BABYLON.Observable}
  20887. */
  20888. this.onDisposeObservable = new BABYLON.Observable();
  20889. /**
  20890. * An event triggered before rendering the scene (right after animations and physics)
  20891. * @type {BABYLON.Observable}
  20892. */
  20893. this.onBeforeRenderObservable = new BABYLON.Observable();
  20894. /**
  20895. * An event triggered after rendering the scene
  20896. * @type {BABYLON.Observable}
  20897. */
  20898. this.onAfterRenderObservable = new BABYLON.Observable();
  20899. /**
  20900. * An event triggered before animating the scene
  20901. * @type {BABYLON.Observable}
  20902. */
  20903. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20904. /**
  20905. * An event triggered after animations processing
  20906. * @type {BABYLON.Observable}
  20907. */
  20908. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20909. /**
  20910. * An event triggered before draw calls are ready to be sent
  20911. * @type {BABYLON.Observable}
  20912. */
  20913. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20914. /**
  20915. * An event triggered after draw calls have been sent
  20916. * @type {BABYLON.Observable}
  20917. */
  20918. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20919. /**
  20920. * An event triggered when physic simulation is about to be run
  20921. * @type {BABYLON.Observable}
  20922. */
  20923. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20924. /**
  20925. * An event triggered when physic simulation has been done
  20926. * @type {BABYLON.Observable}
  20927. */
  20928. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20929. /**
  20930. * An event triggered when the scene is ready
  20931. * @type {BABYLON.Observable}
  20932. */
  20933. this.onReadyObservable = new BABYLON.Observable();
  20934. /**
  20935. * An event triggered before rendering a camera
  20936. * @type {BABYLON.Observable}
  20937. */
  20938. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20939. /**
  20940. * An event triggered after rendering a camera
  20941. * @type {BABYLON.Observable}
  20942. */
  20943. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20944. /**
  20945. * An event triggered when active meshes evaluation is about to start
  20946. * @type {BABYLON.Observable}
  20947. */
  20948. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20949. /**
  20950. * An event triggered when active meshes evaluation is done
  20951. * @type {BABYLON.Observable}
  20952. */
  20953. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20954. /**
  20955. * An event triggered when particles rendering is about to start
  20956. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20957. * @type {BABYLON.Observable}
  20958. */
  20959. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20960. /**
  20961. * An event triggered when particles rendering is done
  20962. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20963. * @type {BABYLON.Observable}
  20964. */
  20965. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20966. /**
  20967. * An event triggered when sprites rendering is about to start
  20968. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20969. * @type {BABYLON.Observable}
  20970. */
  20971. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20972. /**
  20973. * An event triggered when sprites rendering is done
  20974. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20975. * @type {BABYLON.Observable}
  20976. */
  20977. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20978. /**
  20979. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20980. * @type {BABYLON.Observable}
  20981. */
  20982. this.onDataLoadedObservable = new BABYLON.Observable();
  20983. /**
  20984. * An event triggered when a camera is created
  20985. * @type {BABYLON.Observable}
  20986. */
  20987. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20988. /**
  20989. * An event triggered when a camera is removed
  20990. * @type {BABYLON.Observable}
  20991. */
  20992. this.onCameraRemovedObservable = new BABYLON.Observable();
  20993. /**
  20994. * An event triggered when a light is created
  20995. * @type {BABYLON.Observable}
  20996. */
  20997. this.onNewLightAddedObservable = new BABYLON.Observable();
  20998. /**
  20999. * An event triggered when a light is removed
  21000. * @type {BABYLON.Observable}
  21001. */
  21002. this.onLightRemovedObservable = new BABYLON.Observable();
  21003. /**
  21004. * An event triggered when a geometry is created
  21005. * @type {BABYLON.Observable}
  21006. */
  21007. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21008. /**
  21009. * An event triggered when a geometry is removed
  21010. * @type {BABYLON.Observable}
  21011. */
  21012. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21013. /**
  21014. * An event triggered when a transform node is created
  21015. * @type {BABYLON.Observable}
  21016. */
  21017. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21018. /**
  21019. * An event triggered when a transform node is removed
  21020. * @type {BABYLON.Observable}
  21021. */
  21022. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21023. /**
  21024. * An event triggered when a mesh is created
  21025. * @type {BABYLON.Observable}
  21026. */
  21027. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21028. /**
  21029. * An event triggered when a mesh is removed
  21030. * @type {BABYLON.Observable}
  21031. */
  21032. this.onMeshRemovedObservable = new BABYLON.Observable();
  21033. /**
  21034. * An event triggered when render targets are about to be rendered
  21035. * Can happen multiple times per frame.
  21036. * @type {BABYLON.Observable}
  21037. */
  21038. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21039. /**
  21040. * An event triggered when render targets were rendered.
  21041. * Can happen multiple times per frame.
  21042. * @type {BABYLON.Observable}
  21043. */
  21044. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21045. /**
  21046. * An event triggered before calculating deterministic simulation step
  21047. * @type {BABYLON.Observable}
  21048. */
  21049. this.onBeforeStepObservable = new BABYLON.Observable();
  21050. /**
  21051. * An event triggered after calculating deterministic simulation step
  21052. * @type {BABYLON.Observable}
  21053. */
  21054. this.onAfterStepObservable = new BABYLON.Observable();
  21055. /**
  21056. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21057. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21058. * 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)
  21059. */
  21060. this.onRenderingGroupObservable = new BABYLON.Observable();
  21061. // Animations
  21062. this.animations = [];
  21063. /**
  21064. * 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).
  21065. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21066. */
  21067. this.onPrePointerObservable = new BABYLON.Observable();
  21068. /**
  21069. * Observable event triggered each time an input event is received from the rendering canvas
  21070. */
  21071. this.onPointerObservable = new BABYLON.Observable();
  21072. this._meshPickProceed = false;
  21073. this._currentPickResult = null;
  21074. this._previousPickResult = null;
  21075. this._totalPointersPressed = 0;
  21076. this._doubleClickOccured = false;
  21077. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21078. this.cameraToUseForPointers = null;
  21079. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21080. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21081. this._startingPointerTime = 0;
  21082. this._previousStartingPointerTime = 0;
  21083. // Deterministic lockstep
  21084. this._timeAccumulator = 0;
  21085. this._currentStepId = 0;
  21086. this._currentInternalStep = 0;
  21087. // Keyboard
  21088. /**
  21089. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21090. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21091. */
  21092. this.onPreKeyboardObservable = new BABYLON.Observable();
  21093. /**
  21094. * Observable event triggered each time an keyboard event is received from the hosting window
  21095. */
  21096. this.onKeyboardObservable = new BABYLON.Observable();
  21097. // Coordinate system
  21098. /**
  21099. * use right-handed coordinate system on this scene.
  21100. * @type {boolean}
  21101. */
  21102. this._useRightHandedSystem = false;
  21103. // Fog
  21104. this._fogEnabled = true;
  21105. this._fogMode = Scene.FOGMODE_NONE;
  21106. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21107. this.fogDensity = 0.1;
  21108. this.fogStart = 0;
  21109. this.fogEnd = 1000.0;
  21110. // Lights
  21111. /**
  21112. * is shadow enabled on this scene.
  21113. * @type {boolean}
  21114. */
  21115. this._shadowsEnabled = true;
  21116. /**
  21117. * is light enabled on this scene.
  21118. * @type {boolean}
  21119. */
  21120. this._lightsEnabled = true;
  21121. /**
  21122. * All of the lights added to this scene.
  21123. * @see BABYLON.Light
  21124. * @type {BABYLON.Light[]}
  21125. */
  21126. this.lights = new Array();
  21127. // Cameras
  21128. /** All of the cameras added to this scene. */
  21129. this.cameras = new Array();
  21130. /** All of the active cameras added to this scene. */
  21131. this.activeCameras = new Array();
  21132. // Meshes
  21133. /**
  21134. * All of the tranform nodes added to this scene.
  21135. * @see BABYLON.TransformNode
  21136. * @type {BABYLON.TransformNode[]}
  21137. */
  21138. this.transformNodes = new Array();
  21139. /**
  21140. * All of the (abstract) meshes added to this scene.
  21141. * @see BABYLON.AbstractMesh
  21142. * @type {BABYLON.AbstractMesh[]}
  21143. */
  21144. this.meshes = new Array();
  21145. /**
  21146. * All of the animation groups added to this scene.
  21147. * @see BABYLON.AnimationGroup
  21148. * @type {BABYLON.AnimationGroup[]}
  21149. */
  21150. this.animationGroups = new Array();
  21151. // Geometries
  21152. this._geometries = new Array();
  21153. this.materials = new Array();
  21154. this.multiMaterials = new Array();
  21155. // Textures
  21156. this._texturesEnabled = true;
  21157. this.textures = new Array();
  21158. // Particles
  21159. this.particlesEnabled = true;
  21160. this.particleSystems = new Array();
  21161. // Sprites
  21162. this.spritesEnabled = true;
  21163. this.spriteManagers = new Array();
  21164. /**
  21165. * The list of layers (background and foreground) of the scene.
  21166. */
  21167. this.layers = new Array();
  21168. /**
  21169. * The list of effect layers (highlights/glow) contained in the scene.
  21170. */
  21171. this.effectLayers = new Array();
  21172. // Skeletons
  21173. this._skeletonsEnabled = true;
  21174. this.skeletons = new Array();
  21175. // Morph targets
  21176. this.morphTargetManagers = new Array();
  21177. // Lens flares
  21178. this.lensFlaresEnabled = true;
  21179. this.lensFlareSystems = new Array();
  21180. // Collisions
  21181. this.collisionsEnabled = true;
  21182. /** Defines the gravity applied to this scene */
  21183. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21184. // Postprocesses
  21185. this.postProcesses = new Array();
  21186. this.postProcessesEnabled = true;
  21187. // Customs render targets
  21188. this.renderTargetsEnabled = true;
  21189. this.dumpNextRenderTargets = false;
  21190. this.customRenderTargets = new Array();
  21191. // Imported meshes
  21192. this.importedMeshesFiles = new Array();
  21193. // Probes
  21194. this.probesEnabled = true;
  21195. this.reflectionProbes = new Array();
  21196. this._actionManagers = new Array();
  21197. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21198. // Procedural textures
  21199. this.proceduralTexturesEnabled = true;
  21200. this._proceduralTextures = new Array();
  21201. this.soundTracks = new Array();
  21202. this._audioEnabled = true;
  21203. this._headphone = false;
  21204. // Performance counters
  21205. this._totalVertices = new BABYLON.PerfCounter();
  21206. this._activeIndices = new BABYLON.PerfCounter();
  21207. this._activeParticles = new BABYLON.PerfCounter();
  21208. this._activeBones = new BABYLON.PerfCounter();
  21209. this._animationTime = 0;
  21210. this.animationTimeScale = 1;
  21211. this._renderId = 0;
  21212. this._executeWhenReadyTimeoutId = -1;
  21213. this._intermediateRendering = false;
  21214. this._viewUpdateFlag = -1;
  21215. this._projectionUpdateFlag = -1;
  21216. this._alternateViewUpdateFlag = -1;
  21217. this._alternateProjectionUpdateFlag = -1;
  21218. this._toBeDisposed = new BABYLON.SmartArray(256);
  21219. this._activeRequests = new Array();
  21220. this._pendingData = new Array();
  21221. this._isDisposed = false;
  21222. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21223. this._activeMeshes = new BABYLON.SmartArray(256);
  21224. this._processedMaterials = new BABYLON.SmartArray(256);
  21225. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21226. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21227. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21228. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21229. this._activeAnimatables = new Array();
  21230. this._transformMatrix = BABYLON.Matrix.Zero();
  21231. this._useAlternateCameraConfiguration = false;
  21232. this._alternateRendering = false;
  21233. this.requireLightSorting = false;
  21234. this._activeMeshesFrozen = false;
  21235. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21236. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21237. this._engine.scenes.push(this);
  21238. this._uid = null;
  21239. this._renderingManager = new BABYLON.RenderingManager(this);
  21240. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21241. if (BABYLON.OutlineRenderer) {
  21242. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21243. }
  21244. if (BABYLON.Tools.IsWindowObjectExist()) {
  21245. this.attachControl();
  21246. }
  21247. //simplification queue
  21248. if (BABYLON.SimplificationQueue) {
  21249. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21250. }
  21251. //collision coordinator initialization. For now legacy per default.
  21252. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21253. // Uniform Buffer
  21254. this._createUbo();
  21255. // Default Image processing definition.
  21256. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21257. }
  21258. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21259. /** The fog is deactivated */
  21260. get: function () {
  21261. return Scene._FOGMODE_NONE;
  21262. },
  21263. enumerable: true,
  21264. configurable: true
  21265. });
  21266. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21267. /** The fog density is following an exponential function */
  21268. get: function () {
  21269. return Scene._FOGMODE_EXP;
  21270. },
  21271. enumerable: true,
  21272. configurable: true
  21273. });
  21274. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21275. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21276. get: function () {
  21277. return Scene._FOGMODE_EXP2;
  21278. },
  21279. enumerable: true,
  21280. configurable: true
  21281. });
  21282. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21283. /** The fog density is following a linear function. */
  21284. get: function () {
  21285. return Scene._FOGMODE_LINEAR;
  21286. },
  21287. enumerable: true,
  21288. configurable: true
  21289. });
  21290. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21291. /**
  21292. * Texture used in all pbr material as the reflection texture.
  21293. * As in the majority of the scene they are the same (exception for multi room and so on),
  21294. * this is easier to reference from here than from all the materials.
  21295. */
  21296. get: function () {
  21297. return this._environmentTexture;
  21298. },
  21299. /**
  21300. * Texture used in all pbr material as the reflection texture.
  21301. * As in the majority of the scene they are the same (exception for multi room and so on),
  21302. * this is easier to set here than in all the materials.
  21303. */
  21304. set: function (value) {
  21305. if (this._environmentTexture === value) {
  21306. return;
  21307. }
  21308. this._environmentTexture = value;
  21309. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21310. },
  21311. enumerable: true,
  21312. configurable: true
  21313. });
  21314. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21315. /**
  21316. * Default image processing configuration used either in the rendering
  21317. * Forward main pass or through the imageProcessingPostProcess if present.
  21318. * As in the majority of the scene they are the same (exception for multi camera),
  21319. * this is easier to reference from here than from all the materials and post process.
  21320. *
  21321. * No setter as we it is a shared configuration, you can set the values instead.
  21322. */
  21323. get: function () {
  21324. return this._imageProcessingConfiguration;
  21325. },
  21326. enumerable: true,
  21327. configurable: true
  21328. });
  21329. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21330. get: function () {
  21331. return this._forcePointsCloud;
  21332. },
  21333. set: function (value) {
  21334. if (this._forcePointsCloud === value) {
  21335. return;
  21336. }
  21337. this._forcePointsCloud = value;
  21338. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21339. },
  21340. enumerable: true,
  21341. configurable: true
  21342. });
  21343. Object.defineProperty(Scene.prototype, "onDispose", {
  21344. /** A function to be executed when this scene is disposed. */
  21345. set: function (callback) {
  21346. if (this._onDisposeObserver) {
  21347. this.onDisposeObservable.remove(this._onDisposeObserver);
  21348. }
  21349. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21350. },
  21351. enumerable: true,
  21352. configurable: true
  21353. });
  21354. Object.defineProperty(Scene.prototype, "beforeRender", {
  21355. /** A function to be executed before rendering this scene */
  21356. set: function (callback) {
  21357. if (this._onBeforeRenderObserver) {
  21358. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21359. }
  21360. if (callback) {
  21361. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21362. }
  21363. },
  21364. enumerable: true,
  21365. configurable: true
  21366. });
  21367. Object.defineProperty(Scene.prototype, "afterRender", {
  21368. /** A function to be executed after rendering this scene */
  21369. set: function (callback) {
  21370. if (this._onAfterRenderObserver) {
  21371. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21372. }
  21373. if (callback) {
  21374. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21375. }
  21376. },
  21377. enumerable: true,
  21378. configurable: true
  21379. });
  21380. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21381. set: function (callback) {
  21382. if (this._onBeforeCameraRenderObserver) {
  21383. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21384. }
  21385. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21386. },
  21387. enumerable: true,
  21388. configurable: true
  21389. });
  21390. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21391. set: function (callback) {
  21392. if (this._onAfterCameraRenderObserver) {
  21393. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21394. }
  21395. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21401. get: function () {
  21402. if (!this._gamepadManager) {
  21403. this._gamepadManager = new BABYLON.GamepadManager(this);
  21404. }
  21405. return this._gamepadManager;
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21411. get: function () {
  21412. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21413. },
  21414. enumerable: true,
  21415. configurable: true
  21416. });
  21417. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21418. get: function () {
  21419. return this._useRightHandedSystem;
  21420. },
  21421. set: function (value) {
  21422. if (this._useRightHandedSystem === value) {
  21423. return;
  21424. }
  21425. this._useRightHandedSystem = value;
  21426. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21427. },
  21428. enumerable: true,
  21429. configurable: true
  21430. });
  21431. Scene.prototype.setStepId = function (newStepId) {
  21432. this._currentStepId = newStepId;
  21433. };
  21434. ;
  21435. Scene.prototype.getStepId = function () {
  21436. return this._currentStepId;
  21437. };
  21438. ;
  21439. Scene.prototype.getInternalStep = function () {
  21440. return this._currentInternalStep;
  21441. };
  21442. ;
  21443. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21444. get: function () {
  21445. return this._fogEnabled;
  21446. },
  21447. /**
  21448. * is fog enabled on this scene.
  21449. */
  21450. set: function (value) {
  21451. if (this._fogEnabled === value) {
  21452. return;
  21453. }
  21454. this._fogEnabled = value;
  21455. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21456. },
  21457. enumerable: true,
  21458. configurable: true
  21459. });
  21460. Object.defineProperty(Scene.prototype, "fogMode", {
  21461. get: function () {
  21462. return this._fogMode;
  21463. },
  21464. set: function (value) {
  21465. if (this._fogMode === value) {
  21466. return;
  21467. }
  21468. this._fogMode = value;
  21469. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21470. },
  21471. enumerable: true,
  21472. configurable: true
  21473. });
  21474. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21475. get: function () {
  21476. return this._shadowsEnabled;
  21477. },
  21478. set: function (value) {
  21479. if (this._shadowsEnabled === value) {
  21480. return;
  21481. }
  21482. this._shadowsEnabled = value;
  21483. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21484. },
  21485. enumerable: true,
  21486. configurable: true
  21487. });
  21488. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21489. get: function () {
  21490. return this._lightsEnabled;
  21491. },
  21492. set: function (value) {
  21493. if (this._lightsEnabled === value) {
  21494. return;
  21495. }
  21496. this._lightsEnabled = value;
  21497. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21498. },
  21499. enumerable: true,
  21500. configurable: true
  21501. });
  21502. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21503. /** The default material used on meshes when no material is affected */
  21504. get: function () {
  21505. if (!this._defaultMaterial) {
  21506. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21507. }
  21508. return this._defaultMaterial;
  21509. },
  21510. /** The default material used on meshes when no material is affected */
  21511. set: function (value) {
  21512. this._defaultMaterial = value;
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21518. get: function () {
  21519. return this._texturesEnabled;
  21520. },
  21521. set: function (value) {
  21522. if (this._texturesEnabled === value) {
  21523. return;
  21524. }
  21525. this._texturesEnabled = value;
  21526. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21532. get: function () {
  21533. return this._skeletonsEnabled;
  21534. },
  21535. set: function (value) {
  21536. if (this._skeletonsEnabled === value) {
  21537. return;
  21538. }
  21539. this._skeletonsEnabled = value;
  21540. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21541. },
  21542. enumerable: true,
  21543. configurable: true
  21544. });
  21545. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21546. get: function () {
  21547. if (!this._postProcessRenderPipelineManager) {
  21548. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21549. }
  21550. return this._postProcessRenderPipelineManager;
  21551. },
  21552. enumerable: true,
  21553. configurable: true
  21554. });
  21555. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21556. get: function () {
  21557. if (!this._mainSoundTrack) {
  21558. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21559. }
  21560. return this._mainSoundTrack;
  21561. },
  21562. enumerable: true,
  21563. configurable: true
  21564. });
  21565. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21566. get: function () {
  21567. return this._alternateRendering;
  21568. },
  21569. enumerable: true,
  21570. configurable: true
  21571. });
  21572. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21573. get: function () {
  21574. return this._frustumPlanes;
  21575. },
  21576. enumerable: true,
  21577. configurable: true
  21578. });
  21579. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21580. /**
  21581. * Gets the current geometry buffer associated to the scene.
  21582. */
  21583. get: function () {
  21584. return this._geometryBufferRenderer;
  21585. },
  21586. /**
  21587. * Sets the current geometry buffer for the scene.
  21588. */
  21589. set: function (geometryBufferRenderer) {
  21590. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21591. this._geometryBufferRenderer = geometryBufferRenderer;
  21592. }
  21593. },
  21594. enumerable: true,
  21595. configurable: true
  21596. });
  21597. Object.defineProperty(Scene.prototype, "debugLayer", {
  21598. // Properties
  21599. get: function () {
  21600. if (!this._debugLayer) {
  21601. this._debugLayer = new BABYLON.DebugLayer(this);
  21602. }
  21603. return this._debugLayer;
  21604. },
  21605. enumerable: true,
  21606. configurable: true
  21607. });
  21608. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21609. get: function () {
  21610. return this._workerCollisions;
  21611. },
  21612. set: function (enabled) {
  21613. if (!BABYLON.CollisionCoordinatorLegacy) {
  21614. return;
  21615. }
  21616. enabled = (enabled && !!Worker);
  21617. this._workerCollisions = enabled;
  21618. if (this.collisionCoordinator) {
  21619. this.collisionCoordinator.destroy();
  21620. }
  21621. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21622. this.collisionCoordinator.init(this);
  21623. },
  21624. enumerable: true,
  21625. configurable: true
  21626. });
  21627. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21628. get: function () {
  21629. return this._selectionOctree;
  21630. },
  21631. enumerable: true,
  21632. configurable: true
  21633. });
  21634. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21635. /**
  21636. * The mesh that is currently under the pointer.
  21637. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21638. */
  21639. get: function () {
  21640. return this._pointerOverMesh;
  21641. },
  21642. enumerable: true,
  21643. configurable: true
  21644. });
  21645. Object.defineProperty(Scene.prototype, "pointerX", {
  21646. /**
  21647. * Current on-screen X position of the pointer
  21648. * @return {number} X position of the pointer
  21649. */
  21650. get: function () {
  21651. return this._pointerX;
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(Scene.prototype, "pointerY", {
  21657. /**
  21658. * Current on-screen Y position of the pointer
  21659. * @return {number} Y position of the pointer
  21660. */
  21661. get: function () {
  21662. return this._pointerY;
  21663. },
  21664. enumerable: true,
  21665. configurable: true
  21666. });
  21667. Scene.prototype.getCachedMaterial = function () {
  21668. return this._cachedMaterial;
  21669. };
  21670. Scene.prototype.getCachedEffect = function () {
  21671. return this._cachedEffect;
  21672. };
  21673. Scene.prototype.getCachedVisibility = function () {
  21674. return this._cachedVisibility;
  21675. };
  21676. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21677. if (visibility === void 0) { visibility = 1; }
  21678. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21679. };
  21680. Scene.prototype.getBoundingBoxRenderer = function () {
  21681. if (!this._boundingBoxRenderer) {
  21682. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21683. }
  21684. return this._boundingBoxRenderer;
  21685. };
  21686. Scene.prototype.getOutlineRenderer = function () {
  21687. return this._outlineRenderer;
  21688. };
  21689. Scene.prototype.getEngine = function () {
  21690. return this._engine;
  21691. };
  21692. Scene.prototype.getTotalVertices = function () {
  21693. return this._totalVertices.current;
  21694. };
  21695. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21696. get: function () {
  21697. return this._totalVertices;
  21698. },
  21699. enumerable: true,
  21700. configurable: true
  21701. });
  21702. Scene.prototype.getActiveIndices = function () {
  21703. return this._activeIndices.current;
  21704. };
  21705. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21706. get: function () {
  21707. return this._activeIndices;
  21708. },
  21709. enumerable: true,
  21710. configurable: true
  21711. });
  21712. Scene.prototype.getActiveParticles = function () {
  21713. return this._activeParticles.current;
  21714. };
  21715. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21716. get: function () {
  21717. return this._activeParticles;
  21718. },
  21719. enumerable: true,
  21720. configurable: true
  21721. });
  21722. Scene.prototype.getActiveBones = function () {
  21723. return this._activeBones.current;
  21724. };
  21725. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21726. get: function () {
  21727. return this._activeBones;
  21728. },
  21729. enumerable: true,
  21730. configurable: true
  21731. });
  21732. // Stats
  21733. Scene.prototype.getInterFramePerfCounter = function () {
  21734. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21735. return 0;
  21736. };
  21737. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21738. get: function () {
  21739. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21740. return null;
  21741. },
  21742. enumerable: true,
  21743. configurable: true
  21744. });
  21745. Scene.prototype.getLastFrameDuration = function () {
  21746. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21747. return 0;
  21748. };
  21749. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21750. get: function () {
  21751. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21752. return null;
  21753. },
  21754. enumerable: true,
  21755. configurable: true
  21756. });
  21757. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21758. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21759. return 0;
  21760. };
  21761. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21762. get: function () {
  21763. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21764. return null;
  21765. },
  21766. enumerable: true,
  21767. configurable: true
  21768. });
  21769. Scene.prototype.getActiveMeshes = function () {
  21770. return this._activeMeshes;
  21771. };
  21772. Scene.prototype.getRenderTargetsDuration = function () {
  21773. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21774. return 0;
  21775. };
  21776. Scene.prototype.getRenderDuration = function () {
  21777. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21778. return 0;
  21779. };
  21780. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21781. get: function () {
  21782. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21783. return null;
  21784. },
  21785. enumerable: true,
  21786. configurable: true
  21787. });
  21788. Scene.prototype.getParticlesDuration = function () {
  21789. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21790. return 0;
  21791. };
  21792. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21793. get: function () {
  21794. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21795. return null;
  21796. },
  21797. enumerable: true,
  21798. configurable: true
  21799. });
  21800. Scene.prototype.getSpritesDuration = function () {
  21801. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21802. return 0;
  21803. };
  21804. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21805. get: function () {
  21806. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21807. return null;
  21808. },
  21809. enumerable: true,
  21810. configurable: true
  21811. });
  21812. Scene.prototype.getAnimationRatio = function () {
  21813. return this._animationRatio;
  21814. };
  21815. Scene.prototype.getRenderId = function () {
  21816. return this._renderId;
  21817. };
  21818. Scene.prototype.incrementRenderId = function () {
  21819. this._renderId++;
  21820. };
  21821. Scene.prototype._updatePointerPosition = function (evt) {
  21822. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21823. if (!canvasRect) {
  21824. return;
  21825. }
  21826. this._pointerX = evt.clientX - canvasRect.left;
  21827. this._pointerY = evt.clientY - canvasRect.top;
  21828. this._unTranslatedPointerX = this._pointerX;
  21829. this._unTranslatedPointerY = this._pointerY;
  21830. };
  21831. Scene.prototype._createUbo = function () {
  21832. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21833. this._sceneUbo.addUniform("viewProjection", 16);
  21834. this._sceneUbo.addUniform("view", 16);
  21835. };
  21836. Scene.prototype._createAlternateUbo = function () {
  21837. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21838. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21839. this._alternateSceneUbo.addUniform("view", 16);
  21840. };
  21841. // Pointers handling
  21842. /**
  21843. * Use this method to simulate a pointer move on a mesh
  21844. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21845. */
  21846. Scene.prototype.simulatePointerMove = function (pickResult) {
  21847. var evt = new PointerEvent("pointermove");
  21848. return this._processPointerMove(pickResult, evt);
  21849. };
  21850. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21851. var canvas = this._engine.getRenderingCanvas();
  21852. if (!canvas) {
  21853. return this;
  21854. }
  21855. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21856. this.setPointerOverSprite(null);
  21857. this.setPointerOverMesh(pickResult.pickedMesh);
  21858. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21859. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21860. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21861. }
  21862. else {
  21863. canvas.style.cursor = this.hoverCursor;
  21864. }
  21865. }
  21866. else {
  21867. canvas.style.cursor = this.defaultCursor;
  21868. }
  21869. }
  21870. else {
  21871. this.setPointerOverMesh(null);
  21872. // Sprites
  21873. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21874. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21875. this.setPointerOverSprite(pickResult.pickedSprite);
  21876. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21877. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21878. }
  21879. else {
  21880. canvas.style.cursor = this.hoverCursor;
  21881. }
  21882. }
  21883. else {
  21884. this.setPointerOverSprite(null);
  21885. // Restore pointer
  21886. canvas.style.cursor = this.defaultCursor;
  21887. }
  21888. }
  21889. if (pickResult) {
  21890. if (this.onPointerMove) {
  21891. this.onPointerMove(evt, pickResult);
  21892. }
  21893. if (this.onPointerObservable.hasObservers()) {
  21894. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21895. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21896. this.onPointerObservable.notifyObservers(pi, type);
  21897. }
  21898. }
  21899. return this;
  21900. };
  21901. /**
  21902. * Use this method to simulate a pointer down on a mesh
  21903. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21904. */
  21905. Scene.prototype.simulatePointerDown = function (pickResult) {
  21906. var evt = new PointerEvent("pointerdown");
  21907. return this._processPointerDown(pickResult, evt);
  21908. };
  21909. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21910. var _this = this;
  21911. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21912. this._pickedDownMesh = pickResult.pickedMesh;
  21913. var actionManager = pickResult.pickedMesh.actionManager;
  21914. if (actionManager) {
  21915. if (actionManager.hasPickTriggers) {
  21916. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21917. switch (evt.button) {
  21918. case 0:
  21919. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21920. break;
  21921. case 1:
  21922. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21923. break;
  21924. case 2:
  21925. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21926. break;
  21927. }
  21928. }
  21929. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21930. window.setTimeout(function () {
  21931. 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);
  21932. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21933. if (_this._totalPointersPressed !== 0 &&
  21934. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21935. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21936. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21937. _this._startingPointerTime = 0;
  21938. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21939. }
  21940. }
  21941. }, Scene.LongPressDelay);
  21942. }
  21943. }
  21944. }
  21945. if (pickResult) {
  21946. if (this.onPointerDown) {
  21947. this.onPointerDown(evt, pickResult);
  21948. }
  21949. if (this.onPointerObservable.hasObservers()) {
  21950. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21951. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21952. this.onPointerObservable.notifyObservers(pi, type);
  21953. }
  21954. }
  21955. return this;
  21956. };
  21957. /**
  21958. * Use this method to simulate a pointer up on a mesh
  21959. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21960. */
  21961. Scene.prototype.simulatePointerUp = function (pickResult) {
  21962. var evt = new PointerEvent("pointerup");
  21963. var clickInfo = new ClickInfo();
  21964. clickInfo.singleClick = true;
  21965. clickInfo.ignore = true;
  21966. return this._processPointerUp(pickResult, evt, clickInfo);
  21967. };
  21968. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21969. if (pickResult && pickResult && pickResult.pickedMesh) {
  21970. this._pickedUpMesh = pickResult.pickedMesh;
  21971. if (this._pickedDownMesh === this._pickedUpMesh) {
  21972. if (this.onPointerPick) {
  21973. this.onPointerPick(evt, pickResult);
  21974. }
  21975. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21976. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21977. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21978. this.onPointerObservable.notifyObservers(pi, type);
  21979. }
  21980. }
  21981. if (pickResult.pickedMesh.actionManager) {
  21982. if (clickInfo.ignore) {
  21983. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21984. }
  21985. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21986. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21987. }
  21988. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21989. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21990. }
  21991. }
  21992. }
  21993. if (this._pickedDownMesh &&
  21994. this._pickedDownMesh.actionManager &&
  21995. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  21996. this._pickedDownMesh !== this._pickedUpMesh) {
  21997. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  21998. }
  21999. if (this.onPointerUp) {
  22000. this.onPointerUp(evt, pickResult);
  22001. }
  22002. if (this.onPointerObservable.hasObservers()) {
  22003. if (!clickInfo.ignore) {
  22004. if (!clickInfo.hasSwiped) {
  22005. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22006. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22007. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22008. this.onPointerObservable.notifyObservers(pi, type);
  22009. }
  22010. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22011. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22012. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22013. this.onPointerObservable.notifyObservers(pi, type);
  22014. }
  22015. }
  22016. }
  22017. else {
  22018. var type = BABYLON.PointerEventTypes.POINTERUP;
  22019. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22020. this.onPointerObservable.notifyObservers(pi, type);
  22021. }
  22022. }
  22023. return this;
  22024. };
  22025. /**
  22026. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22027. * @param attachUp defines if you want to attach events to pointerup
  22028. * @param attachDown defines if you want to attach events to pointerdown
  22029. * @param attachMove defines if you want to attach events to pointermove
  22030. */
  22031. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22032. var _this = this;
  22033. if (attachUp === void 0) { attachUp = true; }
  22034. if (attachDown === void 0) { attachDown = true; }
  22035. if (attachMove === void 0) { attachMove = true; }
  22036. this._initActionManager = function (act, clickInfo) {
  22037. if (!_this._meshPickProceed) {
  22038. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22039. _this._currentPickResult = pickResult;
  22040. if (pickResult) {
  22041. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22042. }
  22043. _this._meshPickProceed = true;
  22044. }
  22045. return act;
  22046. };
  22047. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22048. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22049. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22050. btn !== _this._previousButtonPressed) {
  22051. _this._doubleClickOccured = false;
  22052. clickInfo.singleClick = true;
  22053. clickInfo.ignore = false;
  22054. cb(clickInfo, _this._currentPickResult);
  22055. }
  22056. };
  22057. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22058. var clickInfo = new ClickInfo();
  22059. _this._currentPickResult = null;
  22060. var act = null;
  22061. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22062. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22063. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22064. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22065. act = _this._initActionManager(act, clickInfo);
  22066. if (act)
  22067. checkPicking = act.hasPickTriggers;
  22068. }
  22069. if (checkPicking) {
  22070. var btn = evt.button;
  22071. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22072. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22073. if (!clickInfo.hasSwiped) {
  22074. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22075. if (!checkSingleClickImmediately) {
  22076. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22077. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22078. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22079. act = _this._initActionManager(act, clickInfo);
  22080. if (act)
  22081. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22082. }
  22083. }
  22084. if (checkSingleClickImmediately) {
  22085. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22086. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22087. btn !== _this._previousButtonPressed) {
  22088. clickInfo.singleClick = true;
  22089. cb(clickInfo, _this._currentPickResult);
  22090. }
  22091. }
  22092. else {
  22093. // wait that no double click has been raised during the double click delay
  22094. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22095. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22096. }
  22097. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22098. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22099. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22100. act = _this._initActionManager(act, clickInfo);
  22101. if (act)
  22102. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22103. }
  22104. if (checkDoubleClick) {
  22105. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22106. if (btn === _this._previousButtonPressed &&
  22107. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22108. !_this._doubleClickOccured) {
  22109. // pointer has not moved for 2 clicks, it's a double click
  22110. if (!clickInfo.hasSwiped &&
  22111. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22112. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22113. _this._previousStartingPointerTime = 0;
  22114. _this._doubleClickOccured = true;
  22115. clickInfo.doubleClick = true;
  22116. clickInfo.ignore = false;
  22117. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22118. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22119. }
  22120. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22121. cb(clickInfo, _this._currentPickResult);
  22122. }
  22123. else {
  22124. _this._doubleClickOccured = false;
  22125. _this._previousStartingPointerTime = _this._startingPointerTime;
  22126. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22127. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22128. _this._previousButtonPressed = btn;
  22129. if (Scene.ExclusiveDoubleClickMode) {
  22130. if (_this._previousDelayedSimpleClickTimeout) {
  22131. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22132. }
  22133. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22134. cb(clickInfo, _this._previousPickResult);
  22135. }
  22136. else {
  22137. cb(clickInfo, _this._currentPickResult);
  22138. }
  22139. }
  22140. }
  22141. else {
  22142. _this._doubleClickOccured = false;
  22143. _this._previousStartingPointerTime = _this._startingPointerTime;
  22144. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22145. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22146. _this._previousButtonPressed = btn;
  22147. }
  22148. }
  22149. }
  22150. }
  22151. clickInfo.ignore = true;
  22152. cb(clickInfo, _this._currentPickResult);
  22153. };
  22154. this._spritePredicate = function (sprite) {
  22155. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22156. };
  22157. this._onPointerMove = function (evt) {
  22158. _this._updatePointerPosition(evt);
  22159. // PreObservable support
  22160. if (_this.onPrePointerObservable.hasObservers()) {
  22161. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22162. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22163. _this.onPrePointerObservable.notifyObservers(pi, type);
  22164. if (pi.skipOnPointerObservable) {
  22165. return;
  22166. }
  22167. }
  22168. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22169. return;
  22170. }
  22171. if (!_this.pointerMovePredicate) {
  22172. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22173. }
  22174. // Meshes
  22175. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22176. _this._processPointerMove(pickResult, evt);
  22177. };
  22178. this._onPointerDown = function (evt) {
  22179. _this._totalPointersPressed++;
  22180. _this._pickedDownMesh = null;
  22181. _this._meshPickProceed = false;
  22182. _this._updatePointerPosition(evt);
  22183. if (_this.preventDefaultOnPointerDown && canvas) {
  22184. evt.preventDefault();
  22185. canvas.focus();
  22186. }
  22187. // PreObservable support
  22188. if (_this.onPrePointerObservable.hasObservers()) {
  22189. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22190. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22191. _this.onPrePointerObservable.notifyObservers(pi, type);
  22192. if (pi.skipOnPointerObservable) {
  22193. return;
  22194. }
  22195. }
  22196. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22197. return;
  22198. }
  22199. _this._startingPointerPosition.x = _this._pointerX;
  22200. _this._startingPointerPosition.y = _this._pointerY;
  22201. _this._startingPointerTime = new Date().getTime();
  22202. if (!_this.pointerDownPredicate) {
  22203. _this.pointerDownPredicate = function (mesh) {
  22204. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22205. };
  22206. }
  22207. // Meshes
  22208. _this._pickedDownMesh = null;
  22209. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22210. _this._processPointerDown(pickResult, evt);
  22211. // Sprites
  22212. _this._pickedDownSprite = null;
  22213. if (_this.spriteManagers.length > 0) {
  22214. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22215. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22216. if (pickResult.pickedSprite.actionManager) {
  22217. _this._pickedDownSprite = pickResult.pickedSprite;
  22218. switch (evt.button) {
  22219. case 0:
  22220. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22221. break;
  22222. case 1:
  22223. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22224. break;
  22225. case 2:
  22226. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22227. break;
  22228. }
  22229. if (pickResult.pickedSprite.actionManager) {
  22230. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22231. }
  22232. }
  22233. }
  22234. }
  22235. };
  22236. this._onPointerUp = function (evt) {
  22237. if (_this._totalPointersPressed === 0) {
  22238. return; // So we need to test it the pointer down was pressed before.
  22239. }
  22240. _this._totalPointersPressed--;
  22241. _this._pickedUpMesh = null;
  22242. _this._meshPickProceed = false;
  22243. _this._updatePointerPosition(evt);
  22244. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22245. // PreObservable support
  22246. if (_this.onPrePointerObservable.hasObservers()) {
  22247. if (!clickInfo.ignore) {
  22248. if (!clickInfo.hasSwiped) {
  22249. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22250. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22251. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22252. _this.onPrePointerObservable.notifyObservers(pi, type);
  22253. if (pi.skipOnPointerObservable) {
  22254. return;
  22255. }
  22256. }
  22257. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22258. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22259. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22260. _this.onPrePointerObservable.notifyObservers(pi, type);
  22261. if (pi.skipOnPointerObservable) {
  22262. return;
  22263. }
  22264. }
  22265. }
  22266. }
  22267. else {
  22268. var type = BABYLON.PointerEventTypes.POINTERUP;
  22269. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22270. _this.onPrePointerObservable.notifyObservers(pi, type);
  22271. if (pi.skipOnPointerObservable) {
  22272. return;
  22273. }
  22274. }
  22275. }
  22276. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22277. return;
  22278. }
  22279. if (!_this.pointerUpPredicate) {
  22280. _this.pointerUpPredicate = function (mesh) {
  22281. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22282. };
  22283. }
  22284. // Meshes
  22285. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22286. _this._initActionManager(null, clickInfo);
  22287. }
  22288. if (!pickResult) {
  22289. pickResult = _this._currentPickResult;
  22290. }
  22291. _this._processPointerUp(pickResult, evt, clickInfo);
  22292. // Sprites
  22293. if (_this.spriteManagers.length > 0) {
  22294. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22295. if (spritePickResult) {
  22296. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22297. if (spritePickResult.pickedSprite.actionManager) {
  22298. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22299. if (spritePickResult.pickedSprite.actionManager) {
  22300. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22301. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22302. }
  22303. }
  22304. }
  22305. }
  22306. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22307. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22308. }
  22309. }
  22310. }
  22311. _this._previousPickResult = _this._currentPickResult;
  22312. });
  22313. };
  22314. this._onKeyDown = function (evt) {
  22315. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22316. if (_this.onPreKeyboardObservable.hasObservers()) {
  22317. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22318. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22319. if (pi.skipOnPointerObservable) {
  22320. return;
  22321. }
  22322. }
  22323. if (_this.onKeyboardObservable.hasObservers()) {
  22324. var pi = new BABYLON.KeyboardInfo(type, evt);
  22325. _this.onKeyboardObservable.notifyObservers(pi, type);
  22326. }
  22327. if (_this.actionManager) {
  22328. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22329. }
  22330. };
  22331. this._onKeyUp = function (evt) {
  22332. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22333. if (_this.onPreKeyboardObservable.hasObservers()) {
  22334. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22335. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22336. if (pi.skipOnPointerObservable) {
  22337. return;
  22338. }
  22339. }
  22340. if (_this.onKeyboardObservable.hasObservers()) {
  22341. var pi = new BABYLON.KeyboardInfo(type, evt);
  22342. _this.onKeyboardObservable.notifyObservers(pi, type);
  22343. }
  22344. if (_this.actionManager) {
  22345. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22346. }
  22347. };
  22348. var engine = this.getEngine();
  22349. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22350. if (!canvas) {
  22351. return;
  22352. }
  22353. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22354. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22355. });
  22356. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22357. if (!canvas) {
  22358. return;
  22359. }
  22360. canvas.removeEventListener("keydown", _this._onKeyDown);
  22361. canvas.removeEventListener("keyup", _this._onKeyUp);
  22362. });
  22363. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22364. var canvas = this._engine.getRenderingCanvas();
  22365. if (!canvas) {
  22366. return;
  22367. }
  22368. if (attachMove) {
  22369. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22370. // Wheel
  22371. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22372. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22373. }
  22374. if (attachDown) {
  22375. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22376. }
  22377. if (attachUp) {
  22378. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22379. }
  22380. canvas.tabIndex = 1;
  22381. };
  22382. Scene.prototype.detachControl = function () {
  22383. var engine = this.getEngine();
  22384. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22385. var canvas = engine.getRenderingCanvas();
  22386. if (!canvas) {
  22387. return;
  22388. }
  22389. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22390. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22391. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22392. if (this._onCanvasBlurObserver) {
  22393. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22394. }
  22395. if (this._onCanvasFocusObserver) {
  22396. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22397. }
  22398. // Wheel
  22399. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22400. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22401. // Keyboard
  22402. canvas.removeEventListener("keydown", this._onKeyDown);
  22403. canvas.removeEventListener("keyup", this._onKeyUp);
  22404. // Observables
  22405. this.onKeyboardObservable.clear();
  22406. this.onPreKeyboardObservable.clear();
  22407. this.onPointerObservable.clear();
  22408. this.onPrePointerObservable.clear();
  22409. };
  22410. /**
  22411. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22412. * Delay loaded resources are not taking in account
  22413. * @return true if all required resources are ready
  22414. */
  22415. Scene.prototype.isReady = function () {
  22416. if (this._isDisposed) {
  22417. return false;
  22418. }
  22419. if (this._pendingData.length > 0) {
  22420. return false;
  22421. }
  22422. var index;
  22423. var engine = this.getEngine();
  22424. // Geometries
  22425. for (index = 0; index < this._geometries.length; index++) {
  22426. var geometry = this._geometries[index];
  22427. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22428. return false;
  22429. }
  22430. }
  22431. // Meshes
  22432. for (index = 0; index < this.meshes.length; index++) {
  22433. var mesh = this.meshes[index];
  22434. if (!mesh.isEnabled()) {
  22435. continue;
  22436. }
  22437. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22438. continue;
  22439. }
  22440. if (!mesh.isReady(true)) {
  22441. return false;
  22442. }
  22443. // Effect layers
  22444. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22445. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22446. var layer = _a[_i];
  22447. if (!layer.hasMesh(mesh)) {
  22448. continue;
  22449. }
  22450. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22451. var subMesh = _c[_b];
  22452. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22453. return false;
  22454. }
  22455. }
  22456. }
  22457. }
  22458. return true;
  22459. };
  22460. Scene.prototype.resetCachedMaterial = function () {
  22461. this._cachedMaterial = null;
  22462. this._cachedEffect = null;
  22463. this._cachedVisibility = null;
  22464. };
  22465. Scene.prototype.registerBeforeRender = function (func) {
  22466. this.onBeforeRenderObservable.add(func);
  22467. };
  22468. Scene.prototype.unregisterBeforeRender = function (func) {
  22469. this.onBeforeRenderObservable.removeCallback(func);
  22470. };
  22471. Scene.prototype.registerAfterRender = function (func) {
  22472. this.onAfterRenderObservable.add(func);
  22473. };
  22474. Scene.prototype.unregisterAfterRender = function (func) {
  22475. this.onAfterRenderObservable.removeCallback(func);
  22476. };
  22477. Scene.prototype._executeOnceBeforeRender = function (func) {
  22478. var _this = this;
  22479. var execFunc = function () {
  22480. func();
  22481. setTimeout(function () {
  22482. _this.unregisterBeforeRender(execFunc);
  22483. });
  22484. };
  22485. this.registerBeforeRender(execFunc);
  22486. };
  22487. /**
  22488. * The provided function will run before render once and will be disposed afterwards.
  22489. * A timeout delay can be provided so that the function will be executed in N ms.
  22490. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22491. * @param func The function to be executed.
  22492. * @param timeout optional delay in ms
  22493. */
  22494. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22495. var _this = this;
  22496. if (timeout !== undefined) {
  22497. setTimeout(function () {
  22498. _this._executeOnceBeforeRender(func);
  22499. }, timeout);
  22500. }
  22501. else {
  22502. this._executeOnceBeforeRender(func);
  22503. }
  22504. };
  22505. Scene.prototype._addPendingData = function (data) {
  22506. this._pendingData.push(data);
  22507. };
  22508. Scene.prototype._removePendingData = function (data) {
  22509. var wasLoading = this.isLoading;
  22510. var index = this._pendingData.indexOf(data);
  22511. if (index !== -1) {
  22512. this._pendingData.splice(index, 1);
  22513. }
  22514. if (wasLoading && !this.isLoading) {
  22515. this.onDataLoadedObservable.notifyObservers(this);
  22516. }
  22517. };
  22518. Scene.prototype.getWaitingItemsCount = function () {
  22519. return this._pendingData.length;
  22520. };
  22521. Object.defineProperty(Scene.prototype, "isLoading", {
  22522. get: function () {
  22523. return this._pendingData.length > 0;
  22524. },
  22525. enumerable: true,
  22526. configurable: true
  22527. });
  22528. /**
  22529. * Registers a function to be executed when the scene is ready.
  22530. * @param {Function} func - the function to be executed.
  22531. */
  22532. Scene.prototype.executeWhenReady = function (func) {
  22533. var _this = this;
  22534. this.onReadyObservable.add(func);
  22535. if (this._executeWhenReadyTimeoutId !== -1) {
  22536. return;
  22537. }
  22538. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22539. _this._checkIsReady();
  22540. }, 150);
  22541. };
  22542. /**
  22543. * Returns a promise that resolves when the scene is ready.
  22544. * @returns A promise that resolves when the scene is ready.
  22545. */
  22546. Scene.prototype.whenReadyAsync = function () {
  22547. var _this = this;
  22548. return new Promise(function (resolve) {
  22549. _this.executeWhenReady(function () {
  22550. resolve();
  22551. });
  22552. });
  22553. };
  22554. Scene.prototype._checkIsReady = function () {
  22555. var _this = this;
  22556. if (this.isReady()) {
  22557. this.onReadyObservable.notifyObservers(this);
  22558. this.onReadyObservable.clear();
  22559. this._executeWhenReadyTimeoutId = -1;
  22560. return;
  22561. }
  22562. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22563. _this._checkIsReady();
  22564. }, 150);
  22565. };
  22566. // Animations
  22567. /**
  22568. * Will start the animation sequence of a given target
  22569. * @param target - the target
  22570. * @param {number} from - from which frame should animation start
  22571. * @param {number} to - till which frame should animation run.
  22572. * @param {boolean} [loop] - should the animation loop
  22573. * @param {number} [speedRatio] - the speed in which to run the animation
  22574. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22575. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22576. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22577. * See BABYLON.Animatable
  22578. */
  22579. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22580. if (speedRatio === void 0) { speedRatio = 1.0; }
  22581. if (from > to && speedRatio > 0) {
  22582. speedRatio *= -1;
  22583. }
  22584. this.stopAnimation(target);
  22585. if (!animatable) {
  22586. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22587. }
  22588. // Local animations
  22589. if (target.animations) {
  22590. animatable.appendAnimations(target, target.animations);
  22591. }
  22592. // Children animations
  22593. if (target.getAnimatables) {
  22594. var animatables = target.getAnimatables();
  22595. for (var index = 0; index < animatables.length; index++) {
  22596. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22597. }
  22598. }
  22599. animatable.reset();
  22600. return animatable;
  22601. };
  22602. /**
  22603. * Begin a new animation on a given node
  22604. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22605. * @param {BABYLON.Animation[]} defines the list of animations to start
  22606. * @param {number} from defines the initial value
  22607. * @param {number} to defines the final value
  22608. * @param {boolean} loop defines if you want animation to loop (off by default)
  22609. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22610. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22611. * @returns the list of created animatables
  22612. */
  22613. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22614. if (speedRatio === undefined) {
  22615. speedRatio = 1.0;
  22616. }
  22617. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22618. return animatable;
  22619. };
  22620. /**
  22621. * Begin a new animation on a given node and its hierarchy
  22622. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22623. * @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.
  22624. * @param {BABYLON.Animation[]} defines the list of animations to start
  22625. * @param {number} from defines the initial value
  22626. * @param {number} to defines the final value
  22627. * @param {boolean} loop defines if you want animation to loop (off by default)
  22628. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22629. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22630. * @returns the list of animatables created for all nodes
  22631. */
  22632. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22633. var children = target.getDescendants(directDescendantsOnly);
  22634. var result = [];
  22635. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22636. var child = children_1[_i];
  22637. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22638. }
  22639. return result;
  22640. };
  22641. Scene.prototype.getAnimatableByTarget = function (target) {
  22642. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22643. if (this._activeAnimatables[index].target === target) {
  22644. return this._activeAnimatables[index];
  22645. }
  22646. }
  22647. return null;
  22648. };
  22649. Object.defineProperty(Scene.prototype, "animatables", {
  22650. get: function () {
  22651. return this._activeAnimatables;
  22652. },
  22653. enumerable: true,
  22654. configurable: true
  22655. });
  22656. /**
  22657. * Will stop the animation of the given target
  22658. * @param target - the target
  22659. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22660. * @see beginAnimation
  22661. */
  22662. Scene.prototype.stopAnimation = function (target, animationName) {
  22663. var animatable = this.getAnimatableByTarget(target);
  22664. if (animatable) {
  22665. animatable.stop(animationName);
  22666. }
  22667. };
  22668. /**
  22669. * Stops and removes all animations that have been applied to the scene
  22670. */
  22671. Scene.prototype.stopAllAnimations = function () {
  22672. if (this._activeAnimatables) {
  22673. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22674. this._activeAnimatables[i].stop();
  22675. }
  22676. this._activeAnimatables = [];
  22677. }
  22678. };
  22679. Scene.prototype._animate = function () {
  22680. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22681. return;
  22682. }
  22683. // Getting time
  22684. var now = BABYLON.Tools.Now;
  22685. if (!this._animationTimeLast) {
  22686. if (this._pendingData.length > 0) {
  22687. return;
  22688. }
  22689. this._animationTimeLast = now;
  22690. }
  22691. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22692. this._animationTime += deltaTime;
  22693. this._animationTimeLast = now;
  22694. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22695. this._activeAnimatables[index]._animate(this._animationTime);
  22696. }
  22697. };
  22698. // Matrix
  22699. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22700. this._useAlternateCameraConfiguration = active;
  22701. };
  22702. Scene.prototype.getViewMatrix = function () {
  22703. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22704. };
  22705. Scene.prototype.getProjectionMatrix = function () {
  22706. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22707. };
  22708. Scene.prototype.getTransformMatrix = function () {
  22709. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22710. };
  22711. Scene.prototype.setTransformMatrix = function (view, projection) {
  22712. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22713. return;
  22714. }
  22715. this._viewUpdateFlag = view.updateFlag;
  22716. this._projectionUpdateFlag = projection.updateFlag;
  22717. this._viewMatrix = view;
  22718. this._projectionMatrix = projection;
  22719. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22720. // Update frustum
  22721. if (!this._frustumPlanes) {
  22722. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22723. }
  22724. else {
  22725. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22726. }
  22727. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22728. var otherCamera = this.activeCamera._alternateCamera;
  22729. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22730. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22731. }
  22732. if (this._sceneUbo.useUbo) {
  22733. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22734. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22735. this._sceneUbo.update();
  22736. }
  22737. };
  22738. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22739. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22740. return;
  22741. }
  22742. this._alternateViewUpdateFlag = view.updateFlag;
  22743. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22744. this._alternateViewMatrix = view;
  22745. this._alternateProjectionMatrix = projection;
  22746. if (!this._alternateTransformMatrix) {
  22747. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22748. }
  22749. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22750. if (!this._alternateSceneUbo) {
  22751. this._createAlternateUbo();
  22752. }
  22753. if (this._alternateSceneUbo.useUbo) {
  22754. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22755. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22756. this._alternateSceneUbo.update();
  22757. }
  22758. };
  22759. Scene.prototype.getSceneUniformBuffer = function () {
  22760. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22761. };
  22762. // Methods
  22763. Scene.prototype.getUniqueId = function () {
  22764. var result = Scene._uniqueIdCounter;
  22765. Scene._uniqueIdCounter++;
  22766. return result;
  22767. };
  22768. Scene.prototype.addMesh = function (newMesh) {
  22769. this.meshes.push(newMesh);
  22770. //notify the collision coordinator
  22771. if (this.collisionCoordinator) {
  22772. this.collisionCoordinator.onMeshAdded(newMesh);
  22773. }
  22774. newMesh._resyncLightSources();
  22775. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22776. };
  22777. Scene.prototype.removeMesh = function (toRemove) {
  22778. var index = this.meshes.indexOf(toRemove);
  22779. if (index !== -1) {
  22780. // Remove from the scene if mesh found
  22781. this.meshes.splice(index, 1);
  22782. }
  22783. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22784. return index;
  22785. };
  22786. Scene.prototype.addTransformNode = function (newTransformNode) {
  22787. this.transformNodes.push(newTransformNode);
  22788. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22789. };
  22790. Scene.prototype.removeTransformNode = function (toRemove) {
  22791. var index = this.transformNodes.indexOf(toRemove);
  22792. if (index !== -1) {
  22793. // Remove from the scene if found
  22794. this.transformNodes.splice(index, 1);
  22795. }
  22796. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22797. return index;
  22798. };
  22799. Scene.prototype.removeSkeleton = function (toRemove) {
  22800. var index = this.skeletons.indexOf(toRemove);
  22801. if (index !== -1) {
  22802. // Remove from the scene if found
  22803. this.skeletons.splice(index, 1);
  22804. }
  22805. return index;
  22806. };
  22807. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22808. var index = this.morphTargetManagers.indexOf(toRemove);
  22809. if (index !== -1) {
  22810. // Remove from the scene if found
  22811. this.morphTargetManagers.splice(index, 1);
  22812. }
  22813. return index;
  22814. };
  22815. Scene.prototype.removeLight = function (toRemove) {
  22816. var index = this.lights.indexOf(toRemove);
  22817. if (index !== -1) {
  22818. // Remove from meshes
  22819. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22820. var mesh = _a[_i];
  22821. mesh._removeLightSource(toRemove);
  22822. }
  22823. // Remove from the scene if mesh found
  22824. this.lights.splice(index, 1);
  22825. this.sortLightsByPriority();
  22826. }
  22827. this.onLightRemovedObservable.notifyObservers(toRemove);
  22828. return index;
  22829. };
  22830. Scene.prototype.removeCamera = function (toRemove) {
  22831. var index = this.cameras.indexOf(toRemove);
  22832. if (index !== -1) {
  22833. // Remove from the scene if mesh found
  22834. this.cameras.splice(index, 1);
  22835. }
  22836. // Remove from activeCameras
  22837. var index2 = this.activeCameras.indexOf(toRemove);
  22838. if (index2 !== -1) {
  22839. // Remove from the scene if mesh found
  22840. this.activeCameras.splice(index2, 1);
  22841. }
  22842. // Reset the activeCamera
  22843. if (this.activeCamera === toRemove) {
  22844. if (this.cameras.length > 0) {
  22845. this.activeCamera = this.cameras[0];
  22846. }
  22847. else {
  22848. this.activeCamera = null;
  22849. }
  22850. }
  22851. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22852. return index;
  22853. };
  22854. Scene.prototype.removeParticleSystem = function (toRemove) {
  22855. var index = this.particleSystems.indexOf(toRemove);
  22856. if (index !== -1) {
  22857. this.particleSystems.splice(index, 1);
  22858. }
  22859. return index;
  22860. };
  22861. ;
  22862. Scene.prototype.removeAnimation = function (toRemove) {
  22863. var index = this.animations.indexOf(toRemove);
  22864. if (index !== -1) {
  22865. this.animations.splice(index, 1);
  22866. }
  22867. return index;
  22868. };
  22869. ;
  22870. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22871. var index = this.multiMaterials.indexOf(toRemove);
  22872. if (index !== -1) {
  22873. this.multiMaterials.splice(index, 1);
  22874. }
  22875. return index;
  22876. };
  22877. ;
  22878. Scene.prototype.removeMaterial = function (toRemove) {
  22879. var index = this.materials.indexOf(toRemove);
  22880. if (index !== -1) {
  22881. this.materials.splice(index, 1);
  22882. }
  22883. return index;
  22884. };
  22885. ;
  22886. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22887. var index = this.lensFlareSystems.indexOf(toRemove);
  22888. if (index !== -1) {
  22889. this.lensFlareSystems.splice(index, 1);
  22890. }
  22891. return index;
  22892. };
  22893. ;
  22894. Scene.prototype.removeActionManager = function (toRemove) {
  22895. var index = this._actionManagers.indexOf(toRemove);
  22896. if (index !== -1) {
  22897. this._actionManagers.splice(index, 1);
  22898. }
  22899. return index;
  22900. };
  22901. ;
  22902. Scene.prototype.addLight = function (newLight) {
  22903. this.lights.push(newLight);
  22904. this.sortLightsByPriority();
  22905. // Add light to all meshes (To support if the light is removed and then readded)
  22906. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22907. var mesh = _a[_i];
  22908. if (mesh._lightSources.indexOf(newLight) === -1) {
  22909. mesh._lightSources.push(newLight);
  22910. mesh._resyncLightSources();
  22911. }
  22912. }
  22913. this.onNewLightAddedObservable.notifyObservers(newLight);
  22914. };
  22915. Scene.prototype.sortLightsByPriority = function () {
  22916. if (this.requireLightSorting) {
  22917. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22918. }
  22919. };
  22920. Scene.prototype.addCamera = function (newCamera) {
  22921. this.cameras.push(newCamera);
  22922. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22923. };
  22924. Scene.prototype.addSkeleton = function (newSkeleton) {
  22925. this.skeletons.push(newSkeleton);
  22926. };
  22927. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22928. this.particleSystems.push(newParticleSystem);
  22929. };
  22930. Scene.prototype.addAnimation = function (newAnimation) {
  22931. this.animations.push(newAnimation);
  22932. };
  22933. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22934. this.multiMaterials.push(newMultiMaterial);
  22935. };
  22936. Scene.prototype.addMaterial = function (newMaterial) {
  22937. this.materials.push(newMaterial);
  22938. };
  22939. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22940. this.morphTargetManagers.push(newMorphTargetManager);
  22941. };
  22942. Scene.prototype.addGeometry = function (newGeometrie) {
  22943. this._geometries.push(newGeometrie);
  22944. };
  22945. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22946. this.lensFlareSystems.push(newLensFlareSystem);
  22947. };
  22948. Scene.prototype.addActionManager = function (newActionManager) {
  22949. this._actionManagers.push(newActionManager);
  22950. };
  22951. /**
  22952. * Switch active camera
  22953. * @param {Camera} newCamera - new active camera
  22954. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22955. */
  22956. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22957. if (attachControl === void 0) { attachControl = true; }
  22958. var canvas = this._engine.getRenderingCanvas();
  22959. if (!canvas) {
  22960. return;
  22961. }
  22962. if (this.activeCamera) {
  22963. this.activeCamera.detachControl(canvas);
  22964. }
  22965. this.activeCamera = newCamera;
  22966. if (attachControl) {
  22967. newCamera.attachControl(canvas);
  22968. }
  22969. };
  22970. /**
  22971. * sets the active camera of the scene using its ID
  22972. * @param {string} id - the camera's ID
  22973. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22974. * @see activeCamera
  22975. */
  22976. Scene.prototype.setActiveCameraByID = function (id) {
  22977. var camera = this.getCameraByID(id);
  22978. if (camera) {
  22979. this.activeCamera = camera;
  22980. return camera;
  22981. }
  22982. return null;
  22983. };
  22984. /**
  22985. * sets the active camera of the scene using its name
  22986. * @param {string} name - the camera's name
  22987. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22988. * @see activeCamera
  22989. */
  22990. Scene.prototype.setActiveCameraByName = function (name) {
  22991. var camera = this.getCameraByName(name);
  22992. if (camera) {
  22993. this.activeCamera = camera;
  22994. return camera;
  22995. }
  22996. return null;
  22997. };
  22998. /**
  22999. * get an animation group using its name
  23000. * @param {string} the material's name
  23001. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23002. */
  23003. Scene.prototype.getAnimationGroupByName = function (name) {
  23004. for (var index = 0; index < this.animationGroups.length; index++) {
  23005. if (this.animationGroups[index].name === name) {
  23006. return this.animationGroups[index];
  23007. }
  23008. }
  23009. return null;
  23010. };
  23011. /**
  23012. * get a material using its id
  23013. * @param {string} the material's ID
  23014. * @return {BABYLON.Material|null} the material or null if none found.
  23015. */
  23016. Scene.prototype.getMaterialByID = function (id) {
  23017. for (var index = 0; index < this.materials.length; index++) {
  23018. if (this.materials[index].id === id) {
  23019. return this.materials[index];
  23020. }
  23021. }
  23022. return null;
  23023. };
  23024. /**
  23025. * get a material using its name
  23026. * @param {string} the material's name
  23027. * @return {BABYLON.Material|null} the material or null if none found.
  23028. */
  23029. Scene.prototype.getMaterialByName = function (name) {
  23030. for (var index = 0; index < this.materials.length; index++) {
  23031. if (this.materials[index].name === name) {
  23032. return this.materials[index];
  23033. }
  23034. }
  23035. return null;
  23036. };
  23037. Scene.prototype.getLensFlareSystemByName = function (name) {
  23038. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23039. if (this.lensFlareSystems[index].name === name) {
  23040. return this.lensFlareSystems[index];
  23041. }
  23042. }
  23043. return null;
  23044. };
  23045. Scene.prototype.getLensFlareSystemByID = function (id) {
  23046. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23047. if (this.lensFlareSystems[index].id === id) {
  23048. return this.lensFlareSystems[index];
  23049. }
  23050. }
  23051. return null;
  23052. };
  23053. Scene.prototype.getCameraByID = function (id) {
  23054. for (var index = 0; index < this.cameras.length; index++) {
  23055. if (this.cameras[index].id === id) {
  23056. return this.cameras[index];
  23057. }
  23058. }
  23059. return null;
  23060. };
  23061. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23062. for (var index = 0; index < this.cameras.length; index++) {
  23063. if (this.cameras[index].uniqueId === uniqueId) {
  23064. return this.cameras[index];
  23065. }
  23066. }
  23067. return null;
  23068. };
  23069. /**
  23070. * get a camera using its name
  23071. * @param {string} the camera's name
  23072. * @return {BABYLON.Camera|null} the camera or null if none found.
  23073. */
  23074. Scene.prototype.getCameraByName = function (name) {
  23075. for (var index = 0; index < this.cameras.length; index++) {
  23076. if (this.cameras[index].name === name) {
  23077. return this.cameras[index];
  23078. }
  23079. }
  23080. return null;
  23081. };
  23082. /**
  23083. * get a bone using its id
  23084. * @param {string} the bone's id
  23085. * @return {BABYLON.Bone|null} the bone or null if not found
  23086. */
  23087. Scene.prototype.getBoneByID = function (id) {
  23088. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23089. var skeleton = this.skeletons[skeletonIndex];
  23090. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23091. if (skeleton.bones[boneIndex].id === id) {
  23092. return skeleton.bones[boneIndex];
  23093. }
  23094. }
  23095. }
  23096. return null;
  23097. };
  23098. /**
  23099. * get a bone using its id
  23100. * @param {string} the bone's name
  23101. * @return {BABYLON.Bone|null} the bone or null if not found
  23102. */
  23103. Scene.prototype.getBoneByName = function (name) {
  23104. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23105. var skeleton = this.skeletons[skeletonIndex];
  23106. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23107. if (skeleton.bones[boneIndex].name === name) {
  23108. return skeleton.bones[boneIndex];
  23109. }
  23110. }
  23111. }
  23112. return null;
  23113. };
  23114. /**
  23115. * get a light node using its name
  23116. * @param {string} the light's name
  23117. * @return {BABYLON.Light|null} the light or null if none found.
  23118. */
  23119. Scene.prototype.getLightByName = function (name) {
  23120. for (var index = 0; index < this.lights.length; index++) {
  23121. if (this.lights[index].name === name) {
  23122. return this.lights[index];
  23123. }
  23124. }
  23125. return null;
  23126. };
  23127. /**
  23128. * get a light node using its ID
  23129. * @param {string} the light's id
  23130. * @return {BABYLON.Light|null} the light or null if none found.
  23131. */
  23132. Scene.prototype.getLightByID = function (id) {
  23133. for (var index = 0; index < this.lights.length; index++) {
  23134. if (this.lights[index].id === id) {
  23135. return this.lights[index];
  23136. }
  23137. }
  23138. return null;
  23139. };
  23140. /**
  23141. * get a light node using its scene-generated unique ID
  23142. * @param {number} the light's unique id
  23143. * @return {BABYLON.Light|null} the light or null if none found.
  23144. */
  23145. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23146. for (var index = 0; index < this.lights.length; index++) {
  23147. if (this.lights[index].uniqueId === uniqueId) {
  23148. return this.lights[index];
  23149. }
  23150. }
  23151. return null;
  23152. };
  23153. /**
  23154. * get a particle system by id
  23155. * @param id {number} the particle system id
  23156. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23157. */
  23158. Scene.prototype.getParticleSystemByID = function (id) {
  23159. for (var index = 0; index < this.particleSystems.length; index++) {
  23160. if (this.particleSystems[index].id === id) {
  23161. return this.particleSystems[index];
  23162. }
  23163. }
  23164. return null;
  23165. };
  23166. /**
  23167. * get a geometry using its ID
  23168. * @param {string} the geometry's id
  23169. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23170. */
  23171. Scene.prototype.getGeometryByID = function (id) {
  23172. for (var index = 0; index < this._geometries.length; index++) {
  23173. if (this._geometries[index].id === id) {
  23174. return this._geometries[index];
  23175. }
  23176. }
  23177. return null;
  23178. };
  23179. /**
  23180. * add a new geometry to this scene.
  23181. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23182. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23183. * @return {boolean} was the geometry added or not
  23184. */
  23185. Scene.prototype.pushGeometry = function (geometry, force) {
  23186. if (!force && this.getGeometryByID(geometry.id)) {
  23187. return false;
  23188. }
  23189. this._geometries.push(geometry);
  23190. //notify the collision coordinator
  23191. if (this.collisionCoordinator) {
  23192. this.collisionCoordinator.onGeometryAdded(geometry);
  23193. }
  23194. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23195. return true;
  23196. };
  23197. /**
  23198. * Removes an existing geometry
  23199. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23200. * @return {boolean} was the geometry removed or not
  23201. */
  23202. Scene.prototype.removeGeometry = function (geometry) {
  23203. var index = this._geometries.indexOf(geometry);
  23204. if (index > -1) {
  23205. this._geometries.splice(index, 1);
  23206. //notify the collision coordinator
  23207. if (this.collisionCoordinator) {
  23208. this.collisionCoordinator.onGeometryDeleted(geometry);
  23209. }
  23210. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23211. return true;
  23212. }
  23213. return false;
  23214. };
  23215. Scene.prototype.getGeometries = function () {
  23216. return this._geometries;
  23217. };
  23218. /**
  23219. * Get the first added mesh found of a given ID
  23220. * @param {string} id - the id to search for
  23221. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23222. */
  23223. Scene.prototype.getMeshByID = function (id) {
  23224. for (var index = 0; index < this.meshes.length; index++) {
  23225. if (this.meshes[index].id === id) {
  23226. return this.meshes[index];
  23227. }
  23228. }
  23229. return null;
  23230. };
  23231. Scene.prototype.getMeshesByID = function (id) {
  23232. return this.meshes.filter(function (m) {
  23233. return m.id === id;
  23234. });
  23235. };
  23236. /**
  23237. * Get the first added transform node found of a given ID
  23238. * @param {string} id - the id to search for
  23239. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23240. */
  23241. Scene.prototype.getTransformNodeByID = function (id) {
  23242. for (var index = 0; index < this.transformNodes.length; index++) {
  23243. if (this.transformNodes[index].id === id) {
  23244. return this.transformNodes[index];
  23245. }
  23246. }
  23247. return null;
  23248. };
  23249. Scene.prototype.getTransformNodesByID = function (id) {
  23250. return this.transformNodes.filter(function (m) {
  23251. return m.id === id;
  23252. });
  23253. };
  23254. /**
  23255. * Get a mesh with its auto-generated unique id
  23256. * @param {number} uniqueId - the unique id to search for
  23257. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23258. */
  23259. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23260. for (var index = 0; index < this.meshes.length; index++) {
  23261. if (this.meshes[index].uniqueId === uniqueId) {
  23262. return this.meshes[index];
  23263. }
  23264. }
  23265. return null;
  23266. };
  23267. /**
  23268. * Get a the last added mesh found of a given ID
  23269. * @param {string} id - the id to search for
  23270. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23271. */
  23272. Scene.prototype.getLastMeshByID = function (id) {
  23273. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23274. if (this.meshes[index].id === id) {
  23275. return this.meshes[index];
  23276. }
  23277. }
  23278. return null;
  23279. };
  23280. /**
  23281. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23282. * @param {string} id - the id to search for
  23283. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23284. */
  23285. Scene.prototype.getLastEntryByID = function (id) {
  23286. var index;
  23287. for (index = this.meshes.length - 1; index >= 0; index--) {
  23288. if (this.meshes[index].id === id) {
  23289. return this.meshes[index];
  23290. }
  23291. }
  23292. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23293. if (this.transformNodes[index].id === id) {
  23294. return this.transformNodes[index];
  23295. }
  23296. }
  23297. for (index = this.cameras.length - 1; index >= 0; index--) {
  23298. if (this.cameras[index].id === id) {
  23299. return this.cameras[index];
  23300. }
  23301. }
  23302. for (index = this.lights.length - 1; index >= 0; index--) {
  23303. if (this.lights[index].id === id) {
  23304. return this.lights[index];
  23305. }
  23306. }
  23307. return null;
  23308. };
  23309. Scene.prototype.getNodeByID = function (id) {
  23310. var mesh = this.getMeshByID(id);
  23311. if (mesh) {
  23312. return mesh;
  23313. }
  23314. var light = this.getLightByID(id);
  23315. if (light) {
  23316. return light;
  23317. }
  23318. var camera = this.getCameraByID(id);
  23319. if (camera) {
  23320. return camera;
  23321. }
  23322. var bone = this.getBoneByID(id);
  23323. return bone;
  23324. };
  23325. Scene.prototype.getNodeByName = function (name) {
  23326. var mesh = this.getMeshByName(name);
  23327. if (mesh) {
  23328. return mesh;
  23329. }
  23330. var light = this.getLightByName(name);
  23331. if (light) {
  23332. return light;
  23333. }
  23334. var camera = this.getCameraByName(name);
  23335. if (camera) {
  23336. return camera;
  23337. }
  23338. var bone = this.getBoneByName(name);
  23339. return bone;
  23340. };
  23341. Scene.prototype.getMeshByName = function (name) {
  23342. for (var index = 0; index < this.meshes.length; index++) {
  23343. if (this.meshes[index].name === name) {
  23344. return this.meshes[index];
  23345. }
  23346. }
  23347. return null;
  23348. };
  23349. Scene.prototype.getTransformNodeByName = function (name) {
  23350. for (var index = 0; index < this.transformNodes.length; index++) {
  23351. if (this.transformNodes[index].name === name) {
  23352. return this.transformNodes[index];
  23353. }
  23354. }
  23355. return null;
  23356. };
  23357. Scene.prototype.getSoundByName = function (name) {
  23358. var index;
  23359. if (BABYLON.AudioEngine) {
  23360. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23361. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23362. return this.mainSoundTrack.soundCollection[index];
  23363. }
  23364. }
  23365. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23366. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23367. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23368. return this.soundTracks[sdIndex].soundCollection[index];
  23369. }
  23370. }
  23371. }
  23372. }
  23373. return null;
  23374. };
  23375. Scene.prototype.getLastSkeletonByID = function (id) {
  23376. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23377. if (this.skeletons[index].id === id) {
  23378. return this.skeletons[index];
  23379. }
  23380. }
  23381. return null;
  23382. };
  23383. Scene.prototype.getSkeletonById = function (id) {
  23384. for (var index = 0; index < this.skeletons.length; index++) {
  23385. if (this.skeletons[index].id === id) {
  23386. return this.skeletons[index];
  23387. }
  23388. }
  23389. return null;
  23390. };
  23391. Scene.prototype.getSkeletonByName = function (name) {
  23392. for (var index = 0; index < this.skeletons.length; index++) {
  23393. if (this.skeletons[index].name === name) {
  23394. return this.skeletons[index];
  23395. }
  23396. }
  23397. return null;
  23398. };
  23399. Scene.prototype.getMorphTargetManagerById = function (id) {
  23400. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23401. if (this.morphTargetManagers[index].uniqueId === id) {
  23402. return this.morphTargetManagers[index];
  23403. }
  23404. }
  23405. return null;
  23406. };
  23407. Scene.prototype.isActiveMesh = function (mesh) {
  23408. return (this._activeMeshes.indexOf(mesh) !== -1);
  23409. };
  23410. /**
  23411. * Return a the first highlight layer of the scene with a given name.
  23412. * @param name The name of the highlight layer to look for.
  23413. * @return The highlight layer if found otherwise null.
  23414. */
  23415. Scene.prototype.getHighlightLayerByName = function (name) {
  23416. for (var index = 0; index < this.effectLayers.length; index++) {
  23417. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23418. return this.effectLayers[index];
  23419. }
  23420. }
  23421. return null;
  23422. };
  23423. /**
  23424. * Return a the first highlight layer of the scene with a given name.
  23425. * @param name The name of the highlight layer to look for.
  23426. * @return The highlight layer if found otherwise null.
  23427. */
  23428. Scene.prototype.getGlowLayerByName = function (name) {
  23429. for (var index = 0; index < this.effectLayers.length; index++) {
  23430. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23431. return this.effectLayers[index];
  23432. }
  23433. }
  23434. return null;
  23435. };
  23436. Object.defineProperty(Scene.prototype, "uid", {
  23437. /**
  23438. * Return a unique id as a string which can serve as an identifier for the scene
  23439. */
  23440. get: function () {
  23441. if (!this._uid) {
  23442. this._uid = BABYLON.Tools.RandomId();
  23443. }
  23444. return this._uid;
  23445. },
  23446. enumerable: true,
  23447. configurable: true
  23448. });
  23449. /**
  23450. * Add an externaly attached data from its key.
  23451. * This method call will fail and return false, if such key already exists.
  23452. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23453. * @param key the unique key that identifies the data
  23454. * @param data the data object to associate to the key for this Engine instance
  23455. * @return true if no such key were already present and the data was added successfully, false otherwise
  23456. */
  23457. Scene.prototype.addExternalData = function (key, data) {
  23458. if (!this._externalData) {
  23459. this._externalData = new BABYLON.StringDictionary();
  23460. }
  23461. return this._externalData.add(key, data);
  23462. };
  23463. /**
  23464. * Get an externaly attached data from its key
  23465. * @param key the unique key that identifies the data
  23466. * @return the associated data, if present (can be null), or undefined if not present
  23467. */
  23468. Scene.prototype.getExternalData = function (key) {
  23469. if (!this._externalData) {
  23470. return null;
  23471. }
  23472. return this._externalData.get(key);
  23473. };
  23474. /**
  23475. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23476. * @param key the unique key that identifies the data
  23477. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23478. * @return the associated data, can be null if the factory returned null.
  23479. */
  23480. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23481. if (!this._externalData) {
  23482. this._externalData = new BABYLON.StringDictionary();
  23483. }
  23484. return this._externalData.getOrAddWithFactory(key, factory);
  23485. };
  23486. /**
  23487. * Remove an externaly attached data from the Engine instance
  23488. * @param key the unique key that identifies the data
  23489. * @return true if the data was successfully removed, false if it doesn't exist
  23490. */
  23491. Scene.prototype.removeExternalData = function (key) {
  23492. return this._externalData.remove(key);
  23493. };
  23494. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23495. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23496. if (mesh.showSubMeshesBoundingBox) {
  23497. var boundingInfo = subMesh.getBoundingInfo();
  23498. if (boundingInfo !== null && boundingInfo !== undefined) {
  23499. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23500. }
  23501. }
  23502. var material = subMesh.getMaterial();
  23503. if (material !== null && material !== undefined) {
  23504. // Render targets
  23505. if (material.getRenderTargetTextures !== undefined) {
  23506. if (this._processedMaterials.indexOf(material) === -1) {
  23507. this._processedMaterials.push(material);
  23508. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23509. }
  23510. }
  23511. // Dispatch
  23512. this._activeIndices.addCount(subMesh.indexCount, false);
  23513. this._renderingManager.dispatch(subMesh, mesh, material);
  23514. }
  23515. }
  23516. };
  23517. Scene.prototype._isInIntermediateRendering = function () {
  23518. return this._intermediateRendering;
  23519. };
  23520. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23521. this._activeMeshCandidateProvider = provider;
  23522. };
  23523. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23524. return this._activeMeshCandidateProvider;
  23525. };
  23526. /**
  23527. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23528. */
  23529. Scene.prototype.freezeActiveMeshes = function () {
  23530. this._evaluateActiveMeshes();
  23531. this._activeMeshesFrozen = true;
  23532. return this;
  23533. };
  23534. /**
  23535. * Use this function to restart evaluating active meshes on every frame
  23536. */
  23537. Scene.prototype.unfreezeActiveMeshes = function () {
  23538. this._activeMeshesFrozen = false;
  23539. return this;
  23540. };
  23541. Scene.prototype._evaluateActiveMeshes = function () {
  23542. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23543. return;
  23544. }
  23545. if (!this.activeCamera) {
  23546. return;
  23547. }
  23548. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23549. this.activeCamera._activeMeshes.reset();
  23550. this._activeMeshes.reset();
  23551. this._renderingManager.reset();
  23552. this._processedMaterials.reset();
  23553. this._activeParticleSystems.reset();
  23554. this._activeSkeletons.reset();
  23555. this._softwareSkinnedMeshes.reset();
  23556. if (this._boundingBoxRenderer) {
  23557. this._boundingBoxRenderer.reset();
  23558. }
  23559. // Meshes
  23560. var meshes;
  23561. var len;
  23562. var checkIsEnabled = true;
  23563. // Determine mesh candidates
  23564. if (this._activeMeshCandidateProvider !== undefined) {
  23565. // Use _activeMeshCandidateProvider
  23566. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23567. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23568. if (meshes !== undefined) {
  23569. len = meshes.length;
  23570. }
  23571. else {
  23572. len = 0;
  23573. }
  23574. }
  23575. else if (this._selectionOctree !== undefined) {
  23576. // Octree
  23577. var selection = this._selectionOctree.select(this._frustumPlanes);
  23578. meshes = selection.data;
  23579. len = selection.length;
  23580. }
  23581. else {
  23582. // Full scene traversal
  23583. len = this.meshes.length;
  23584. meshes = this.meshes;
  23585. }
  23586. // Check each mesh
  23587. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23588. mesh = meshes[meshIndex];
  23589. if (mesh.isBlocked) {
  23590. continue;
  23591. }
  23592. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23593. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23594. continue;
  23595. }
  23596. mesh.computeWorldMatrix();
  23597. // Intersections
  23598. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23599. this._meshesForIntersections.pushNoDuplicate(mesh);
  23600. }
  23601. // Switch to current LOD
  23602. meshLOD = mesh.getLOD(this.activeCamera);
  23603. if (meshLOD === undefined || meshLOD === null) {
  23604. continue;
  23605. }
  23606. mesh._preActivate();
  23607. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23608. this._activeMeshes.push(mesh);
  23609. this.activeCamera._activeMeshes.push(mesh);
  23610. mesh._activate(this._renderId);
  23611. if (meshLOD !== mesh) {
  23612. meshLOD._activate(this._renderId);
  23613. }
  23614. this._activeMesh(mesh, meshLOD);
  23615. }
  23616. }
  23617. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23618. // Particle systems
  23619. if (this.particlesEnabled) {
  23620. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23621. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23622. var particleSystem = this.particleSystems[particleIndex];
  23623. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23624. continue;
  23625. }
  23626. var emitter = particleSystem.emitter;
  23627. if (!emitter.position || emitter.isEnabled()) {
  23628. this._activeParticleSystems.push(particleSystem);
  23629. particleSystem.animate();
  23630. this._renderingManager.dispatchParticles(particleSystem);
  23631. }
  23632. }
  23633. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23634. }
  23635. };
  23636. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23637. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23638. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23639. mesh.skeleton.prepare();
  23640. }
  23641. if (!mesh.computeBonesUsingShaders) {
  23642. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23643. }
  23644. }
  23645. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23646. var boundingInfo = sourceMesh.getBoundingInfo();
  23647. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23648. }
  23649. if (mesh !== undefined && mesh !== null
  23650. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23651. // Submeshes Octrees
  23652. var len;
  23653. var subMeshes;
  23654. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23655. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23656. len = intersections.length;
  23657. subMeshes = intersections.data;
  23658. }
  23659. else {
  23660. subMeshes = mesh.subMeshes;
  23661. len = subMeshes.length;
  23662. }
  23663. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23664. subMesh = subMeshes[subIndex];
  23665. this._evaluateSubMesh(subMesh, mesh);
  23666. }
  23667. }
  23668. };
  23669. Scene.prototype.updateTransformMatrix = function (force) {
  23670. if (!this.activeCamera) {
  23671. return;
  23672. }
  23673. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23674. };
  23675. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23676. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23677. };
  23678. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23679. if (camera && camera._skipRendering) {
  23680. return;
  23681. }
  23682. var engine = this._engine;
  23683. this.activeCamera = camera;
  23684. if (!this.activeCamera)
  23685. throw new Error("Active camera not set");
  23686. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23687. // Viewport
  23688. engine.setViewport(this.activeCamera.viewport);
  23689. // Camera
  23690. this.resetCachedMaterial();
  23691. this._renderId++;
  23692. this.activeCamera.update();
  23693. this.updateTransformMatrix();
  23694. if (camera._alternateCamera) {
  23695. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23696. this._alternateRendering = true;
  23697. }
  23698. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23699. // Meshes
  23700. this._evaluateActiveMeshes();
  23701. // Software skinning
  23702. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23703. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23704. mesh.applySkeleton(mesh.skeleton);
  23705. }
  23706. // Render targets
  23707. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23708. var needsRestoreFrameBuffer = false;
  23709. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23710. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23711. }
  23712. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  23713. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  23714. }
  23715. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23716. this._intermediateRendering = true;
  23717. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23718. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23719. var renderTarget = this._renderTargets.data[renderIndex];
  23720. if (renderTarget._shouldRender()) {
  23721. this._renderId++;
  23722. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23723. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23724. }
  23725. }
  23726. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23727. this._intermediateRendering = false;
  23728. this._renderId++;
  23729. needsRestoreFrameBuffer = true; // Restore back buffer
  23730. }
  23731. // Render EffecttLayer Texture
  23732. var stencilState = this._engine.getStencilBuffer();
  23733. var renderEffects = false;
  23734. var needStencil = false;
  23735. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23736. this._intermediateRendering = true;
  23737. for (var i = 0; i < this.effectLayers.length; i++) {
  23738. var effectLayer = this.effectLayers[i];
  23739. if (effectLayer.shouldRender() &&
  23740. (!effectLayer.camera ||
  23741. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23742. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23743. renderEffects = true;
  23744. needStencil = needStencil || effectLayer.needStencil();
  23745. var renderTarget = effectLayer._mainTexture;
  23746. if (renderTarget._shouldRender()) {
  23747. this._renderId++;
  23748. renderTarget.render(false, false);
  23749. needsRestoreFrameBuffer = true;
  23750. }
  23751. }
  23752. }
  23753. this._intermediateRendering = false;
  23754. this._renderId++;
  23755. }
  23756. if (needsRestoreFrameBuffer) {
  23757. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23758. }
  23759. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23760. // Prepare Frame
  23761. this.postProcessManager._prepareFrame();
  23762. // Backgrounds
  23763. var layerIndex;
  23764. var layer;
  23765. if (this.layers.length) {
  23766. engine.setDepthBuffer(false);
  23767. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23768. layer = this.layers[layerIndex];
  23769. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23770. layer.render();
  23771. }
  23772. }
  23773. engine.setDepthBuffer(true);
  23774. }
  23775. // Activate effect Layer stencil
  23776. if (needStencil) {
  23777. this._engine.setStencilBuffer(true);
  23778. }
  23779. // Render
  23780. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23781. this._renderingManager.render(null, null, true, true);
  23782. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23783. // Restore effect Layer stencil
  23784. if (needStencil) {
  23785. this._engine.setStencilBuffer(stencilState);
  23786. }
  23787. // Bounding boxes
  23788. if (this._boundingBoxRenderer) {
  23789. this._boundingBoxRenderer.render();
  23790. }
  23791. // Lens flares
  23792. if (this.lensFlaresEnabled) {
  23793. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23794. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23795. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23796. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23797. lensFlareSystem.render();
  23798. }
  23799. }
  23800. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23801. }
  23802. // Foregrounds
  23803. if (this.layers.length) {
  23804. engine.setDepthBuffer(false);
  23805. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23806. layer = this.layers[layerIndex];
  23807. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23808. layer.render();
  23809. }
  23810. }
  23811. engine.setDepthBuffer(true);
  23812. }
  23813. // Effect Layer
  23814. if (renderEffects) {
  23815. engine.setDepthBuffer(false);
  23816. for (var i = 0; i < this.effectLayers.length; i++) {
  23817. if (this.effectLayers[i].shouldRender()) {
  23818. this.effectLayers[i].render();
  23819. }
  23820. }
  23821. engine.setDepthBuffer(true);
  23822. }
  23823. // Finalize frame
  23824. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23825. // Reset some special arrays
  23826. this._renderTargets.reset();
  23827. this._alternateRendering = false;
  23828. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23829. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23830. };
  23831. Scene.prototype._processSubCameras = function (camera) {
  23832. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23833. this._renderForCamera(camera);
  23834. return;
  23835. }
  23836. // Update camera
  23837. if (this.activeCamera) {
  23838. this.activeCamera.update();
  23839. }
  23840. // rig cameras
  23841. for (var index = 0; index < camera._rigCameras.length; index++) {
  23842. this._renderForCamera(camera._rigCameras[index], camera);
  23843. }
  23844. this.activeCamera = camera;
  23845. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23846. };
  23847. Scene.prototype._checkIntersections = function () {
  23848. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23849. var sourceMesh = this._meshesForIntersections.data[index];
  23850. if (!sourceMesh.actionManager) {
  23851. continue;
  23852. }
  23853. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23854. var action = sourceMesh.actionManager.actions[actionIndex];
  23855. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23856. var parameters = action.getTriggerParameter();
  23857. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23858. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23859. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23860. if (areIntersecting && currentIntersectionInProgress === -1) {
  23861. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23862. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23863. sourceMesh._intersectionsInProgress.push(otherMesh);
  23864. }
  23865. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23866. sourceMesh._intersectionsInProgress.push(otherMesh);
  23867. }
  23868. }
  23869. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23870. //They intersected, and now they don't.
  23871. //is this trigger an exit trigger? execute an event.
  23872. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23873. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23874. }
  23875. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23876. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23877. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23878. }
  23879. }
  23880. }
  23881. }
  23882. }
  23883. };
  23884. Scene.prototype.render = function () {
  23885. if (this.isDisposed) {
  23886. return;
  23887. }
  23888. this._activeParticles.fetchNewFrame();
  23889. this._totalVertices.fetchNewFrame();
  23890. this._activeIndices.fetchNewFrame();
  23891. this._activeBones.fetchNewFrame();
  23892. this._meshesForIntersections.reset();
  23893. this.resetCachedMaterial();
  23894. this.onBeforeAnimationsObservable.notifyObservers(this);
  23895. // Actions
  23896. if (this.actionManager) {
  23897. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23898. }
  23899. //Simplification Queue
  23900. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23901. this.simplificationQueue.executeNext();
  23902. }
  23903. if (this._engine.isDeterministicLockStep()) {
  23904. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23905. var defaultFPS = (60.0 / 1000.0);
  23906. var defaultFrameTime = 1000 / 60; // frame time in MS
  23907. if (this._physicsEngine) {
  23908. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23909. }
  23910. var stepsTaken = 0;
  23911. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23912. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23913. internalSteps = Math.min(internalSteps, maxSubSteps);
  23914. do {
  23915. this.onBeforeStepObservable.notifyObservers(this);
  23916. // Animations
  23917. this._animationRatio = defaultFrameTime * defaultFPS;
  23918. this._animate();
  23919. this.onAfterAnimationsObservable.notifyObservers(this);
  23920. // Physics
  23921. if (this._physicsEngine) {
  23922. this.onBeforePhysicsObservable.notifyObservers(this);
  23923. this._physicsEngine._step(defaultFrameTime / 1000);
  23924. this.onAfterPhysicsObservable.notifyObservers(this);
  23925. }
  23926. this.onAfterStepObservable.notifyObservers(this);
  23927. this._currentStepId++;
  23928. stepsTaken++;
  23929. deltaTime -= defaultFrameTime;
  23930. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23931. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23932. }
  23933. else {
  23934. // Animations
  23935. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23936. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23937. this._animate();
  23938. this.onAfterAnimationsObservable.notifyObservers(this);
  23939. // Physics
  23940. if (this._physicsEngine) {
  23941. this.onBeforePhysicsObservable.notifyObservers(this);
  23942. this._physicsEngine._step(deltaTime / 1000.0);
  23943. this.onAfterPhysicsObservable.notifyObservers(this);
  23944. }
  23945. }
  23946. // update gamepad manager
  23947. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23948. this._gamepadManager._checkGamepadsStatus();
  23949. }
  23950. // Before render
  23951. this.onBeforeRenderObservable.notifyObservers(this);
  23952. // Customs render targets
  23953. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23954. var engine = this.getEngine();
  23955. var currentActiveCamera = this.activeCamera;
  23956. if (this.renderTargetsEnabled) {
  23957. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23958. this._intermediateRendering = true;
  23959. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23960. var renderTarget = this.customRenderTargets[customIndex];
  23961. if (renderTarget._shouldRender()) {
  23962. this._renderId++;
  23963. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23964. if (!this.activeCamera)
  23965. throw new Error("Active camera not set");
  23966. // Viewport
  23967. engine.setViewport(this.activeCamera.viewport);
  23968. // Camera
  23969. this.updateTransformMatrix();
  23970. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23971. }
  23972. }
  23973. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23974. this._intermediateRendering = false;
  23975. this._renderId++;
  23976. }
  23977. // Restore back buffer
  23978. if (this.customRenderTargets.length > 0) {
  23979. engine.restoreDefaultFramebuffer();
  23980. }
  23981. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23982. this.activeCamera = currentActiveCamera;
  23983. // Procedural textures
  23984. if (this.proceduralTexturesEnabled) {
  23985. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23986. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23987. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23988. if (proceduralTexture._shouldRender()) {
  23989. proceduralTexture.render();
  23990. }
  23991. }
  23992. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23993. }
  23994. // Clear
  23995. if (this.autoClearDepthAndStencil || this.autoClear) {
  23996. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  23997. }
  23998. // Shadows
  23999. if (this.shadowsEnabled) {
  24000. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24001. var light = this.lights[lightIndex];
  24002. var shadowGenerator = light.getShadowGenerator();
  24003. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24004. var shadowMap = (shadowGenerator.getShadowMap());
  24005. if (this.textures.indexOf(shadowMap) !== -1) {
  24006. this._renderTargets.push(shadowMap);
  24007. }
  24008. }
  24009. }
  24010. }
  24011. // Depth renderer
  24012. if (this._depthRenderer) {
  24013. this._renderTargets.push(this._depthRenderer.getDepthMap());
  24014. }
  24015. // Geometry renderer
  24016. if (this._geometryBufferRenderer) {
  24017. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24018. }
  24019. // RenderPipeline
  24020. if (this._postProcessRenderPipelineManager) {
  24021. this._postProcessRenderPipelineManager.update();
  24022. }
  24023. // Multi-cameras?
  24024. if (this.activeCameras.length > 0) {
  24025. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24026. if (cameraIndex > 0) {
  24027. this._engine.clear(null, false, true, true);
  24028. }
  24029. this._processSubCameras(this.activeCameras[cameraIndex]);
  24030. }
  24031. }
  24032. else {
  24033. if (!this.activeCamera) {
  24034. throw new Error("No camera defined");
  24035. }
  24036. this._processSubCameras(this.activeCamera);
  24037. }
  24038. // Intersection checks
  24039. this._checkIntersections();
  24040. // Update the audio listener attached to the camera
  24041. if (BABYLON.AudioEngine) {
  24042. this._updateAudioParameters();
  24043. }
  24044. // After render
  24045. if (this.afterRender) {
  24046. this.afterRender();
  24047. }
  24048. this.onAfterRenderObservable.notifyObservers(this);
  24049. // Cleaning
  24050. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24051. var data = this._toBeDisposed.data[index];
  24052. if (data) {
  24053. data.dispose();
  24054. }
  24055. this._toBeDisposed[index] = null;
  24056. }
  24057. this._toBeDisposed.reset();
  24058. if (this.dumpNextRenderTargets) {
  24059. this.dumpNextRenderTargets = false;
  24060. }
  24061. this._activeBones.addCount(0, true);
  24062. this._activeIndices.addCount(0, true);
  24063. this._activeParticles.addCount(0, true);
  24064. };
  24065. Scene.prototype._updateAudioParameters = function () {
  24066. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24067. return;
  24068. }
  24069. var listeningCamera;
  24070. var audioEngine = BABYLON.Engine.audioEngine;
  24071. if (this.activeCameras.length > 0) {
  24072. listeningCamera = this.activeCameras[0];
  24073. }
  24074. else {
  24075. listeningCamera = this.activeCamera;
  24076. }
  24077. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24078. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24079. // for VR cameras
  24080. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24081. listeningCamera = listeningCamera.rigCameras[0];
  24082. }
  24083. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24084. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24085. cameraDirection.normalize();
  24086. // To avoid some errors on GearVR
  24087. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24088. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24089. }
  24090. var i;
  24091. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24092. var sound = this.mainSoundTrack.soundCollection[i];
  24093. if (sound.useCustomAttenuation) {
  24094. sound.updateDistanceFromListener();
  24095. }
  24096. }
  24097. for (i = 0; i < this.soundTracks.length; i++) {
  24098. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24099. sound = this.soundTracks[i].soundCollection[j];
  24100. if (sound.useCustomAttenuation) {
  24101. sound.updateDistanceFromListener();
  24102. }
  24103. }
  24104. }
  24105. }
  24106. };
  24107. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24108. // Audio
  24109. get: function () {
  24110. return this._audioEnabled;
  24111. },
  24112. set: function (value) {
  24113. this._audioEnabled = value;
  24114. if (BABYLON.AudioEngine) {
  24115. if (this._audioEnabled) {
  24116. this._enableAudio();
  24117. }
  24118. else {
  24119. this._disableAudio();
  24120. }
  24121. }
  24122. },
  24123. enumerable: true,
  24124. configurable: true
  24125. });
  24126. Scene.prototype._disableAudio = function () {
  24127. var i;
  24128. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24129. this.mainSoundTrack.soundCollection[i].pause();
  24130. }
  24131. for (i = 0; i < this.soundTracks.length; i++) {
  24132. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24133. this.soundTracks[i].soundCollection[j].pause();
  24134. }
  24135. }
  24136. };
  24137. Scene.prototype._enableAudio = function () {
  24138. var i;
  24139. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24140. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24141. this.mainSoundTrack.soundCollection[i].play();
  24142. }
  24143. }
  24144. for (i = 0; i < this.soundTracks.length; i++) {
  24145. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24146. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24147. this.soundTracks[i].soundCollection[j].play();
  24148. }
  24149. }
  24150. }
  24151. };
  24152. Object.defineProperty(Scene.prototype, "headphone", {
  24153. get: function () {
  24154. return this._headphone;
  24155. },
  24156. set: function (value) {
  24157. this._headphone = value;
  24158. if (BABYLON.AudioEngine) {
  24159. if (this._headphone) {
  24160. this._switchAudioModeForHeadphones();
  24161. }
  24162. else {
  24163. this._switchAudioModeForNormalSpeakers();
  24164. }
  24165. }
  24166. },
  24167. enumerable: true,
  24168. configurable: true
  24169. });
  24170. Scene.prototype._switchAudioModeForHeadphones = function () {
  24171. this.mainSoundTrack.switchPanningModelToHRTF();
  24172. for (var i = 0; i < this.soundTracks.length; i++) {
  24173. this.soundTracks[i].switchPanningModelToHRTF();
  24174. }
  24175. };
  24176. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24177. this.mainSoundTrack.switchPanningModelToEqualPower();
  24178. for (var i = 0; i < this.soundTracks.length; i++) {
  24179. this.soundTracks[i].switchPanningModelToEqualPower();
  24180. }
  24181. };
  24182. Scene.prototype.enableDepthRenderer = function () {
  24183. if (this._depthRenderer) {
  24184. return this._depthRenderer;
  24185. }
  24186. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24187. return this._depthRenderer;
  24188. };
  24189. Scene.prototype.disableDepthRenderer = function () {
  24190. if (!this._depthRenderer) {
  24191. return;
  24192. }
  24193. this._depthRenderer.dispose();
  24194. this._depthRenderer = null;
  24195. };
  24196. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24197. if (ratio === void 0) { ratio = 1; }
  24198. if (this._geometryBufferRenderer) {
  24199. return this._geometryBufferRenderer;
  24200. }
  24201. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24202. if (!this._geometryBufferRenderer.isSupported) {
  24203. this._geometryBufferRenderer = null;
  24204. }
  24205. return this._geometryBufferRenderer;
  24206. };
  24207. Scene.prototype.disableGeometryBufferRenderer = function () {
  24208. if (!this._geometryBufferRenderer) {
  24209. return;
  24210. }
  24211. this._geometryBufferRenderer.dispose();
  24212. this._geometryBufferRenderer = null;
  24213. };
  24214. Scene.prototype.freezeMaterials = function () {
  24215. for (var i = 0; i < this.materials.length; i++) {
  24216. this.materials[i].freeze();
  24217. }
  24218. };
  24219. Scene.prototype.unfreezeMaterials = function () {
  24220. for (var i = 0; i < this.materials.length; i++) {
  24221. this.materials[i].unfreeze();
  24222. }
  24223. };
  24224. Scene.prototype.dispose = function () {
  24225. this.beforeRender = null;
  24226. this.afterRender = null;
  24227. this.skeletons = [];
  24228. this.morphTargetManagers = [];
  24229. this.importedMeshesFiles = new Array();
  24230. this.stopAllAnimations();
  24231. this.resetCachedMaterial();
  24232. if (this._depthRenderer) {
  24233. this._depthRenderer.dispose();
  24234. }
  24235. if (this._gamepadManager) {
  24236. this._gamepadManager.dispose();
  24237. this._gamepadManager = null;
  24238. }
  24239. // Smart arrays
  24240. if (this.activeCamera) {
  24241. this.activeCamera._activeMeshes.dispose();
  24242. this.activeCamera = null;
  24243. }
  24244. this._activeMeshes.dispose();
  24245. this._renderingManager.dispose();
  24246. this._processedMaterials.dispose();
  24247. this._activeParticleSystems.dispose();
  24248. this._activeSkeletons.dispose();
  24249. this._softwareSkinnedMeshes.dispose();
  24250. this._renderTargets.dispose();
  24251. if (this._boundingBoxRenderer) {
  24252. this._boundingBoxRenderer.dispose();
  24253. }
  24254. this._meshesForIntersections.dispose();
  24255. this._toBeDisposed.dispose();
  24256. // Abort active requests
  24257. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24258. var request = _a[_i];
  24259. request.abort();
  24260. }
  24261. // Debug layer
  24262. if (this._debugLayer) {
  24263. this._debugLayer.hide();
  24264. }
  24265. // Events
  24266. this.onDisposeObservable.notifyObservers(this);
  24267. this.onDisposeObservable.clear();
  24268. this.onBeforeRenderObservable.clear();
  24269. this.onAfterRenderObservable.clear();
  24270. this.OnBeforeRenderTargetsRenderObservable.clear();
  24271. this.OnAfterRenderTargetsRenderObservable.clear();
  24272. this.onAfterStepObservable.clear();
  24273. this.onBeforeStepObservable.clear();
  24274. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24275. this.onAfterActiveMeshesEvaluationObservable.clear();
  24276. this.onBeforeParticlesRenderingObservable.clear();
  24277. this.onAfterParticlesRenderingObservable.clear();
  24278. this.onBeforeSpritesRenderingObservable.clear();
  24279. this.onAfterSpritesRenderingObservable.clear();
  24280. this.onBeforeDrawPhaseObservable.clear();
  24281. this.onAfterDrawPhaseObservable.clear();
  24282. this.onBeforePhysicsObservable.clear();
  24283. this.onAfterPhysicsObservable.clear();
  24284. this.onBeforeAnimationsObservable.clear();
  24285. this.onAfterAnimationsObservable.clear();
  24286. this.onDataLoadedObservable.clear();
  24287. this.detachControl();
  24288. // Release sounds & sounds tracks
  24289. if (BABYLON.AudioEngine) {
  24290. this.disposeSounds();
  24291. }
  24292. // VR Helper
  24293. if (this.VRHelper) {
  24294. this.VRHelper.dispose();
  24295. }
  24296. // Detach cameras
  24297. var canvas = this._engine.getRenderingCanvas();
  24298. if (canvas) {
  24299. var index;
  24300. for (index = 0; index < this.cameras.length; index++) {
  24301. this.cameras[index].detachControl(canvas);
  24302. }
  24303. }
  24304. // Release animation groups
  24305. while (this.animationGroups.length) {
  24306. this.animationGroups[0].dispose();
  24307. }
  24308. // Release lights
  24309. while (this.lights.length) {
  24310. this.lights[0].dispose();
  24311. }
  24312. // Release meshes
  24313. while (this.meshes.length) {
  24314. this.meshes[0].dispose(true);
  24315. }
  24316. while (this.transformNodes.length) {
  24317. this.removeTransformNode(this.transformNodes[0]);
  24318. }
  24319. // Release cameras
  24320. while (this.cameras.length) {
  24321. this.cameras[0].dispose();
  24322. }
  24323. // Release materials
  24324. if (this.defaultMaterial) {
  24325. this.defaultMaterial.dispose();
  24326. }
  24327. while (this.multiMaterials.length) {
  24328. this.multiMaterials[0].dispose();
  24329. }
  24330. while (this.materials.length) {
  24331. this.materials[0].dispose();
  24332. }
  24333. // Release particles
  24334. while (this.particleSystems.length) {
  24335. this.particleSystems[0].dispose();
  24336. }
  24337. // Release sprites
  24338. while (this.spriteManagers.length) {
  24339. this.spriteManagers[0].dispose();
  24340. }
  24341. // Release postProcesses
  24342. while (this.postProcesses.length) {
  24343. this.postProcesses[0].dispose();
  24344. }
  24345. // Release layers
  24346. while (this.layers.length) {
  24347. this.layers[0].dispose();
  24348. }
  24349. while (this.effectLayers.length) {
  24350. this.effectLayers[0].dispose();
  24351. }
  24352. // Release textures
  24353. while (this.textures.length) {
  24354. this.textures[0].dispose();
  24355. }
  24356. // Release UBO
  24357. this._sceneUbo.dispose();
  24358. if (this._alternateSceneUbo) {
  24359. this._alternateSceneUbo.dispose();
  24360. }
  24361. // Post-processes
  24362. this.postProcessManager.dispose();
  24363. if (this._postProcessRenderPipelineManager) {
  24364. this._postProcessRenderPipelineManager.dispose();
  24365. }
  24366. // Physics
  24367. if (this._physicsEngine) {
  24368. this.disablePhysicsEngine();
  24369. }
  24370. // Remove from engine
  24371. index = this._engine.scenes.indexOf(this);
  24372. if (index > -1) {
  24373. this._engine.scenes.splice(index, 1);
  24374. }
  24375. this._engine.wipeCaches(true);
  24376. this._isDisposed = true;
  24377. };
  24378. Object.defineProperty(Scene.prototype, "isDisposed", {
  24379. get: function () {
  24380. return this._isDisposed;
  24381. },
  24382. enumerable: true,
  24383. configurable: true
  24384. });
  24385. // Release sounds & sounds tracks
  24386. Scene.prototype.disposeSounds = function () {
  24387. if (!this._mainSoundTrack) {
  24388. return;
  24389. }
  24390. this.mainSoundTrack.dispose();
  24391. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24392. this.soundTracks[scIndex].dispose();
  24393. }
  24394. };
  24395. // Octrees
  24396. Scene.prototype.getWorldExtends = function () {
  24397. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24398. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24399. for (var index = 0; index < this.meshes.length; index++) {
  24400. var mesh = this.meshes[index];
  24401. mesh.computeWorldMatrix(true);
  24402. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24403. continue;
  24404. }
  24405. var boundingInfo = mesh.getBoundingInfo();
  24406. var minBox = boundingInfo.boundingBox.minimumWorld;
  24407. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24408. BABYLON.Tools.CheckExtends(minBox, min, max);
  24409. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24410. }
  24411. return {
  24412. min: min,
  24413. max: max
  24414. };
  24415. };
  24416. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24417. if (maxCapacity === void 0) { maxCapacity = 64; }
  24418. if (maxDepth === void 0) { maxDepth = 2; }
  24419. if (!this._selectionOctree) {
  24420. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24421. }
  24422. var worldExtends = this.getWorldExtends();
  24423. // Update octree
  24424. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24425. return this._selectionOctree;
  24426. };
  24427. // Picking
  24428. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24429. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24430. var result = BABYLON.Ray.Zero();
  24431. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24432. return result;
  24433. };
  24434. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24435. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24436. var engine = this._engine;
  24437. if (!camera) {
  24438. if (!this.activeCamera)
  24439. throw new Error("Active camera not set");
  24440. camera = this.activeCamera;
  24441. }
  24442. var cameraViewport = camera.viewport;
  24443. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24444. // Moving coordinates to local viewport world
  24445. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24446. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24447. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24448. return this;
  24449. };
  24450. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24451. var result = BABYLON.Ray.Zero();
  24452. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24453. return result;
  24454. };
  24455. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24456. if (!BABYLON.PickingInfo) {
  24457. return this;
  24458. }
  24459. var engine = this._engine;
  24460. if (!camera) {
  24461. if (!this.activeCamera)
  24462. throw new Error("Active camera not set");
  24463. camera = this.activeCamera;
  24464. }
  24465. var cameraViewport = camera.viewport;
  24466. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24467. var identity = BABYLON.Matrix.Identity();
  24468. // Moving coordinates to local viewport world
  24469. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24470. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24471. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24472. return this;
  24473. };
  24474. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24475. if (!BABYLON.PickingInfo) {
  24476. return null;
  24477. }
  24478. var pickingInfo = null;
  24479. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24480. var mesh = this.meshes[meshIndex];
  24481. if (predicate) {
  24482. if (!predicate(mesh)) {
  24483. continue;
  24484. }
  24485. }
  24486. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24487. continue;
  24488. }
  24489. var world = mesh.getWorldMatrix();
  24490. var ray = rayFunction(world);
  24491. var result = mesh.intersects(ray, fastCheck);
  24492. if (!result || !result.hit)
  24493. continue;
  24494. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24495. continue;
  24496. pickingInfo = result;
  24497. if (fastCheck) {
  24498. break;
  24499. }
  24500. }
  24501. return pickingInfo || new BABYLON.PickingInfo();
  24502. };
  24503. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24504. if (!BABYLON.PickingInfo) {
  24505. return null;
  24506. }
  24507. var pickingInfos = new Array();
  24508. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24509. var mesh = this.meshes[meshIndex];
  24510. if (predicate) {
  24511. if (!predicate(mesh)) {
  24512. continue;
  24513. }
  24514. }
  24515. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24516. continue;
  24517. }
  24518. var world = mesh.getWorldMatrix();
  24519. var ray = rayFunction(world);
  24520. var result = mesh.intersects(ray, false);
  24521. if (!result || !result.hit)
  24522. continue;
  24523. pickingInfos.push(result);
  24524. }
  24525. return pickingInfos;
  24526. };
  24527. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24528. if (!BABYLON.PickingInfo) {
  24529. return null;
  24530. }
  24531. var pickingInfo = null;
  24532. if (!camera) {
  24533. if (!this.activeCamera) {
  24534. return null;
  24535. }
  24536. camera = this.activeCamera;
  24537. }
  24538. if (this.spriteManagers.length > 0) {
  24539. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24540. var spriteManager = this.spriteManagers[spriteIndex];
  24541. if (!spriteManager.isPickable) {
  24542. continue;
  24543. }
  24544. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24545. if (!result || !result.hit)
  24546. continue;
  24547. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24548. continue;
  24549. pickingInfo = result;
  24550. if (fastCheck) {
  24551. break;
  24552. }
  24553. }
  24554. }
  24555. return pickingInfo || new BABYLON.PickingInfo();
  24556. };
  24557. /** Launch a ray to try to pick a mesh in the scene
  24558. * @param x position on screen
  24559. * @param y position on screen
  24560. * @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
  24561. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24562. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24563. */
  24564. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24565. var _this = this;
  24566. if (!BABYLON.PickingInfo) {
  24567. return null;
  24568. }
  24569. return this._internalPick(function (world) {
  24570. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24571. return _this._tempPickingRay;
  24572. }, predicate, fastCheck);
  24573. };
  24574. /** Launch a ray to try to pick a sprite in the scene
  24575. * @param x position on screen
  24576. * @param y position on screen
  24577. * @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
  24578. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24579. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24580. */
  24581. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24582. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24583. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24584. };
  24585. /** Use the given ray to pick a mesh in the scene
  24586. * @param ray The ray to use to pick meshes
  24587. * @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
  24588. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24589. */
  24590. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24591. var _this = this;
  24592. return this._internalPick(function (world) {
  24593. if (!_this._pickWithRayInverseMatrix) {
  24594. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24595. }
  24596. world.invertToRef(_this._pickWithRayInverseMatrix);
  24597. if (!_this._cachedRayForTransform) {
  24598. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24599. }
  24600. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24601. return _this._cachedRayForTransform;
  24602. }, predicate, fastCheck);
  24603. };
  24604. /**
  24605. * Launch a ray to try to pick a mesh in the scene
  24606. * @param x X position on screen
  24607. * @param y Y position on screen
  24608. * @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
  24609. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24610. */
  24611. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24612. var _this = this;
  24613. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24614. };
  24615. /**
  24616. * Launch a ray to try to pick a mesh in the scene
  24617. * @param ray Ray to use
  24618. * @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
  24619. */
  24620. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24621. var _this = this;
  24622. return this._internalMultiPick(function (world) {
  24623. if (!_this._pickWithRayInverseMatrix) {
  24624. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24625. }
  24626. world.invertToRef(_this._pickWithRayInverseMatrix);
  24627. if (!_this._cachedRayForTransform) {
  24628. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24629. }
  24630. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24631. return _this._cachedRayForTransform;
  24632. }, predicate);
  24633. };
  24634. Scene.prototype.setPointerOverMesh = function (mesh) {
  24635. if (this._pointerOverMesh === mesh) {
  24636. return;
  24637. }
  24638. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24639. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24640. }
  24641. this._pointerOverMesh = mesh;
  24642. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24643. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24644. }
  24645. };
  24646. Scene.prototype.getPointerOverMesh = function () {
  24647. return this._pointerOverMesh;
  24648. };
  24649. Scene.prototype.setPointerOverSprite = function (sprite) {
  24650. if (this._pointerOverSprite === sprite) {
  24651. return;
  24652. }
  24653. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24654. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24655. }
  24656. this._pointerOverSprite = sprite;
  24657. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24658. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24659. }
  24660. };
  24661. Scene.prototype.getPointerOverSprite = function () {
  24662. return this._pointerOverSprite;
  24663. };
  24664. // Physics
  24665. Scene.prototype.getPhysicsEngine = function () {
  24666. return this._physicsEngine;
  24667. };
  24668. /**
  24669. * Enables physics to the current scene
  24670. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24671. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24672. * @return {boolean} was the physics engine initialized
  24673. */
  24674. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24675. if (gravity === void 0) { gravity = null; }
  24676. if (this._physicsEngine) {
  24677. return true;
  24678. }
  24679. try {
  24680. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24681. return true;
  24682. }
  24683. catch (e) {
  24684. BABYLON.Tools.Error(e.message);
  24685. return false;
  24686. }
  24687. };
  24688. Scene.prototype.disablePhysicsEngine = function () {
  24689. if (!this._physicsEngine) {
  24690. return;
  24691. }
  24692. this._physicsEngine.dispose();
  24693. this._physicsEngine = null;
  24694. };
  24695. Scene.prototype.isPhysicsEnabled = function () {
  24696. return this._physicsEngine !== undefined;
  24697. };
  24698. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24699. var mesh = compound.parts[0].mesh;
  24700. if (mesh.physicsImpostor) {
  24701. mesh.physicsImpostor.dispose();
  24702. mesh.physicsImpostor = null;
  24703. }
  24704. };
  24705. // Misc.
  24706. Scene.prototype._rebuildGeometries = function () {
  24707. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24708. var geometry = _a[_i];
  24709. geometry._rebuild();
  24710. }
  24711. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24712. var mesh = _c[_b];
  24713. mesh._rebuild();
  24714. }
  24715. if (this.postProcessManager) {
  24716. this.postProcessManager._rebuild();
  24717. }
  24718. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24719. var layer = _e[_d];
  24720. layer._rebuild();
  24721. }
  24722. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24723. var effectLayer = _g[_f];
  24724. effectLayer._rebuild();
  24725. }
  24726. if (this._boundingBoxRenderer) {
  24727. this._boundingBoxRenderer._rebuild();
  24728. }
  24729. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24730. var system = _j[_h];
  24731. system.rebuild();
  24732. }
  24733. if (this._postProcessRenderPipelineManager) {
  24734. this._postProcessRenderPipelineManager._rebuild();
  24735. }
  24736. };
  24737. Scene.prototype._rebuildTextures = function () {
  24738. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24739. var texture = _a[_i];
  24740. texture._rebuild();
  24741. }
  24742. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24743. };
  24744. /**
  24745. * Creates a default light for the scene.
  24746. * @param replace Whether to replace the existing lights in the scene.
  24747. */
  24748. Scene.prototype.createDefaultLight = function (replace) {
  24749. if (replace === void 0) { replace = false; }
  24750. // Dispose existing light in replace mode.
  24751. if (replace) {
  24752. if (this.lights) {
  24753. for (var i = 0; i < this.lights.length; i++) {
  24754. this.lights[i].dispose();
  24755. }
  24756. }
  24757. }
  24758. // Light
  24759. if (this.lights.length === 0) {
  24760. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24761. }
  24762. };
  24763. /**
  24764. * Creates a default camera for the scene.
  24765. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24766. * @param replace Whether to replace the existing active camera in the scene.
  24767. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24768. */
  24769. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24770. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24771. if (replace === void 0) { replace = false; }
  24772. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24773. // Dispose existing camera in replace mode.
  24774. if (replace) {
  24775. if (this.activeCamera) {
  24776. this.activeCamera.dispose();
  24777. this.activeCamera = null;
  24778. }
  24779. }
  24780. // Camera
  24781. if (!this.activeCamera) {
  24782. var worldExtends = this.getWorldExtends();
  24783. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24784. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24785. var camera;
  24786. var radius = worldSize.length() * 1.5;
  24787. // empty scene scenario!
  24788. if (!isFinite(radius)) {
  24789. radius = 1;
  24790. worldCenter.copyFromFloats(0, 0, 0);
  24791. }
  24792. if (createArcRotateCamera) {
  24793. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24794. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24795. arcRotateCamera.wheelPrecision = 100 / radius;
  24796. camera = arcRotateCamera;
  24797. }
  24798. else {
  24799. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24800. freeCamera.setTarget(worldCenter);
  24801. camera = freeCamera;
  24802. }
  24803. camera.minZ = radius * 0.01;
  24804. camera.maxZ = radius * 1000;
  24805. camera.speed = radius * 0.2;
  24806. this.activeCamera = camera;
  24807. var canvas = this.getEngine().getRenderingCanvas();
  24808. if (attachCameraControls && canvas) {
  24809. camera.attachControl(canvas);
  24810. }
  24811. }
  24812. };
  24813. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24814. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24815. if (replace === void 0) { replace = false; }
  24816. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24817. this.createDefaultLight(replace);
  24818. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24819. };
  24820. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24821. if (pbr === void 0) { pbr = false; }
  24822. if (scale === void 0) { scale = 1000; }
  24823. if (blur === void 0) { blur = 0; }
  24824. if (environmentTexture) {
  24825. this.environmentTexture = environmentTexture;
  24826. }
  24827. if (!this.environmentTexture) {
  24828. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24829. return null;
  24830. }
  24831. // Skybox
  24832. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24833. if (pbr) {
  24834. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24835. hdrSkyboxMaterial.backFaceCulling = false;
  24836. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24837. if (hdrSkyboxMaterial.reflectionTexture) {
  24838. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24839. }
  24840. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24841. hdrSkyboxMaterial.disableLighting = true;
  24842. hdrSkyboxMaterial.twoSidedLighting = true;
  24843. hdrSkybox.infiniteDistance = true;
  24844. hdrSkybox.material = hdrSkyboxMaterial;
  24845. }
  24846. else {
  24847. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24848. skyboxMaterial.backFaceCulling = false;
  24849. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24850. if (skyboxMaterial.reflectionTexture) {
  24851. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24852. }
  24853. skyboxMaterial.disableLighting = true;
  24854. hdrSkybox.infiniteDistance = true;
  24855. hdrSkybox.material = skyboxMaterial;
  24856. }
  24857. return hdrSkybox;
  24858. };
  24859. Scene.prototype.createDefaultEnvironment = function (options) {
  24860. if (BABYLON.EnvironmentHelper) {
  24861. return new BABYLON.EnvironmentHelper(options, this);
  24862. }
  24863. return null;
  24864. };
  24865. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24866. if (webVROptions === void 0) { webVROptions = {}; }
  24867. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24868. };
  24869. // Tags
  24870. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24871. if (tagsQuery === undefined) {
  24872. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24873. return list;
  24874. }
  24875. var listByTags = [];
  24876. forEach = forEach || (function (item) { return; });
  24877. for (var i in list) {
  24878. var item = list[i];
  24879. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24880. listByTags.push(item);
  24881. forEach(item);
  24882. }
  24883. }
  24884. return listByTags;
  24885. };
  24886. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24887. return this._getByTags(this.meshes, tagsQuery, forEach);
  24888. };
  24889. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24890. return this._getByTags(this.cameras, tagsQuery, forEach);
  24891. };
  24892. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24893. return this._getByTags(this.lights, tagsQuery, forEach);
  24894. };
  24895. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24896. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24897. };
  24898. /**
  24899. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24900. * This allowed control for front to back rendering or reversly depending of the special needs.
  24901. *
  24902. * @param renderingGroupId The rendering group id corresponding to its index
  24903. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24904. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24905. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24906. */
  24907. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24908. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24909. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24910. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24911. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24912. };
  24913. /**
  24914. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24915. *
  24916. * @param renderingGroupId The rendering group id corresponding to its index
  24917. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24918. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24919. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24920. */
  24921. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24922. if (depth === void 0) { depth = true; }
  24923. if (stencil === void 0) { stencil = true; }
  24924. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24925. };
  24926. /**
  24927. * Will flag all materials as dirty to trigger new shader compilation
  24928. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24929. */
  24930. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24931. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24932. var material = _a[_i];
  24933. if (predicate && !predicate(material)) {
  24934. continue;
  24935. }
  24936. material.markAsDirty(flag);
  24937. }
  24938. };
  24939. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24940. var _this = this;
  24941. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24942. this._activeRequests.push(request);
  24943. request.onCompleteObservable.add(function (request) {
  24944. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24945. });
  24946. return request;
  24947. };
  24948. /** @ignore */
  24949. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24950. var _this = this;
  24951. return new Promise(function (resolve, reject) {
  24952. _this._loadFile(url, function (data) {
  24953. resolve(data);
  24954. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24955. reject(exception);
  24956. });
  24957. });
  24958. };
  24959. // Statics
  24960. Scene._FOGMODE_NONE = 0;
  24961. Scene._FOGMODE_EXP = 1;
  24962. Scene._FOGMODE_EXP2 = 2;
  24963. Scene._FOGMODE_LINEAR = 3;
  24964. Scene._uniqueIdCounter = 0;
  24965. Scene.MinDeltaTime = 1.0;
  24966. Scene.MaxDeltaTime = 1000.0;
  24967. /** The distance in pixel that you have to move to prevent some events */
  24968. Scene.DragMovementThreshold = 10; // in pixels
  24969. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24970. Scene.LongPressDelay = 500; // in milliseconds
  24971. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24972. Scene.DoubleClickDelay = 300; // in milliseconds
  24973. /** If you need to check double click without raising a single click at first click, enable this flag */
  24974. Scene.ExclusiveDoubleClickMode = false;
  24975. return Scene;
  24976. }());
  24977. BABYLON.Scene = Scene;
  24978. })(BABYLON || (BABYLON = {}));
  24979. //# sourceMappingURL=babylon.scene.js.map
  24980. var BABYLON;
  24981. (function (BABYLON) {
  24982. /**
  24983. * Set of assets to keep when moving a scene into an asset container.
  24984. */
  24985. var KeepAssets = /** @class */ (function () {
  24986. function KeepAssets() {
  24987. /**
  24988. * Cameras to keep.
  24989. */
  24990. this.cameras = new Array();
  24991. /**
  24992. * Lights to keep.
  24993. */
  24994. this.lights = new Array();
  24995. /**
  24996. * Meshes to keep.
  24997. */
  24998. this.meshes = new Array();
  24999. /**
  25000. * Skeletons to keep.
  25001. */
  25002. this.skeletons = new Array();
  25003. /**
  25004. * ParticleSystems to keep.
  25005. */
  25006. this.particleSystems = new Array();
  25007. /**
  25008. * Animations to keep.
  25009. */
  25010. this.animations = new Array();
  25011. /**
  25012. * MultiMaterials to keep.
  25013. */
  25014. this.multiMaterials = new Array();
  25015. /**
  25016. * Materials to keep.
  25017. */
  25018. this.materials = new Array();
  25019. /**
  25020. * MorphTargetManagers to keep.
  25021. */
  25022. this.morphTargetManagers = new Array();
  25023. /**
  25024. * Geometries to keep.
  25025. */
  25026. this.geometries = new Array();
  25027. /**
  25028. * TransformNodes to keep.
  25029. */
  25030. this.transformNodes = new Array();
  25031. /**
  25032. * LensFlareSystems to keep.
  25033. */
  25034. this.lensFlareSystems = new Array();
  25035. /**
  25036. * ShadowGenerators to keep.
  25037. */
  25038. this.shadowGenerators = new Array();
  25039. /**
  25040. * ActionManagers to keep.
  25041. */
  25042. this.actionManagers = new Array();
  25043. /**
  25044. * Sounds to keep.
  25045. */
  25046. this.sounds = new Array();
  25047. }
  25048. return KeepAssets;
  25049. }());
  25050. BABYLON.KeepAssets = KeepAssets;
  25051. /**
  25052. * Container with a set of assets that can be added or removed from a scene.
  25053. */
  25054. var AssetContainer = /** @class */ (function () {
  25055. /**
  25056. * Instantiates an AssetContainer.
  25057. * @param scene The scene the AssetContainer belongs to.
  25058. */
  25059. function AssetContainer(scene) {
  25060. // Objects
  25061. /**
  25062. * Cameras populated in the container.
  25063. */
  25064. this.cameras = new Array();
  25065. /**
  25066. * Lights populated in the container.
  25067. */
  25068. this.lights = new Array();
  25069. /**
  25070. * Meshes populated in the container.
  25071. */
  25072. this.meshes = new Array();
  25073. /**
  25074. * Skeletons populated in the container.
  25075. */
  25076. this.skeletons = new Array();
  25077. /**
  25078. * ParticleSystems populated in the container.
  25079. */
  25080. this.particleSystems = new Array();
  25081. /**
  25082. * Animations populated in the container.
  25083. */
  25084. this.animations = new Array();
  25085. /**
  25086. * MultiMaterials populated in the container.
  25087. */
  25088. this.multiMaterials = new Array();
  25089. /**
  25090. * Materials populated in the container.
  25091. */
  25092. this.materials = new Array();
  25093. /**
  25094. * MorphTargetManagers populated in the container.
  25095. */
  25096. this.morphTargetManagers = new Array();
  25097. /**
  25098. * Geometries populated in the container.
  25099. */
  25100. this.geometries = new Array();
  25101. /**
  25102. * TransformNodes populated in the container.
  25103. */
  25104. this.transformNodes = new Array();
  25105. /**
  25106. * LensFlareSystems populated in the container.
  25107. */
  25108. this.lensFlareSystems = new Array();
  25109. /**
  25110. * ShadowGenerators populated in the container.
  25111. */
  25112. this.shadowGenerators = new Array();
  25113. /**
  25114. * ActionManagers populated in the container.
  25115. */
  25116. this.actionManagers = new Array();
  25117. /**
  25118. * Sounds populated in the container.
  25119. */
  25120. this.sounds = new Array();
  25121. this.scene = scene;
  25122. }
  25123. /**
  25124. * Adds all the assets from the container to the scene.
  25125. */
  25126. AssetContainer.prototype.addAllToScene = function () {
  25127. var _this = this;
  25128. this.cameras.forEach(function (o) {
  25129. _this.scene.addCamera(o);
  25130. });
  25131. this.lights.forEach(function (o) {
  25132. _this.scene.addLight(o);
  25133. });
  25134. this.meshes.forEach(function (o) {
  25135. _this.scene.addMesh(o);
  25136. });
  25137. this.skeletons.forEach(function (o) {
  25138. _this.scene.addSkeleton(o);
  25139. });
  25140. this.particleSystems.forEach(function (o) {
  25141. _this.scene.addParticleSystem(o);
  25142. });
  25143. this.animations.forEach(function (o) {
  25144. _this.scene.addAnimation(o);
  25145. });
  25146. this.multiMaterials.forEach(function (o) {
  25147. _this.scene.addMultiMaterial(o);
  25148. });
  25149. this.materials.forEach(function (o) {
  25150. _this.scene.addMaterial(o);
  25151. });
  25152. this.morphTargetManagers.forEach(function (o) {
  25153. _this.scene.addMorphTargetManager(o);
  25154. });
  25155. this.geometries.forEach(function (o) {
  25156. _this.scene.addGeometry(o);
  25157. });
  25158. this.transformNodes.forEach(function (o) {
  25159. _this.scene.addTransformNode(o);
  25160. });
  25161. this.lensFlareSystems.forEach(function (o) {
  25162. _this.scene.addLensFlareSystem(o);
  25163. });
  25164. this.actionManagers.forEach(function (o) {
  25165. _this.scene.addActionManager(o);
  25166. });
  25167. this.sounds.forEach(function (o) {
  25168. o.play();
  25169. o.autoplay = true;
  25170. _this.scene.mainSoundTrack.AddSound(o);
  25171. });
  25172. };
  25173. /**
  25174. * Removes all the assets in the container from the scene
  25175. */
  25176. AssetContainer.prototype.removeAllFromScene = function () {
  25177. var _this = this;
  25178. this.cameras.forEach(function (o) {
  25179. _this.scene.removeCamera(o);
  25180. });
  25181. this.lights.forEach(function (o) {
  25182. _this.scene.removeLight(o);
  25183. });
  25184. this.meshes.forEach(function (o) {
  25185. _this.scene.removeMesh(o);
  25186. });
  25187. this.skeletons.forEach(function (o) {
  25188. _this.scene.removeSkeleton(o);
  25189. });
  25190. this.particleSystems.forEach(function (o) {
  25191. _this.scene.removeParticleSystem(o);
  25192. });
  25193. this.animations.forEach(function (o) {
  25194. _this.scene.removeAnimation(o);
  25195. });
  25196. this.multiMaterials.forEach(function (o) {
  25197. _this.scene.removeMultiMaterial(o);
  25198. });
  25199. this.materials.forEach(function (o) {
  25200. _this.scene.removeMaterial(o);
  25201. });
  25202. this.morphTargetManagers.forEach(function (o) {
  25203. _this.scene.removeMorphTargetManager(o);
  25204. });
  25205. this.geometries.forEach(function (o) {
  25206. _this.scene.removeGeometry(o);
  25207. });
  25208. this.transformNodes.forEach(function (o) {
  25209. _this.scene.removeTransformNode(o);
  25210. });
  25211. this.lensFlareSystems.forEach(function (o) {
  25212. _this.scene.removeLensFlareSystem(o);
  25213. });
  25214. this.actionManagers.forEach(function (o) {
  25215. _this.scene.removeActionManager(o);
  25216. });
  25217. this.sounds.forEach(function (o) {
  25218. o.stop();
  25219. o.autoplay = false;
  25220. _this.scene.mainSoundTrack.RemoveSound(o);
  25221. });
  25222. };
  25223. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25224. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25225. var asset = sourceAssets_1[_i];
  25226. var move = true;
  25227. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25228. var keepAsset = keepAssets_1[_a];
  25229. if (asset === keepAsset) {
  25230. move = false;
  25231. break;
  25232. }
  25233. }
  25234. if (move) {
  25235. targetAssets.push(asset);
  25236. }
  25237. }
  25238. };
  25239. /**
  25240. * Removes all the assets contained in the scene and adds them to the container.
  25241. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25242. */
  25243. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25244. if (keepAssets === undefined) {
  25245. keepAssets = new KeepAssets();
  25246. }
  25247. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25248. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25249. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25250. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25251. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25252. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25253. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25254. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25255. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25256. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25257. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25258. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25259. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25260. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25261. this.removeAllFromScene();
  25262. };
  25263. return AssetContainer;
  25264. }());
  25265. BABYLON.AssetContainer = AssetContainer;
  25266. })(BABYLON || (BABYLON = {}));
  25267. //# sourceMappingURL=babylon.assetContainer.js.map
  25268. var BABYLON;
  25269. (function (BABYLON) {
  25270. var Buffer = /** @class */ (function () {
  25271. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25272. if (instanced === void 0) { instanced = false; }
  25273. if (engine instanceof BABYLON.Mesh) {
  25274. this._engine = engine.getScene().getEngine();
  25275. }
  25276. else {
  25277. this._engine = engine;
  25278. }
  25279. this._updatable = updatable;
  25280. this._instanced = instanced;
  25281. this._data = data;
  25282. this._strideSize = stride;
  25283. if (!postponeInternalCreation) {
  25284. this.create();
  25285. }
  25286. }
  25287. /**
  25288. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25289. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25290. * @param offset defines offset in the buffer (0 by default)
  25291. * @param size defines the size in floats of attributes (position is 3 for instance)
  25292. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25293. * @param instanced defines if the vertex buffer contains indexed data
  25294. * @returns the new vertex buffer
  25295. */
  25296. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25297. // a lot of these parameters are ignored as they are overriden by the buffer
  25298. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25299. };
  25300. // Properties
  25301. Buffer.prototype.isUpdatable = function () {
  25302. return this._updatable;
  25303. };
  25304. Buffer.prototype.getData = function () {
  25305. return this._data;
  25306. };
  25307. Buffer.prototype.getBuffer = function () {
  25308. return this._buffer;
  25309. };
  25310. Buffer.prototype.getStrideSize = function () {
  25311. return this._strideSize;
  25312. };
  25313. // public getIsInstanced(): boolean {
  25314. // return this._instanced;
  25315. // }
  25316. // public get instanceDivisor(): number {
  25317. // return this._instanceDivisor;
  25318. // }
  25319. // public set instanceDivisor(value: number) {
  25320. // this._instanceDivisor = value;
  25321. // if (value == 0) {
  25322. // this._instanced = false;
  25323. // } else {
  25324. // this._instanced = true;
  25325. // }
  25326. // }
  25327. // Methods
  25328. Buffer.prototype.create = function (data) {
  25329. if (data === void 0) { data = null; }
  25330. if (!data && this._buffer) {
  25331. return; // nothing to do
  25332. }
  25333. data = data || this._data;
  25334. if (!data) {
  25335. return;
  25336. }
  25337. if (!this._buffer) {
  25338. if (this._updatable) {
  25339. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25340. this._data = data;
  25341. }
  25342. else {
  25343. this._buffer = this._engine.createVertexBuffer(data);
  25344. }
  25345. }
  25346. else if (this._updatable) {
  25347. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25348. this._data = data;
  25349. }
  25350. };
  25351. Buffer.prototype._rebuild = function () {
  25352. this._buffer = null;
  25353. this.create(this._data);
  25354. };
  25355. Buffer.prototype.update = function (data) {
  25356. this.create(data);
  25357. };
  25358. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25359. if (!this._buffer) {
  25360. return;
  25361. }
  25362. if (this._updatable) {
  25363. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25364. this._data = null;
  25365. }
  25366. };
  25367. Buffer.prototype.dispose = function () {
  25368. if (!this._buffer) {
  25369. return;
  25370. }
  25371. if (this._engine._releaseBuffer(this._buffer)) {
  25372. this._buffer = null;
  25373. }
  25374. };
  25375. return Buffer;
  25376. }());
  25377. BABYLON.Buffer = Buffer;
  25378. })(BABYLON || (BABYLON = {}));
  25379. //# sourceMappingURL=babylon.buffer.js.map
  25380. var BABYLON;
  25381. (function (BABYLON) {
  25382. var VertexBuffer = /** @class */ (function () {
  25383. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25384. if (data instanceof BABYLON.Buffer) {
  25385. if (!stride) {
  25386. stride = data.getStrideSize();
  25387. }
  25388. this._buffer = data;
  25389. this._ownsBuffer = false;
  25390. }
  25391. else {
  25392. if (!stride) {
  25393. stride = VertexBuffer.DeduceStride(kind);
  25394. }
  25395. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25396. this._ownsBuffer = true;
  25397. }
  25398. this._stride = stride;
  25399. this._instanced = instanced !== undefined ? instanced : false;
  25400. this._instanceDivisor = instanced ? 1 : 0;
  25401. this._offset = offset ? offset : 0;
  25402. this._size = size ? size : stride;
  25403. this._kind = kind;
  25404. }
  25405. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25406. /**
  25407. * Gets or sets the instance divisor when in instanced mode
  25408. */
  25409. get: function () {
  25410. return this._instanceDivisor;
  25411. },
  25412. set: function (value) {
  25413. this._instanceDivisor = value;
  25414. if (value == 0) {
  25415. this._instanced = false;
  25416. }
  25417. else {
  25418. this._instanced = true;
  25419. }
  25420. },
  25421. enumerable: true,
  25422. configurable: true
  25423. });
  25424. VertexBuffer.prototype._rebuild = function () {
  25425. if (!this._buffer) {
  25426. return;
  25427. }
  25428. this._buffer._rebuild();
  25429. };
  25430. /**
  25431. * Returns the kind of the VertexBuffer (string).
  25432. */
  25433. VertexBuffer.prototype.getKind = function () {
  25434. return this._kind;
  25435. };
  25436. // Properties
  25437. /**
  25438. * Boolean : is the VertexBuffer updatable ?
  25439. */
  25440. VertexBuffer.prototype.isUpdatable = function () {
  25441. return this._buffer.isUpdatable();
  25442. };
  25443. /**
  25444. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25445. */
  25446. VertexBuffer.prototype.getData = function () {
  25447. return this._buffer.getData();
  25448. };
  25449. /**
  25450. * Returns the WebGLBuffer associated to the VertexBuffer.
  25451. */
  25452. VertexBuffer.prototype.getBuffer = function () {
  25453. return this._buffer.getBuffer();
  25454. };
  25455. /**
  25456. * Returns the stride of the VertexBuffer (integer).
  25457. */
  25458. VertexBuffer.prototype.getStrideSize = function () {
  25459. return this._stride;
  25460. };
  25461. /**
  25462. * Returns the offset (integer).
  25463. */
  25464. VertexBuffer.prototype.getOffset = function () {
  25465. return this._offset;
  25466. };
  25467. /**
  25468. * Returns the VertexBuffer total size (integer).
  25469. */
  25470. VertexBuffer.prototype.getSize = function () {
  25471. return this._size;
  25472. };
  25473. /**
  25474. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25475. */
  25476. VertexBuffer.prototype.getIsInstanced = function () {
  25477. return this._instanced;
  25478. };
  25479. /**
  25480. * Returns the instancing divisor, zero for non-instanced (integer).
  25481. */
  25482. VertexBuffer.prototype.getInstanceDivisor = function () {
  25483. return this._instanceDivisor;
  25484. };
  25485. // Methods
  25486. /**
  25487. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25488. * Returns the created WebGLBuffer.
  25489. */
  25490. VertexBuffer.prototype.create = function (data) {
  25491. return this._buffer.create(data);
  25492. };
  25493. /**
  25494. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25495. * This function will create a new buffer if the current one is not updatable
  25496. * Returns the updated WebGLBuffer.
  25497. */
  25498. VertexBuffer.prototype.update = function (data) {
  25499. return this._buffer.update(data);
  25500. };
  25501. /**
  25502. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25503. * Returns the directly updated WebGLBuffer.
  25504. */
  25505. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25506. return this._buffer.updateDirectly(data, offset);
  25507. };
  25508. /**
  25509. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25510. */
  25511. VertexBuffer.prototype.dispose = function () {
  25512. if (this._ownsBuffer) {
  25513. this._buffer.dispose();
  25514. }
  25515. };
  25516. Object.defineProperty(VertexBuffer, "PositionKind", {
  25517. get: function () {
  25518. return VertexBuffer._PositionKind;
  25519. },
  25520. enumerable: true,
  25521. configurable: true
  25522. });
  25523. Object.defineProperty(VertexBuffer, "NormalKind", {
  25524. get: function () {
  25525. return VertexBuffer._NormalKind;
  25526. },
  25527. enumerable: true,
  25528. configurable: true
  25529. });
  25530. Object.defineProperty(VertexBuffer, "TangentKind", {
  25531. get: function () {
  25532. return VertexBuffer._TangentKind;
  25533. },
  25534. enumerable: true,
  25535. configurable: true
  25536. });
  25537. Object.defineProperty(VertexBuffer, "UVKind", {
  25538. get: function () {
  25539. return VertexBuffer._UVKind;
  25540. },
  25541. enumerable: true,
  25542. configurable: true
  25543. });
  25544. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25545. get: function () {
  25546. return VertexBuffer._UV2Kind;
  25547. },
  25548. enumerable: true,
  25549. configurable: true
  25550. });
  25551. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25552. get: function () {
  25553. return VertexBuffer._UV3Kind;
  25554. },
  25555. enumerable: true,
  25556. configurable: true
  25557. });
  25558. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25559. get: function () {
  25560. return VertexBuffer._UV4Kind;
  25561. },
  25562. enumerable: true,
  25563. configurable: true
  25564. });
  25565. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25566. get: function () {
  25567. return VertexBuffer._UV5Kind;
  25568. },
  25569. enumerable: true,
  25570. configurable: true
  25571. });
  25572. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25573. get: function () {
  25574. return VertexBuffer._UV6Kind;
  25575. },
  25576. enumerable: true,
  25577. configurable: true
  25578. });
  25579. Object.defineProperty(VertexBuffer, "ColorKind", {
  25580. get: function () {
  25581. return VertexBuffer._ColorKind;
  25582. },
  25583. enumerable: true,
  25584. configurable: true
  25585. });
  25586. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25587. get: function () {
  25588. return VertexBuffer._MatricesIndicesKind;
  25589. },
  25590. enumerable: true,
  25591. configurable: true
  25592. });
  25593. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25594. get: function () {
  25595. return VertexBuffer._MatricesWeightsKind;
  25596. },
  25597. enumerable: true,
  25598. configurable: true
  25599. });
  25600. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25601. get: function () {
  25602. return VertexBuffer._MatricesIndicesExtraKind;
  25603. },
  25604. enumerable: true,
  25605. configurable: true
  25606. });
  25607. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25608. get: function () {
  25609. return VertexBuffer._MatricesWeightsExtraKind;
  25610. },
  25611. enumerable: true,
  25612. configurable: true
  25613. });
  25614. /**
  25615. * Deduces the stride given a kind.
  25616. * @param kind The kind string to deduce
  25617. * @returns The deduced stride
  25618. */
  25619. VertexBuffer.DeduceStride = function (kind) {
  25620. switch (kind) {
  25621. case VertexBuffer.PositionKind:
  25622. return 3;
  25623. case VertexBuffer.NormalKind:
  25624. return 3;
  25625. case VertexBuffer.UVKind:
  25626. case VertexBuffer.UV2Kind:
  25627. case VertexBuffer.UV3Kind:
  25628. case VertexBuffer.UV4Kind:
  25629. case VertexBuffer.UV5Kind:
  25630. case VertexBuffer.UV6Kind:
  25631. return 2;
  25632. case VertexBuffer.TangentKind:
  25633. case VertexBuffer.ColorKind:
  25634. return 4;
  25635. case VertexBuffer.MatricesIndicesKind:
  25636. case VertexBuffer.MatricesIndicesExtraKind:
  25637. return 4;
  25638. case VertexBuffer.MatricesWeightsKind:
  25639. case VertexBuffer.MatricesWeightsExtraKind:
  25640. return 4;
  25641. default:
  25642. throw new Error("Invalid kind '" + kind + "'");
  25643. }
  25644. };
  25645. // Enums
  25646. VertexBuffer._PositionKind = "position";
  25647. VertexBuffer._NormalKind = "normal";
  25648. VertexBuffer._TangentKind = "tangent";
  25649. VertexBuffer._UVKind = "uv";
  25650. VertexBuffer._UV2Kind = "uv2";
  25651. VertexBuffer._UV3Kind = "uv3";
  25652. VertexBuffer._UV4Kind = "uv4";
  25653. VertexBuffer._UV5Kind = "uv5";
  25654. VertexBuffer._UV6Kind = "uv6";
  25655. VertexBuffer._ColorKind = "color";
  25656. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25657. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25658. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25659. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25660. return VertexBuffer;
  25661. }());
  25662. BABYLON.VertexBuffer = VertexBuffer;
  25663. })(BABYLON || (BABYLON = {}));
  25664. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25665. var BABYLON;
  25666. (function (BABYLON) {
  25667. /**
  25668. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25669. */
  25670. var DummyInternalTextureTracker = /** @class */ (function () {
  25671. function DummyInternalTextureTracker() {
  25672. /**
  25673. * Gets or set the previous tracker in the list
  25674. */
  25675. this.previous = null;
  25676. /**
  25677. * Gets or set the next tracker in the list
  25678. */
  25679. this.next = null;
  25680. }
  25681. return DummyInternalTextureTracker;
  25682. }());
  25683. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25684. })(BABYLON || (BABYLON = {}));
  25685. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25686. var BABYLON;
  25687. (function (BABYLON) {
  25688. /**
  25689. * Class used to store data associated with WebGL texture data for the engine
  25690. * This class should not be used directly
  25691. */
  25692. var InternalTexture = /** @class */ (function () {
  25693. /**
  25694. * Creates a new InternalTexture
  25695. * @param engine defines the engine to use
  25696. * @param dataSource defines the type of data that will be used
  25697. */
  25698. function InternalTexture(engine, dataSource) {
  25699. /**
  25700. * Observable called when the texture is loaded
  25701. */
  25702. this.onLoadedObservable = new BABYLON.Observable();
  25703. /**
  25704. * Gets or set the previous tracker in the list
  25705. */
  25706. this.previous = null;
  25707. /**
  25708. * Gets or set the next tracker in the list
  25709. */
  25710. this.next = null;
  25711. // Private
  25712. /** @ignore */
  25713. this._initialSlot = -1;
  25714. /** @ignore */
  25715. this._designatedSlot = -1;
  25716. /** @ignore */
  25717. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25718. /** @ignore */
  25719. this._references = 1;
  25720. this._engine = engine;
  25721. this._dataSource = dataSource;
  25722. this._webGLTexture = engine._createTexture();
  25723. }
  25724. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25725. /**
  25726. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25727. */
  25728. get: function () {
  25729. return this._dataSource;
  25730. },
  25731. enumerable: true,
  25732. configurable: true
  25733. });
  25734. /**
  25735. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25736. */
  25737. InternalTexture.prototype.incrementReferences = function () {
  25738. this._references++;
  25739. };
  25740. /**
  25741. * Change the size of the texture (not the size of the content)
  25742. * @param width defines the new width
  25743. * @param height defines the new height
  25744. * @param depth defines the new depth (1 by default)
  25745. */
  25746. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25747. if (depth === void 0) { depth = 1; }
  25748. this.width = width;
  25749. this.height = height;
  25750. this.depth = depth;
  25751. this.baseWidth = width;
  25752. this.baseHeight = height;
  25753. this.baseDepth = depth;
  25754. this._size = width * height * depth;
  25755. };
  25756. /** @ignore */
  25757. InternalTexture.prototype._rebuild = function () {
  25758. var _this = this;
  25759. var proxy;
  25760. this.isReady = false;
  25761. this._cachedCoordinatesMode = null;
  25762. this._cachedWrapU = null;
  25763. this._cachedWrapV = null;
  25764. this._cachedAnisotropicFilteringLevel = null;
  25765. switch (this._dataSource) {
  25766. case InternalTexture.DATASOURCE_TEMP:
  25767. return;
  25768. case InternalTexture.DATASOURCE_URL:
  25769. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25770. _this.isReady = true;
  25771. }, null, this._buffer, undefined, this.format);
  25772. proxy._swapAndDie(this);
  25773. return;
  25774. case InternalTexture.DATASOURCE_RAW:
  25775. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25776. proxy._swapAndDie(this);
  25777. this.isReady = true;
  25778. return;
  25779. case InternalTexture.DATASOURCE_RAW3D:
  25780. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25781. proxy._swapAndDie(this);
  25782. this.isReady = true;
  25783. return;
  25784. case InternalTexture.DATASOURCE_DYNAMIC:
  25785. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25786. proxy._swapAndDie(this);
  25787. // The engine will make sure to update content so no need to flag it as isReady = true
  25788. return;
  25789. case InternalTexture.DATASOURCE_RENDERTARGET:
  25790. var options = new BABYLON.RenderTargetCreationOptions();
  25791. options.generateDepthBuffer = this._generateDepthBuffer;
  25792. options.generateMipMaps = this.generateMipMaps;
  25793. options.generateStencilBuffer = this._generateStencilBuffer;
  25794. options.samplingMode = this.samplingMode;
  25795. options.type = this.type;
  25796. if (this.isCube) {
  25797. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25798. }
  25799. else {
  25800. var size = {
  25801. width: this.width,
  25802. height: this.height
  25803. };
  25804. proxy = this._engine.createRenderTargetTexture(size, options);
  25805. }
  25806. proxy._swapAndDie(this);
  25807. this.isReady = true;
  25808. return;
  25809. case InternalTexture.DATASOURCE_CUBE:
  25810. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25811. _this.isReady = true;
  25812. }, null, this.format, this._extension);
  25813. proxy._swapAndDie(this);
  25814. return;
  25815. case InternalTexture.DATASOURCE_CUBERAW:
  25816. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25817. proxy._swapAndDie(this);
  25818. this.isReady = true;
  25819. return;
  25820. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25821. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25822. if (proxy) {
  25823. proxy._swapAndDie(_this);
  25824. }
  25825. _this.isReady = true;
  25826. }, null, this.format, this._extension);
  25827. return;
  25828. }
  25829. };
  25830. InternalTexture.prototype._swapAndDie = function (target) {
  25831. target._webGLTexture = this._webGLTexture;
  25832. if (this._framebuffer) {
  25833. target._framebuffer = this._framebuffer;
  25834. }
  25835. if (this._depthStencilBuffer) {
  25836. target._depthStencilBuffer = this._depthStencilBuffer;
  25837. }
  25838. if (this._lodTextureHigh) {
  25839. if (target._lodTextureHigh) {
  25840. target._lodTextureHigh.dispose();
  25841. }
  25842. target._lodTextureHigh = this._lodTextureHigh;
  25843. }
  25844. if (this._lodTextureMid) {
  25845. if (target._lodTextureMid) {
  25846. target._lodTextureMid.dispose();
  25847. }
  25848. target._lodTextureMid = this._lodTextureMid;
  25849. }
  25850. if (this._lodTextureLow) {
  25851. if (target._lodTextureLow) {
  25852. target._lodTextureLow.dispose();
  25853. }
  25854. target._lodTextureLow = this._lodTextureLow;
  25855. }
  25856. var cache = this._engine.getLoadedTexturesCache();
  25857. var index = cache.indexOf(this);
  25858. if (index !== -1) {
  25859. cache.splice(index, 1);
  25860. }
  25861. };
  25862. /**
  25863. * Dispose the current allocated resources
  25864. */
  25865. InternalTexture.prototype.dispose = function () {
  25866. if (!this._webGLTexture) {
  25867. return;
  25868. }
  25869. this._references--;
  25870. if (this._references === 0) {
  25871. this._engine._releaseTexture(this);
  25872. this._webGLTexture = null;
  25873. this.previous = null;
  25874. this.next = null;
  25875. }
  25876. };
  25877. /**
  25878. * The source of the texture data is unknown
  25879. */
  25880. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25881. /**
  25882. * Texture data comes from an URL
  25883. */
  25884. InternalTexture.DATASOURCE_URL = 1;
  25885. /**
  25886. * Texture data is only used for temporary storage
  25887. */
  25888. InternalTexture.DATASOURCE_TEMP = 2;
  25889. /**
  25890. * Texture data comes from raw data (ArrayBuffer)
  25891. */
  25892. InternalTexture.DATASOURCE_RAW = 3;
  25893. /**
  25894. * Texture content is dynamic (video or dynamic texture)
  25895. */
  25896. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25897. /**
  25898. * Texture content is generated by rendering to it
  25899. */
  25900. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25901. /**
  25902. * Texture content is part of a multi render target process
  25903. */
  25904. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25905. /**
  25906. * Texture data comes from a cube data file
  25907. */
  25908. InternalTexture.DATASOURCE_CUBE = 7;
  25909. /**
  25910. * Texture data comes from a raw cube data
  25911. */
  25912. InternalTexture.DATASOURCE_CUBERAW = 8;
  25913. /**
  25914. * Texture data come from a prefiltered cube data file
  25915. */
  25916. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25917. /**
  25918. * Texture content is raw 3D data
  25919. */
  25920. InternalTexture.DATASOURCE_RAW3D = 10;
  25921. return InternalTexture;
  25922. }());
  25923. BABYLON.InternalTexture = InternalTexture;
  25924. })(BABYLON || (BABYLON = {}));
  25925. //# sourceMappingURL=babylon.internalTexture.js.map
  25926. var BABYLON;
  25927. (function (BABYLON) {
  25928. var BaseTexture = /** @class */ (function () {
  25929. function BaseTexture(scene) {
  25930. this._hasAlpha = false;
  25931. this.getAlphaFromRGB = false;
  25932. this.level = 1;
  25933. this.coordinatesIndex = 0;
  25934. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25935. /**
  25936. * | Value | Type | Description |
  25937. * | ----- | ------------------ | ----------- |
  25938. * | 0 | CLAMP_ADDRESSMODE | |
  25939. * | 1 | WRAP_ADDRESSMODE | |
  25940. * | 2 | MIRROR_ADDRESSMODE | |
  25941. */
  25942. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25943. /**
  25944. * | Value | Type | Description |
  25945. * | ----- | ------------------ | ----------- |
  25946. * | 0 | CLAMP_ADDRESSMODE | |
  25947. * | 1 | WRAP_ADDRESSMODE | |
  25948. * | 2 | MIRROR_ADDRESSMODE | |
  25949. */
  25950. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25951. /**
  25952. * | Value | Type | Description |
  25953. * | ----- | ------------------ | ----------- |
  25954. * | 0 | CLAMP_ADDRESSMODE | |
  25955. * | 1 | WRAP_ADDRESSMODE | |
  25956. * | 2 | MIRROR_ADDRESSMODE | |
  25957. */
  25958. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25959. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25960. this.isCube = false;
  25961. this.is3D = false;
  25962. this.gammaSpace = true;
  25963. this.invertZ = false;
  25964. this.lodLevelInAlpha = false;
  25965. this.lodGenerationOffset = 0.0;
  25966. this.lodGenerationScale = 0.8;
  25967. this.isRenderTarget = false;
  25968. this.animations = new Array();
  25969. /**
  25970. * An event triggered when the texture is disposed.
  25971. * @type {BABYLON.Observable}
  25972. */
  25973. this.onDisposeObservable = new BABYLON.Observable();
  25974. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25975. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25976. if (this._scene) {
  25977. this._scene.textures.push(this);
  25978. }
  25979. this._uid = null;
  25980. }
  25981. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25982. get: function () {
  25983. return this._hasAlpha;
  25984. },
  25985. set: function (value) {
  25986. if (this._hasAlpha === value) {
  25987. return;
  25988. }
  25989. this._hasAlpha = value;
  25990. if (this._scene) {
  25991. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  25992. }
  25993. },
  25994. enumerable: true,
  25995. configurable: true
  25996. });
  25997. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  25998. get: function () {
  25999. return this._coordinatesMode;
  26000. },
  26001. /**
  26002. * How a texture is mapped.
  26003. *
  26004. * | Value | Type | Description |
  26005. * | ----- | ----------------------------------- | ----------- |
  26006. * | 0 | EXPLICIT_MODE | |
  26007. * | 1 | SPHERICAL_MODE | |
  26008. * | 2 | PLANAR_MODE | |
  26009. * | 3 | CUBIC_MODE | |
  26010. * | 4 | PROJECTION_MODE | |
  26011. * | 5 | SKYBOX_MODE | |
  26012. * | 6 | INVCUBIC_MODE | |
  26013. * | 7 | EQUIRECTANGULAR_MODE | |
  26014. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26015. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26016. */
  26017. set: function (value) {
  26018. if (this._coordinatesMode === value) {
  26019. return;
  26020. }
  26021. this._coordinatesMode = value;
  26022. if (this._scene) {
  26023. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26024. }
  26025. },
  26026. enumerable: true,
  26027. configurable: true
  26028. });
  26029. Object.defineProperty(BaseTexture.prototype, "uid", {
  26030. get: function () {
  26031. if (!this._uid) {
  26032. this._uid = BABYLON.Tools.RandomId();
  26033. }
  26034. return this._uid;
  26035. },
  26036. enumerable: true,
  26037. configurable: true
  26038. });
  26039. BaseTexture.prototype.toString = function () {
  26040. return this.name;
  26041. };
  26042. BaseTexture.prototype.getClassName = function () {
  26043. return "BaseTexture";
  26044. };
  26045. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26046. set: function (callback) {
  26047. if (this._onDisposeObserver) {
  26048. this.onDisposeObservable.remove(this._onDisposeObserver);
  26049. }
  26050. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26051. },
  26052. enumerable: true,
  26053. configurable: true
  26054. });
  26055. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26056. get: function () {
  26057. return true;
  26058. },
  26059. enumerable: true,
  26060. configurable: true
  26061. });
  26062. BaseTexture.prototype.getScene = function () {
  26063. return this._scene;
  26064. };
  26065. BaseTexture.prototype.getTextureMatrix = function () {
  26066. return BABYLON.Matrix.IdentityReadOnly;
  26067. };
  26068. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26069. return BABYLON.Matrix.IdentityReadOnly;
  26070. };
  26071. BaseTexture.prototype.getInternalTexture = function () {
  26072. return this._texture;
  26073. };
  26074. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26075. return !this.isBlocking || this.isReady();
  26076. };
  26077. BaseTexture.prototype.isReady = function () {
  26078. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26079. this.delayLoad();
  26080. return false;
  26081. }
  26082. if (this._texture) {
  26083. return this._texture.isReady;
  26084. }
  26085. return false;
  26086. };
  26087. BaseTexture.prototype.getSize = function () {
  26088. if (this._texture && this._texture.width) {
  26089. return new BABYLON.Size(this._texture.width, this._texture.height);
  26090. }
  26091. if (this._texture && this._texture._size) {
  26092. return new BABYLON.Size(this._texture._size, this._texture._size);
  26093. }
  26094. return BABYLON.Size.Zero();
  26095. };
  26096. BaseTexture.prototype.getBaseSize = function () {
  26097. if (!this.isReady() || !this._texture)
  26098. return BABYLON.Size.Zero();
  26099. if (this._texture._size) {
  26100. return new BABYLON.Size(this._texture._size, this._texture._size);
  26101. }
  26102. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26103. };
  26104. BaseTexture.prototype.scale = function (ratio) {
  26105. };
  26106. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26107. get: function () {
  26108. return false;
  26109. },
  26110. enumerable: true,
  26111. configurable: true
  26112. });
  26113. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26114. if (!this._scene) {
  26115. return null;
  26116. }
  26117. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26118. for (var index = 0; index < texturesCache.length; index++) {
  26119. var texturesCacheEntry = texturesCache[index];
  26120. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26121. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26122. texturesCacheEntry.incrementReferences();
  26123. return texturesCacheEntry;
  26124. }
  26125. }
  26126. }
  26127. return null;
  26128. };
  26129. BaseTexture.prototype._rebuild = function () {
  26130. };
  26131. BaseTexture.prototype.delayLoad = function () {
  26132. };
  26133. BaseTexture.prototype.clone = function () {
  26134. return null;
  26135. };
  26136. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26137. get: function () {
  26138. if (!this._texture) {
  26139. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26140. }
  26141. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26142. },
  26143. enumerable: true,
  26144. configurable: true
  26145. });
  26146. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26147. get: function () {
  26148. if (!this._texture) {
  26149. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26150. }
  26151. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26152. },
  26153. enumerable: true,
  26154. configurable: true
  26155. });
  26156. BaseTexture.prototype.readPixels = function (faceIndex) {
  26157. if (faceIndex === void 0) { faceIndex = 0; }
  26158. if (!this._texture) {
  26159. return null;
  26160. }
  26161. var size = this.getSize();
  26162. var scene = this.getScene();
  26163. if (!scene) {
  26164. return null;
  26165. }
  26166. var engine = scene.getEngine();
  26167. if (this._texture.isCube) {
  26168. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26169. }
  26170. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26171. };
  26172. BaseTexture.prototype.releaseInternalTexture = function () {
  26173. if (this._texture) {
  26174. this._texture.dispose();
  26175. this._texture = null;
  26176. }
  26177. };
  26178. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26179. get: function () {
  26180. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26181. return null;
  26182. }
  26183. if (!this._texture._sphericalPolynomial) {
  26184. this._texture._sphericalPolynomial =
  26185. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26186. }
  26187. return this._texture._sphericalPolynomial;
  26188. },
  26189. set: function (value) {
  26190. if (this._texture) {
  26191. this._texture._sphericalPolynomial = value;
  26192. }
  26193. },
  26194. enumerable: true,
  26195. configurable: true
  26196. });
  26197. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26198. get: function () {
  26199. if (this._texture) {
  26200. return this._texture._lodTextureHigh;
  26201. }
  26202. return null;
  26203. },
  26204. enumerable: true,
  26205. configurable: true
  26206. });
  26207. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26208. get: function () {
  26209. if (this._texture) {
  26210. return this._texture._lodTextureMid;
  26211. }
  26212. return null;
  26213. },
  26214. enumerable: true,
  26215. configurable: true
  26216. });
  26217. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26218. get: function () {
  26219. if (this._texture) {
  26220. return this._texture._lodTextureLow;
  26221. }
  26222. return null;
  26223. },
  26224. enumerable: true,
  26225. configurable: true
  26226. });
  26227. BaseTexture.prototype.dispose = function () {
  26228. if (!this._scene) {
  26229. return;
  26230. }
  26231. // Animations
  26232. this._scene.stopAnimation(this);
  26233. // Remove from scene
  26234. this._scene._removePendingData(this);
  26235. var index = this._scene.textures.indexOf(this);
  26236. if (index >= 0) {
  26237. this._scene.textures.splice(index, 1);
  26238. }
  26239. if (this._texture === undefined) {
  26240. return;
  26241. }
  26242. // Release
  26243. this.releaseInternalTexture();
  26244. // Callback
  26245. this.onDisposeObservable.notifyObservers(this);
  26246. this.onDisposeObservable.clear();
  26247. };
  26248. BaseTexture.prototype.serialize = function () {
  26249. if (!this.name) {
  26250. return null;
  26251. }
  26252. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26253. // Animations
  26254. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26255. return serializationObject;
  26256. };
  26257. BaseTexture.WhenAllReady = function (textures, callback) {
  26258. var numRemaining = textures.length;
  26259. if (numRemaining === 0) {
  26260. callback();
  26261. return;
  26262. }
  26263. var _loop_1 = function () {
  26264. texture = textures[i];
  26265. if (texture.isReady()) {
  26266. if (--numRemaining === 0) {
  26267. callback();
  26268. }
  26269. }
  26270. else {
  26271. onLoadObservable = texture.onLoadObservable;
  26272. var onLoadCallback_1 = function () {
  26273. onLoadObservable.removeCallback(onLoadCallback_1);
  26274. if (--numRemaining === 0) {
  26275. callback();
  26276. }
  26277. };
  26278. onLoadObservable.add(onLoadCallback_1);
  26279. }
  26280. };
  26281. var texture, onLoadObservable;
  26282. for (var i = 0; i < textures.length; i++) {
  26283. _loop_1();
  26284. }
  26285. };
  26286. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26287. __decorate([
  26288. BABYLON.serialize()
  26289. ], BaseTexture.prototype, "name", void 0);
  26290. __decorate([
  26291. BABYLON.serialize("hasAlpha")
  26292. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26293. __decorate([
  26294. BABYLON.serialize()
  26295. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26296. __decorate([
  26297. BABYLON.serialize()
  26298. ], BaseTexture.prototype, "level", void 0);
  26299. __decorate([
  26300. BABYLON.serialize()
  26301. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26302. __decorate([
  26303. BABYLON.serialize("coordinatesMode")
  26304. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26305. __decorate([
  26306. BABYLON.serialize()
  26307. ], BaseTexture.prototype, "wrapU", void 0);
  26308. __decorate([
  26309. BABYLON.serialize()
  26310. ], BaseTexture.prototype, "wrapV", void 0);
  26311. __decorate([
  26312. BABYLON.serialize()
  26313. ], BaseTexture.prototype, "wrapR", void 0);
  26314. __decorate([
  26315. BABYLON.serialize()
  26316. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26317. __decorate([
  26318. BABYLON.serialize()
  26319. ], BaseTexture.prototype, "isCube", void 0);
  26320. __decorate([
  26321. BABYLON.serialize()
  26322. ], BaseTexture.prototype, "is3D", void 0);
  26323. __decorate([
  26324. BABYLON.serialize()
  26325. ], BaseTexture.prototype, "gammaSpace", void 0);
  26326. __decorate([
  26327. BABYLON.serialize()
  26328. ], BaseTexture.prototype, "invertZ", void 0);
  26329. __decorate([
  26330. BABYLON.serialize()
  26331. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26332. __decorate([
  26333. BABYLON.serialize()
  26334. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26335. __decorate([
  26336. BABYLON.serialize()
  26337. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26338. __decorate([
  26339. BABYLON.serialize()
  26340. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26341. return BaseTexture;
  26342. }());
  26343. BABYLON.BaseTexture = BaseTexture;
  26344. })(BABYLON || (BABYLON = {}));
  26345. //# sourceMappingURL=babylon.baseTexture.js.map
  26346. var BABYLON;
  26347. (function (BABYLON) {
  26348. var Texture = /** @class */ (function (_super) {
  26349. __extends(Texture, _super);
  26350. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26351. if (noMipmap === void 0) { noMipmap = false; }
  26352. if (invertY === void 0) { invertY = true; }
  26353. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26354. if (onLoad === void 0) { onLoad = null; }
  26355. if (onError === void 0) { onError = null; }
  26356. if (buffer === void 0) { buffer = null; }
  26357. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26358. var _this = _super.call(this, scene) || this;
  26359. _this.uOffset = 0;
  26360. _this.vOffset = 0;
  26361. _this.uScale = 1.0;
  26362. _this.vScale = 1.0;
  26363. _this.uAng = 0;
  26364. _this.vAng = 0;
  26365. _this.wAng = 0;
  26366. _this._isBlocking = true;
  26367. _this.name = url || "";
  26368. _this.url = url;
  26369. _this._noMipmap = noMipmap;
  26370. _this._invertY = invertY;
  26371. _this._samplingMode = samplingMode;
  26372. _this._buffer = buffer;
  26373. _this._deleteBuffer = deleteBuffer;
  26374. if (format) {
  26375. _this._format = format;
  26376. }
  26377. scene = _this.getScene();
  26378. if (!scene) {
  26379. return _this;
  26380. }
  26381. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26382. var load = function () {
  26383. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26384. _this.onLoadObservable.notifyObservers(_this);
  26385. }
  26386. if (onLoad) {
  26387. onLoad();
  26388. }
  26389. if (!_this.isBlocking && scene) {
  26390. scene.resetCachedMaterial();
  26391. }
  26392. };
  26393. if (!_this.url) {
  26394. _this._delayedOnLoad = load;
  26395. _this._delayedOnError = onError;
  26396. return _this;
  26397. }
  26398. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26399. if (!_this._texture) {
  26400. if (!scene.useDelayedTextureLoading) {
  26401. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26402. if (deleteBuffer) {
  26403. delete _this._buffer;
  26404. }
  26405. }
  26406. else {
  26407. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26408. _this._delayedOnLoad = load;
  26409. _this._delayedOnError = onError;
  26410. }
  26411. }
  26412. else {
  26413. if (_this._texture.isReady) {
  26414. BABYLON.Tools.SetImmediate(function () { return load(); });
  26415. }
  26416. else {
  26417. _this._texture.onLoadedObservable.add(load);
  26418. }
  26419. }
  26420. return _this;
  26421. }
  26422. Object.defineProperty(Texture.prototype, "noMipmap", {
  26423. get: function () {
  26424. return this._noMipmap;
  26425. },
  26426. enumerable: true,
  26427. configurable: true
  26428. });
  26429. Object.defineProperty(Texture.prototype, "isBlocking", {
  26430. get: function () {
  26431. return this._isBlocking;
  26432. },
  26433. set: function (value) {
  26434. this._isBlocking = value;
  26435. },
  26436. enumerable: true,
  26437. configurable: true
  26438. });
  26439. Object.defineProperty(Texture.prototype, "samplingMode", {
  26440. get: function () {
  26441. return this._samplingMode;
  26442. },
  26443. enumerable: true,
  26444. configurable: true
  26445. });
  26446. Texture.prototype.updateURL = function (url) {
  26447. this.url = url;
  26448. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26449. this.delayLoad();
  26450. };
  26451. Texture.prototype.delayLoad = function () {
  26452. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26453. return;
  26454. }
  26455. var scene = this.getScene();
  26456. if (!scene) {
  26457. return;
  26458. }
  26459. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26460. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26461. if (!this._texture) {
  26462. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26463. if (this._deleteBuffer) {
  26464. delete this._buffer;
  26465. }
  26466. }
  26467. else {
  26468. if (this._delayedOnLoad) {
  26469. if (this._texture.isReady) {
  26470. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26471. }
  26472. else {
  26473. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26474. }
  26475. }
  26476. }
  26477. this._delayedOnLoad = null;
  26478. this._delayedOnError = null;
  26479. };
  26480. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26481. if (!this._texture) {
  26482. return;
  26483. }
  26484. var scene = this.getScene();
  26485. if (!scene) {
  26486. return;
  26487. }
  26488. this._samplingMode = samplingMode;
  26489. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26490. };
  26491. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26492. x *= this.uScale;
  26493. y *= this.vScale;
  26494. x -= 0.5 * this.uScale;
  26495. y -= 0.5 * this.vScale;
  26496. z -= 0.5;
  26497. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26498. t.x += 0.5 * this.uScale + this.uOffset;
  26499. t.y += 0.5 * this.vScale + this.vOffset;
  26500. t.z += 0.5;
  26501. };
  26502. Texture.prototype.getTextureMatrix = function () {
  26503. var _this = this;
  26504. if (this.uOffset === this._cachedUOffset &&
  26505. this.vOffset === this._cachedVOffset &&
  26506. this.uScale === this._cachedUScale &&
  26507. this.vScale === this._cachedVScale &&
  26508. this.uAng === this._cachedUAng &&
  26509. this.vAng === this._cachedVAng &&
  26510. this.wAng === this._cachedWAng) {
  26511. return this._cachedTextureMatrix;
  26512. }
  26513. this._cachedUOffset = this.uOffset;
  26514. this._cachedVOffset = this.vOffset;
  26515. this._cachedUScale = this.uScale;
  26516. this._cachedVScale = this.vScale;
  26517. this._cachedUAng = this.uAng;
  26518. this._cachedVAng = this.vAng;
  26519. this._cachedWAng = this.wAng;
  26520. if (!this._cachedTextureMatrix) {
  26521. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26522. this._rowGenerationMatrix = new BABYLON.Matrix();
  26523. this._t0 = BABYLON.Vector3.Zero();
  26524. this._t1 = BABYLON.Vector3.Zero();
  26525. this._t2 = BABYLON.Vector3.Zero();
  26526. }
  26527. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26528. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26529. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26530. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26531. this._t1.subtractInPlace(this._t0);
  26532. this._t2.subtractInPlace(this._t0);
  26533. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26534. this._cachedTextureMatrix.m[0] = this._t1.x;
  26535. this._cachedTextureMatrix.m[1] = this._t1.y;
  26536. this._cachedTextureMatrix.m[2] = this._t1.z;
  26537. this._cachedTextureMatrix.m[4] = this._t2.x;
  26538. this._cachedTextureMatrix.m[5] = this._t2.y;
  26539. this._cachedTextureMatrix.m[6] = this._t2.z;
  26540. this._cachedTextureMatrix.m[8] = this._t0.x;
  26541. this._cachedTextureMatrix.m[9] = this._t0.y;
  26542. this._cachedTextureMatrix.m[10] = this._t0.z;
  26543. var scene = this.getScene();
  26544. if (!scene) {
  26545. return this._cachedTextureMatrix;
  26546. }
  26547. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26548. return mat.hasTexture(_this);
  26549. });
  26550. return this._cachedTextureMatrix;
  26551. };
  26552. Texture.prototype.getReflectionTextureMatrix = function () {
  26553. var _this = this;
  26554. var scene = this.getScene();
  26555. if (!scene) {
  26556. return this._cachedTextureMatrix;
  26557. }
  26558. if (this.uOffset === this._cachedUOffset &&
  26559. this.vOffset === this._cachedVOffset &&
  26560. this.uScale === this._cachedUScale &&
  26561. this.vScale === this._cachedVScale &&
  26562. this.coordinatesMode === this._cachedCoordinatesMode) {
  26563. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26564. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26565. return this._cachedTextureMatrix;
  26566. }
  26567. }
  26568. else {
  26569. return this._cachedTextureMatrix;
  26570. }
  26571. }
  26572. if (!this._cachedTextureMatrix) {
  26573. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26574. }
  26575. if (!this._projectionModeMatrix) {
  26576. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26577. }
  26578. this._cachedUOffset = this.uOffset;
  26579. this._cachedVOffset = this.vOffset;
  26580. this._cachedUScale = this.uScale;
  26581. this._cachedVScale = this.vScale;
  26582. this._cachedCoordinatesMode = this.coordinatesMode;
  26583. switch (this.coordinatesMode) {
  26584. case Texture.PLANAR_MODE:
  26585. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26586. this._cachedTextureMatrix[0] = this.uScale;
  26587. this._cachedTextureMatrix[5] = this.vScale;
  26588. this._cachedTextureMatrix[12] = this.uOffset;
  26589. this._cachedTextureMatrix[13] = this.vOffset;
  26590. break;
  26591. case Texture.PROJECTION_MODE:
  26592. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26593. this._projectionModeMatrix.m[0] = 0.5;
  26594. this._projectionModeMatrix.m[5] = -0.5;
  26595. this._projectionModeMatrix.m[10] = 0.0;
  26596. this._projectionModeMatrix.m[12] = 0.5;
  26597. this._projectionModeMatrix.m[13] = 0.5;
  26598. this._projectionModeMatrix.m[14] = 1.0;
  26599. this._projectionModeMatrix.m[15] = 1.0;
  26600. var projectionMatrix = scene.getProjectionMatrix();
  26601. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26602. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26603. break;
  26604. default:
  26605. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26606. break;
  26607. }
  26608. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26609. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26610. });
  26611. return this._cachedTextureMatrix;
  26612. };
  26613. Texture.prototype.clone = function () {
  26614. var _this = this;
  26615. return BABYLON.SerializationHelper.Clone(function () {
  26616. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26617. }, this);
  26618. };
  26619. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26620. get: function () {
  26621. if (!this._onLoadObservable) {
  26622. this._onLoadObservable = new BABYLON.Observable();
  26623. }
  26624. return this._onLoadObservable;
  26625. },
  26626. enumerable: true,
  26627. configurable: true
  26628. });
  26629. Texture.prototype.serialize = function () {
  26630. var serializationObject = _super.prototype.serialize.call(this);
  26631. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26632. serializationObject.base64String = this._buffer;
  26633. serializationObject.name = serializationObject.name.replace("data:", "");
  26634. }
  26635. return serializationObject;
  26636. };
  26637. Texture.prototype.getClassName = function () {
  26638. return "Texture";
  26639. };
  26640. Texture.prototype.dispose = function () {
  26641. _super.prototype.dispose.call(this);
  26642. if (this.onLoadObservable) {
  26643. this.onLoadObservable.clear();
  26644. this._onLoadObservable = null;
  26645. }
  26646. this._delayedOnLoad = null;
  26647. this._delayedOnError = null;
  26648. };
  26649. // Statics
  26650. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26651. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26652. if (onLoad === void 0) { onLoad = null; }
  26653. if (onError === void 0) { onError = null; }
  26654. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26655. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26656. };
  26657. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26658. if (parsedTexture.customType) {
  26659. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26660. // Update Sampling Mode
  26661. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26662. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26663. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26664. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26665. }
  26666. }
  26667. return parsedCustomTexture;
  26668. }
  26669. if (parsedTexture.isCube) {
  26670. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26671. }
  26672. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26673. return null;
  26674. }
  26675. var texture = BABYLON.SerializationHelper.Parse(function () {
  26676. var generateMipMaps = true;
  26677. if (parsedTexture.noMipmap) {
  26678. generateMipMaps = false;
  26679. }
  26680. if (parsedTexture.mirrorPlane) {
  26681. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26682. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26683. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26684. return mirrorTexture;
  26685. }
  26686. else if (parsedTexture.isRenderTarget) {
  26687. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26688. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26689. return renderTargetTexture;
  26690. }
  26691. else {
  26692. var texture;
  26693. if (parsedTexture.base64String) {
  26694. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26695. }
  26696. else {
  26697. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26698. }
  26699. return texture;
  26700. }
  26701. }, parsedTexture, scene);
  26702. // Update Sampling Mode
  26703. if (parsedTexture.samplingMode) {
  26704. var sampling = parsedTexture.samplingMode;
  26705. if (texture._samplingMode !== sampling) {
  26706. texture.updateSamplingMode(sampling);
  26707. }
  26708. }
  26709. // Animations
  26710. if (parsedTexture.animations) {
  26711. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26712. var parsedAnimation = parsedTexture.animations[animationIndex];
  26713. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26714. }
  26715. }
  26716. return texture;
  26717. };
  26718. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26719. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26720. if (noMipmap === void 0) { noMipmap = false; }
  26721. if (invertY === void 0) { invertY = true; }
  26722. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26723. if (onLoad === void 0) { onLoad = null; }
  26724. if (onError === void 0) { onError = null; }
  26725. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26726. if (name.substr(0, 5) !== "data:") {
  26727. name = "data:" + name;
  26728. }
  26729. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26730. };
  26731. // Constants
  26732. Texture.NEAREST_SAMPLINGMODE = 1;
  26733. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26734. Texture.BILINEAR_SAMPLINGMODE = 2;
  26735. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26736. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26737. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26738. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26739. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26740. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26741. Texture.NEAREST_LINEAR = 7;
  26742. Texture.NEAREST_NEAREST = 8;
  26743. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26744. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26745. Texture.LINEAR_LINEAR = 11;
  26746. Texture.LINEAR_NEAREST = 12;
  26747. Texture.EXPLICIT_MODE = 0;
  26748. Texture.SPHERICAL_MODE = 1;
  26749. Texture.PLANAR_MODE = 2;
  26750. Texture.CUBIC_MODE = 3;
  26751. Texture.PROJECTION_MODE = 4;
  26752. Texture.SKYBOX_MODE = 5;
  26753. Texture.INVCUBIC_MODE = 6;
  26754. Texture.EQUIRECTANGULAR_MODE = 7;
  26755. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26756. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26757. Texture.CLAMP_ADDRESSMODE = 0;
  26758. Texture.WRAP_ADDRESSMODE = 1;
  26759. Texture.MIRROR_ADDRESSMODE = 2;
  26760. __decorate([
  26761. BABYLON.serialize()
  26762. ], Texture.prototype, "url", void 0);
  26763. __decorate([
  26764. BABYLON.serialize()
  26765. ], Texture.prototype, "uOffset", void 0);
  26766. __decorate([
  26767. BABYLON.serialize()
  26768. ], Texture.prototype, "vOffset", void 0);
  26769. __decorate([
  26770. BABYLON.serialize()
  26771. ], Texture.prototype, "uScale", void 0);
  26772. __decorate([
  26773. BABYLON.serialize()
  26774. ], Texture.prototype, "vScale", void 0);
  26775. __decorate([
  26776. BABYLON.serialize()
  26777. ], Texture.prototype, "uAng", void 0);
  26778. __decorate([
  26779. BABYLON.serialize()
  26780. ], Texture.prototype, "vAng", void 0);
  26781. __decorate([
  26782. BABYLON.serialize()
  26783. ], Texture.prototype, "wAng", void 0);
  26784. __decorate([
  26785. BABYLON.serialize()
  26786. ], Texture.prototype, "isBlocking", null);
  26787. return Texture;
  26788. }(BABYLON.BaseTexture));
  26789. BABYLON.Texture = Texture;
  26790. })(BABYLON || (BABYLON = {}));
  26791. //# sourceMappingURL=babylon.texture.js.map
  26792. var BABYLON;
  26793. (function (BABYLON) {
  26794. var _InstancesBatch = /** @class */ (function () {
  26795. function _InstancesBatch() {
  26796. this.mustReturn = false;
  26797. this.visibleInstances = new Array();
  26798. this.renderSelf = new Array();
  26799. }
  26800. return _InstancesBatch;
  26801. }());
  26802. BABYLON._InstancesBatch = _InstancesBatch;
  26803. var Mesh = /** @class */ (function (_super) {
  26804. __extends(Mesh, _super);
  26805. /**
  26806. * @constructor
  26807. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26808. * @param {Scene} scene The scene to add this mesh to.
  26809. * @param {Node} parent The parent of this mesh, if it has one
  26810. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26811. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26812. * When false, achieved by calling a clone(), also passing False.
  26813. * This will make creation of children, recursive.
  26814. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26815. */
  26816. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26817. if (scene === void 0) { scene = null; }
  26818. if (parent === void 0) { parent = null; }
  26819. if (source === void 0) { source = null; }
  26820. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26821. var _this = _super.call(this, name, scene) || this;
  26822. // Events
  26823. /**
  26824. * An event triggered before rendering the mesh
  26825. * @type {BABYLON.Observable}
  26826. */
  26827. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26828. /**
  26829. * An event triggered after rendering the mesh
  26830. * @type {BABYLON.Observable}
  26831. */
  26832. _this.onAfterRenderObservable = new BABYLON.Observable();
  26833. /**
  26834. * An event triggered before drawing the mesh
  26835. * @type {BABYLON.Observable}
  26836. */
  26837. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26838. // Members
  26839. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26840. _this.instances = new Array();
  26841. _this._LODLevels = new Array();
  26842. _this._visibleInstances = {};
  26843. _this._renderIdForInstances = new Array();
  26844. _this._batchCache = new _InstancesBatch();
  26845. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26846. // Use by builder only to know what orientation were the mesh build in.
  26847. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26848. _this.overrideMaterialSideOrientation = null;
  26849. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26850. // Will be used to save a source mesh reference, If any
  26851. _this._source = null;
  26852. scene = _this.getScene();
  26853. if (source) {
  26854. // Source mesh
  26855. _this._source = source;
  26856. // Geometry
  26857. if (source._geometry) {
  26858. source._geometry.applyToMesh(_this);
  26859. }
  26860. // Deep copy
  26861. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26862. // Metadata
  26863. if (source.metadata && source.metadata.clone) {
  26864. _this.metadata = source.metadata.clone();
  26865. }
  26866. else {
  26867. _this.metadata = source.metadata;
  26868. }
  26869. // Tags
  26870. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26871. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26872. }
  26873. // Parent
  26874. _this.parent = source.parent;
  26875. // Pivot
  26876. _this.setPivotMatrix(source.getPivotMatrix());
  26877. _this.id = name + "." + source.id;
  26878. // Material
  26879. _this.material = source.material;
  26880. var index;
  26881. if (!doNotCloneChildren) {
  26882. // Children
  26883. var directDescendants = source.getDescendants(true);
  26884. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26885. var child = directDescendants[index_1];
  26886. if (child.clone) {
  26887. child.clone(name + "." + child.name, _this);
  26888. }
  26889. }
  26890. }
  26891. // Physics clone
  26892. var physicsEngine = _this.getScene().getPhysicsEngine();
  26893. if (clonePhysicsImpostor && physicsEngine) {
  26894. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26895. if (impostor) {
  26896. _this.physicsImpostor = impostor.clone(_this);
  26897. }
  26898. }
  26899. // Particles
  26900. for (index = 0; index < scene.particleSystems.length; index++) {
  26901. var system = scene.particleSystems[index];
  26902. if (system.emitter === source) {
  26903. system.clone(system.name, _this);
  26904. }
  26905. }
  26906. _this.computeWorldMatrix(true);
  26907. }
  26908. // Parent
  26909. if (parent !== null) {
  26910. _this.parent = parent;
  26911. }
  26912. return _this;
  26913. }
  26914. Object.defineProperty(Mesh, "FRONTSIDE", {
  26915. /**
  26916. * Mesh side orientation : usually the external or front surface
  26917. */
  26918. get: function () {
  26919. return Mesh._FRONTSIDE;
  26920. },
  26921. enumerable: true,
  26922. configurable: true
  26923. });
  26924. Object.defineProperty(Mesh, "BACKSIDE", {
  26925. /**
  26926. * Mesh side orientation : usually the internal or back surface
  26927. */
  26928. get: function () {
  26929. return Mesh._BACKSIDE;
  26930. },
  26931. enumerable: true,
  26932. configurable: true
  26933. });
  26934. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26935. /**
  26936. * Mesh side orientation : both internal and external or front and back surfaces
  26937. */
  26938. get: function () {
  26939. return Mesh._DOUBLESIDE;
  26940. },
  26941. enumerable: true,
  26942. configurable: true
  26943. });
  26944. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26945. /**
  26946. * Mesh side orientation : by default, `FRONTSIDE`
  26947. */
  26948. get: function () {
  26949. return Mesh._DEFAULTSIDE;
  26950. },
  26951. enumerable: true,
  26952. configurable: true
  26953. });
  26954. Object.defineProperty(Mesh, "NO_CAP", {
  26955. /**
  26956. * Mesh cap setting : no cap
  26957. */
  26958. get: function () {
  26959. return Mesh._NO_CAP;
  26960. },
  26961. enumerable: true,
  26962. configurable: true
  26963. });
  26964. Object.defineProperty(Mesh, "CAP_START", {
  26965. /**
  26966. * Mesh cap setting : one cap at the beginning of the mesh
  26967. */
  26968. get: function () {
  26969. return Mesh._CAP_START;
  26970. },
  26971. enumerable: true,
  26972. configurable: true
  26973. });
  26974. Object.defineProperty(Mesh, "CAP_END", {
  26975. /**
  26976. * Mesh cap setting : one cap at the end of the mesh
  26977. */
  26978. get: function () {
  26979. return Mesh._CAP_END;
  26980. },
  26981. enumerable: true,
  26982. configurable: true
  26983. });
  26984. Object.defineProperty(Mesh, "CAP_ALL", {
  26985. /**
  26986. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26987. */
  26988. get: function () {
  26989. return Mesh._CAP_ALL;
  26990. },
  26991. enumerable: true,
  26992. configurable: true
  26993. });
  26994. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  26995. set: function (callback) {
  26996. if (this._onBeforeDrawObserver) {
  26997. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  26998. }
  26999. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27000. },
  27001. enumerable: true,
  27002. configurable: true
  27003. });
  27004. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27005. get: function () {
  27006. return this._morphTargetManager;
  27007. },
  27008. set: function (value) {
  27009. if (this._morphTargetManager === value) {
  27010. return;
  27011. }
  27012. this._morphTargetManager = value;
  27013. this._syncGeometryWithMorphTargetManager();
  27014. },
  27015. enumerable: true,
  27016. configurable: true
  27017. });
  27018. Object.defineProperty(Mesh.prototype, "source", {
  27019. get: function () {
  27020. return this._source;
  27021. },
  27022. enumerable: true,
  27023. configurable: true
  27024. });
  27025. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27026. get: function () {
  27027. return this._unIndexed;
  27028. },
  27029. set: function (value) {
  27030. if (this._unIndexed !== value) {
  27031. this._unIndexed = value;
  27032. this._markSubMeshesAsAttributesDirty();
  27033. }
  27034. },
  27035. enumerable: true,
  27036. configurable: true
  27037. });
  27038. // Methods
  27039. /**
  27040. * Returns the string "Mesh".
  27041. */
  27042. Mesh.prototype.getClassName = function () {
  27043. return "Mesh";
  27044. };
  27045. /**
  27046. * Returns a string.
  27047. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27048. */
  27049. Mesh.prototype.toString = function (fullDetails) {
  27050. var ret = _super.prototype.toString.call(this, fullDetails);
  27051. ret += ", n vertices: " + this.getTotalVertices();
  27052. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27053. if (this.animations) {
  27054. for (var i = 0; i < this.animations.length; i++) {
  27055. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27056. }
  27057. }
  27058. if (fullDetails) {
  27059. if (this._geometry) {
  27060. var ib = this.getIndices();
  27061. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27062. if (vb && ib) {
  27063. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27064. }
  27065. }
  27066. else {
  27067. ret += ", flat shading: UNKNOWN";
  27068. }
  27069. }
  27070. return ret;
  27071. };
  27072. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27073. /**
  27074. * True if the mesh has some Levels Of Details (LOD).
  27075. * Returns a boolean.
  27076. */
  27077. get: function () {
  27078. return this._LODLevels.length > 0;
  27079. },
  27080. enumerable: true,
  27081. configurable: true
  27082. });
  27083. /**
  27084. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27085. * @returns an array of {BABYLON.MeshLODLevel}
  27086. */
  27087. Mesh.prototype.getLODLevels = function () {
  27088. return this._LODLevels;
  27089. };
  27090. Mesh.prototype._sortLODLevels = function () {
  27091. this._LODLevels.sort(function (a, b) {
  27092. if (a.distance < b.distance) {
  27093. return 1;
  27094. }
  27095. if (a.distance > b.distance) {
  27096. return -1;
  27097. }
  27098. return 0;
  27099. });
  27100. };
  27101. /**
  27102. * Add a mesh as LOD level triggered at the given distance.
  27103. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27104. * @param {number} distance The distance from the center of the object to show this level
  27105. * @param {Mesh} mesh The mesh to be added as LOD level
  27106. * @return {Mesh} This mesh (for chaining)
  27107. */
  27108. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27109. if (mesh && mesh._masterMesh) {
  27110. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27111. return this;
  27112. }
  27113. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27114. this._LODLevels.push(level);
  27115. if (mesh) {
  27116. mesh._masterMesh = this;
  27117. }
  27118. this._sortLODLevels();
  27119. return this;
  27120. };
  27121. /**
  27122. * Returns the LOD level mesh at the passed distance or null if not found.
  27123. * It is related to the method `addLODLevel(distance, mesh)`.
  27124. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27125. * Returns an object Mesh or `null`.
  27126. */
  27127. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27128. for (var index = 0; index < this._LODLevels.length; index++) {
  27129. var level = this._LODLevels[index];
  27130. if (level.distance === distance) {
  27131. return level.mesh;
  27132. }
  27133. }
  27134. return null;
  27135. };
  27136. /**
  27137. * Remove a mesh from the LOD array
  27138. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27139. * @param {Mesh} mesh The mesh to be removed.
  27140. * @return {Mesh} This mesh (for chaining)
  27141. */
  27142. Mesh.prototype.removeLODLevel = function (mesh) {
  27143. for (var index = 0; index < this._LODLevels.length; index++) {
  27144. if (this._LODLevels[index].mesh === mesh) {
  27145. this._LODLevels.splice(index, 1);
  27146. if (mesh) {
  27147. mesh._masterMesh = null;
  27148. }
  27149. }
  27150. }
  27151. this._sortLODLevels();
  27152. return this;
  27153. };
  27154. /**
  27155. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27156. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27157. */
  27158. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27159. if (!this._LODLevels || this._LODLevels.length === 0) {
  27160. return this;
  27161. }
  27162. var bSphere;
  27163. if (boundingSphere) {
  27164. bSphere = boundingSphere;
  27165. }
  27166. else {
  27167. var boundingInfo = this.getBoundingInfo();
  27168. bSphere = boundingInfo.boundingSphere;
  27169. }
  27170. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27171. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27172. if (this.onLODLevelSelection) {
  27173. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27174. }
  27175. return this;
  27176. }
  27177. for (var index = 0; index < this._LODLevels.length; index++) {
  27178. var level = this._LODLevels[index];
  27179. if (level.distance < distanceToCamera) {
  27180. if (level.mesh) {
  27181. level.mesh._preActivate();
  27182. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27183. }
  27184. if (this.onLODLevelSelection) {
  27185. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27186. }
  27187. return level.mesh;
  27188. }
  27189. }
  27190. if (this.onLODLevelSelection) {
  27191. this.onLODLevelSelection(distanceToCamera, this, this);
  27192. }
  27193. return this;
  27194. };
  27195. Object.defineProperty(Mesh.prototype, "geometry", {
  27196. /**
  27197. * Returns the mesh internal Geometry object.
  27198. */
  27199. get: function () {
  27200. return this._geometry;
  27201. },
  27202. enumerable: true,
  27203. configurable: true
  27204. });
  27205. /**
  27206. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27207. */
  27208. Mesh.prototype.getTotalVertices = function () {
  27209. if (this._geometry === null || this._geometry === undefined) {
  27210. return 0;
  27211. }
  27212. return this._geometry.getTotalVertices();
  27213. };
  27214. /**
  27215. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27216. * 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.
  27217. * You can force the copy with forceCopy === true
  27218. * Returns null if the mesh has no geometry or no vertex buffer.
  27219. * Possible `kind` values :
  27220. * - BABYLON.VertexBuffer.PositionKind
  27221. * - BABYLON.VertexBuffer.UVKind
  27222. * - BABYLON.VertexBuffer.UV2Kind
  27223. * - BABYLON.VertexBuffer.UV3Kind
  27224. * - BABYLON.VertexBuffer.UV4Kind
  27225. * - BABYLON.VertexBuffer.UV5Kind
  27226. * - BABYLON.VertexBuffer.UV6Kind
  27227. * - BABYLON.VertexBuffer.ColorKind
  27228. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27229. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27230. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27231. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27232. */
  27233. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27234. if (!this._geometry) {
  27235. return null;
  27236. }
  27237. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27238. };
  27239. /**
  27240. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27241. * Returns `null` if the mesh has no geometry.
  27242. * Possible `kind` values :
  27243. * - BABYLON.VertexBuffer.PositionKind
  27244. * - BABYLON.VertexBuffer.UVKind
  27245. * - BABYLON.VertexBuffer.UV2Kind
  27246. * - BABYLON.VertexBuffer.UV3Kind
  27247. * - BABYLON.VertexBuffer.UV4Kind
  27248. * - BABYLON.VertexBuffer.UV5Kind
  27249. * - BABYLON.VertexBuffer.UV6Kind
  27250. * - BABYLON.VertexBuffer.ColorKind
  27251. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27252. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27253. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27254. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27255. */
  27256. Mesh.prototype.getVertexBuffer = function (kind) {
  27257. if (!this._geometry) {
  27258. return null;
  27259. }
  27260. return this._geometry.getVertexBuffer(kind);
  27261. };
  27262. /**
  27263. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27264. * Possible `kind` values :
  27265. * - BABYLON.VertexBuffer.PositionKind
  27266. * - BABYLON.VertexBuffer.UVKind
  27267. * - BABYLON.VertexBuffer.UV2Kind
  27268. * - BABYLON.VertexBuffer.UV3Kind
  27269. * - BABYLON.VertexBuffer.UV4Kind
  27270. * - BABYLON.VertexBuffer.UV5Kind
  27271. * - BABYLON.VertexBuffer.UV6Kind
  27272. * - BABYLON.VertexBuffer.ColorKind
  27273. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27274. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27275. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27276. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27277. */
  27278. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27279. if (!this._geometry) {
  27280. if (this._delayInfo) {
  27281. return this._delayInfo.indexOf(kind) !== -1;
  27282. }
  27283. return false;
  27284. }
  27285. return this._geometry.isVerticesDataPresent(kind);
  27286. };
  27287. /**
  27288. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27289. * Possible `kind` values :
  27290. * - BABYLON.VertexBuffer.PositionKind
  27291. * - BABYLON.VertexBuffer.UVKind
  27292. * - BABYLON.VertexBuffer.UV2Kind
  27293. * - BABYLON.VertexBuffer.UV3Kind
  27294. * - BABYLON.VertexBuffer.UV4Kind
  27295. * - BABYLON.VertexBuffer.UV5Kind
  27296. * - BABYLON.VertexBuffer.UV6Kind
  27297. * - BABYLON.VertexBuffer.ColorKind
  27298. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27299. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27300. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27301. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27302. */
  27303. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27304. if (!this._geometry) {
  27305. if (this._delayInfo) {
  27306. return this._delayInfo.indexOf(kind) !== -1;
  27307. }
  27308. return false;
  27309. }
  27310. return this._geometry.isVertexBufferUpdatable(kind);
  27311. };
  27312. /**
  27313. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27314. * Possible `kind` values :
  27315. * - BABYLON.VertexBuffer.PositionKind
  27316. * - BABYLON.VertexBuffer.UVKind
  27317. * - BABYLON.VertexBuffer.UV2Kind
  27318. * - BABYLON.VertexBuffer.UV3Kind
  27319. * - BABYLON.VertexBuffer.UV4Kind
  27320. * - BABYLON.VertexBuffer.UV5Kind
  27321. * - BABYLON.VertexBuffer.UV6Kind
  27322. * - BABYLON.VertexBuffer.ColorKind
  27323. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27324. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27325. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27326. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27327. */
  27328. Mesh.prototype.getVerticesDataKinds = function () {
  27329. if (!this._geometry) {
  27330. var result = new Array();
  27331. if (this._delayInfo) {
  27332. this._delayInfo.forEach(function (kind, index, array) {
  27333. result.push(kind);
  27334. });
  27335. }
  27336. return result;
  27337. }
  27338. return this._geometry.getVerticesDataKinds();
  27339. };
  27340. /**
  27341. * Returns a positive integer : the total number of indices in this mesh geometry.
  27342. * Returns zero if the mesh has no geometry.
  27343. */
  27344. Mesh.prototype.getTotalIndices = function () {
  27345. if (!this._geometry) {
  27346. return 0;
  27347. }
  27348. return this._geometry.getTotalIndices();
  27349. };
  27350. /**
  27351. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27352. * 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.
  27353. * Returns an empty array if the mesh has no geometry.
  27354. */
  27355. Mesh.prototype.getIndices = function (copyWhenShared) {
  27356. if (!this._geometry) {
  27357. return [];
  27358. }
  27359. return this._geometry.getIndices(copyWhenShared);
  27360. };
  27361. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27362. get: function () {
  27363. return this._masterMesh !== null && this._masterMesh !== undefined;
  27364. },
  27365. enumerable: true,
  27366. configurable: true
  27367. });
  27368. /**
  27369. * Determine if the current mesh is ready to be rendered
  27370. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27371. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27372. * @returns true if all associated assets are ready (material, textures, shaders)
  27373. */
  27374. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27375. if (completeCheck === void 0) { completeCheck = false; }
  27376. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27377. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27378. return false;
  27379. }
  27380. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27381. return false;
  27382. }
  27383. if (!this.subMeshes || this.subMeshes.length === 0) {
  27384. return true;
  27385. }
  27386. if (!completeCheck) {
  27387. return true;
  27388. }
  27389. var engine = this.getEngine();
  27390. var scene = this.getScene();
  27391. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27392. this.computeWorldMatrix();
  27393. var mat = this.material || scene.defaultMaterial;
  27394. if (mat) {
  27395. if (mat.storeEffectOnSubMeshes) {
  27396. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27397. var subMesh = _a[_i];
  27398. var effectiveMaterial = subMesh.getMaterial();
  27399. if (effectiveMaterial) {
  27400. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27401. return false;
  27402. }
  27403. }
  27404. }
  27405. }
  27406. else {
  27407. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27408. return false;
  27409. }
  27410. }
  27411. }
  27412. // Shadows
  27413. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27414. var light = _c[_b];
  27415. var generator = light.getShadowGenerator();
  27416. if (generator) {
  27417. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27418. var subMesh = _e[_d];
  27419. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27420. return false;
  27421. }
  27422. }
  27423. }
  27424. }
  27425. // LOD
  27426. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27427. var lod = _g[_f];
  27428. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27429. return false;
  27430. }
  27431. }
  27432. return true;
  27433. };
  27434. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27435. /**
  27436. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27437. * This property is pertinent only for updatable parametric shapes.
  27438. */
  27439. get: function () {
  27440. return this._areNormalsFrozen;
  27441. },
  27442. enumerable: true,
  27443. configurable: true
  27444. });
  27445. /**
  27446. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27447. * It has no effect at all on other shapes.
  27448. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27449. * Returns the Mesh.
  27450. */
  27451. Mesh.prototype.freezeNormals = function () {
  27452. this._areNormalsFrozen = true;
  27453. return this;
  27454. };
  27455. /**
  27456. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27457. * It has no effect at all on other shapes.
  27458. * It reactivates the mesh normals computation if it was previously frozen.
  27459. * Returns the Mesh.
  27460. */
  27461. Mesh.prototype.unfreezeNormals = function () {
  27462. this._areNormalsFrozen = false;
  27463. return this;
  27464. };
  27465. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27466. /**
  27467. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27468. */
  27469. set: function (count) {
  27470. this._overridenInstanceCount = count;
  27471. },
  27472. enumerable: true,
  27473. configurable: true
  27474. });
  27475. // Methods
  27476. Mesh.prototype._preActivate = function () {
  27477. var sceneRenderId = this.getScene().getRenderId();
  27478. if (this._preActivateId === sceneRenderId) {
  27479. return this;
  27480. }
  27481. this._preActivateId = sceneRenderId;
  27482. this._visibleInstances = null;
  27483. return this;
  27484. };
  27485. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27486. if (this._visibleInstances) {
  27487. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27488. }
  27489. return this;
  27490. };
  27491. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27492. if (!this._visibleInstances) {
  27493. this._visibleInstances = {};
  27494. this._visibleInstances.defaultRenderId = renderId;
  27495. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27496. }
  27497. if (!this._visibleInstances[renderId]) {
  27498. this._visibleInstances[renderId] = new Array();
  27499. }
  27500. this._visibleInstances[renderId].push(instance);
  27501. return this;
  27502. };
  27503. /**
  27504. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27505. * This means the mesh underlying bounding box and sphere are recomputed.
  27506. * Returns the Mesh.
  27507. */
  27508. Mesh.prototype.refreshBoundingInfo = function () {
  27509. return this._refreshBoundingInfo(false);
  27510. };
  27511. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27512. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27513. return this;
  27514. }
  27515. var data = this._getPositionData(applySkeleton);
  27516. if (data) {
  27517. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27518. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27519. }
  27520. if (this.subMeshes) {
  27521. for (var index = 0; index < this.subMeshes.length; index++) {
  27522. this.subMeshes[index].refreshBoundingInfo();
  27523. }
  27524. }
  27525. this._updateBoundingInfo();
  27526. return this;
  27527. };
  27528. Mesh.prototype._getPositionData = function (applySkeleton) {
  27529. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27530. if (data && applySkeleton && this.skeleton) {
  27531. data = BABYLON.Tools.Slice(data);
  27532. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27533. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27534. if (matricesWeightsData && matricesIndicesData) {
  27535. var needExtras = this.numBoneInfluencers > 4;
  27536. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27537. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27538. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27539. var tempVector = BABYLON.Tmp.Vector3[0];
  27540. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27541. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27542. var matWeightIdx = 0;
  27543. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27544. finalMatrix.reset();
  27545. var inf;
  27546. var weight;
  27547. for (inf = 0; inf < 4; inf++) {
  27548. weight = matricesWeightsData[matWeightIdx + inf];
  27549. if (weight <= 0)
  27550. break;
  27551. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27552. finalMatrix.addToSelf(tempMatrix);
  27553. }
  27554. if (needExtras) {
  27555. for (inf = 0; inf < 4; inf++) {
  27556. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27557. if (weight <= 0)
  27558. break;
  27559. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27560. finalMatrix.addToSelf(tempMatrix);
  27561. }
  27562. }
  27563. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27564. tempVector.toArray(data, index);
  27565. }
  27566. }
  27567. }
  27568. return data;
  27569. };
  27570. Mesh.prototype._createGlobalSubMesh = function (force) {
  27571. var totalVertices = this.getTotalVertices();
  27572. if (!totalVertices || !this.getIndices()) {
  27573. return null;
  27574. }
  27575. // Check if we need to recreate the submeshes
  27576. if (this.subMeshes && this.subMeshes.length > 0) {
  27577. var ib = this.getIndices();
  27578. if (!ib) {
  27579. return null;
  27580. }
  27581. var totalIndices = ib.length;
  27582. var needToRecreate = false;
  27583. if (force) {
  27584. needToRecreate = true;
  27585. }
  27586. else {
  27587. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27588. var submesh = _a[_i];
  27589. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27590. needToRecreate = true;
  27591. break;
  27592. }
  27593. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27594. needToRecreate = true;
  27595. break;
  27596. }
  27597. }
  27598. }
  27599. if (!needToRecreate) {
  27600. return this.subMeshes[0];
  27601. }
  27602. }
  27603. this.releaseSubMeshes();
  27604. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27605. };
  27606. Mesh.prototype.subdivide = function (count) {
  27607. if (count < 1) {
  27608. return;
  27609. }
  27610. var totalIndices = this.getTotalIndices();
  27611. var subdivisionSize = (totalIndices / count) | 0;
  27612. var offset = 0;
  27613. // Ensure that subdivisionSize is a multiple of 3
  27614. while (subdivisionSize % 3 !== 0) {
  27615. subdivisionSize++;
  27616. }
  27617. this.releaseSubMeshes();
  27618. for (var index = 0; index < count; index++) {
  27619. if (offset >= totalIndices) {
  27620. break;
  27621. }
  27622. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27623. offset += subdivisionSize;
  27624. }
  27625. this.synchronizeInstances();
  27626. };
  27627. /**
  27628. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27629. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27630. * The `data` are either a numeric array either a Float32Array.
  27631. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27632. * 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).
  27633. * Note that a new underlying VertexBuffer object is created each call.
  27634. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27635. *
  27636. * Possible `kind` values :
  27637. * - BABYLON.VertexBuffer.PositionKind
  27638. * - BABYLON.VertexBuffer.UVKind
  27639. * - BABYLON.VertexBuffer.UV2Kind
  27640. * - BABYLON.VertexBuffer.UV3Kind
  27641. * - BABYLON.VertexBuffer.UV4Kind
  27642. * - BABYLON.VertexBuffer.UV5Kind
  27643. * - BABYLON.VertexBuffer.UV6Kind
  27644. * - BABYLON.VertexBuffer.ColorKind
  27645. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27646. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27647. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27648. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27649. *
  27650. * Returns the Mesh.
  27651. */
  27652. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27653. if (updatable === void 0) { updatable = false; }
  27654. if (!this._geometry) {
  27655. var vertexData = new BABYLON.VertexData();
  27656. vertexData.set(data, kind);
  27657. var scene = this.getScene();
  27658. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27659. }
  27660. else {
  27661. this._geometry.setVerticesData(kind, data, updatable, stride);
  27662. }
  27663. return this;
  27664. };
  27665. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27666. if (updatable === void 0) { updatable = true; }
  27667. var vb = this.getVertexBuffer(kind);
  27668. if (!vb || vb.isUpdatable() === updatable) {
  27669. return;
  27670. }
  27671. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27672. };
  27673. /**
  27674. * Sets the mesh VertexBuffer.
  27675. * Returns the Mesh.
  27676. */
  27677. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27678. if (!this._geometry) {
  27679. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27680. }
  27681. this._geometry.setVerticesBuffer(buffer);
  27682. return this;
  27683. };
  27684. /**
  27685. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27686. * If the mesh has no geometry, it is simply returned as it is.
  27687. * The `data` are either a numeric array either a Float32Array.
  27688. * No new underlying VertexBuffer object is created.
  27689. * 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.
  27690. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27691. *
  27692. * Possible `kind` values :
  27693. * - BABYLON.VertexBuffer.PositionKind
  27694. * - BABYLON.VertexBuffer.UVKind
  27695. * - BABYLON.VertexBuffer.UV2Kind
  27696. * - BABYLON.VertexBuffer.UV3Kind
  27697. * - BABYLON.VertexBuffer.UV4Kind
  27698. * - BABYLON.VertexBuffer.UV5Kind
  27699. * - BABYLON.VertexBuffer.UV6Kind
  27700. * - BABYLON.VertexBuffer.ColorKind
  27701. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27702. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27703. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27704. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27705. *
  27706. * Returns the Mesh.
  27707. */
  27708. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27709. if (!this._geometry) {
  27710. return this;
  27711. }
  27712. if (!makeItUnique) {
  27713. this._geometry.updateVerticesData(kind, data, updateExtends);
  27714. }
  27715. else {
  27716. this.makeGeometryUnique();
  27717. this.updateVerticesData(kind, data, updateExtends, false);
  27718. }
  27719. return this;
  27720. };
  27721. /**
  27722. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27723. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27724. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27725. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27726. * Returns the Mesh.
  27727. */
  27728. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27729. if (computeNormals === void 0) { computeNormals = true; }
  27730. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27731. if (!positions) {
  27732. return this;
  27733. }
  27734. positionFunction(positions);
  27735. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27736. if (computeNormals) {
  27737. var indices = this.getIndices();
  27738. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27739. if (!normals) {
  27740. return this;
  27741. }
  27742. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27743. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27744. }
  27745. return this;
  27746. };
  27747. /**
  27748. * Creates a un-shared specific occurence of the geometry for the mesh.
  27749. * Returns the Mesh.
  27750. */
  27751. Mesh.prototype.makeGeometryUnique = function () {
  27752. if (!this._geometry) {
  27753. return this;
  27754. }
  27755. var oldGeometry = this._geometry;
  27756. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27757. oldGeometry.releaseForMesh(this, true);
  27758. geometry.applyToMesh(this);
  27759. return this;
  27760. };
  27761. /**
  27762. * Sets the mesh indices.
  27763. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27764. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27765. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27766. * This method creates a new index buffer each call.
  27767. * Returns the Mesh.
  27768. */
  27769. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27770. if (totalVertices === void 0) { totalVertices = null; }
  27771. if (updatable === void 0) { updatable = false; }
  27772. if (!this._geometry) {
  27773. var vertexData = new BABYLON.VertexData();
  27774. vertexData.indices = indices;
  27775. var scene = this.getScene();
  27776. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27777. }
  27778. else {
  27779. this._geometry.setIndices(indices, totalVertices, updatable);
  27780. }
  27781. return this;
  27782. };
  27783. /**
  27784. * Update the current index buffer
  27785. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27786. * Returns the Mesh.
  27787. */
  27788. Mesh.prototype.updateIndices = function (indices, offset) {
  27789. if (!this._geometry) {
  27790. return this;
  27791. }
  27792. this._geometry.updateIndices(indices, offset);
  27793. return this;
  27794. };
  27795. /**
  27796. * Invert the geometry to move from a right handed system to a left handed one.
  27797. * Returns the Mesh.
  27798. */
  27799. Mesh.prototype.toLeftHanded = function () {
  27800. if (!this._geometry) {
  27801. return this;
  27802. }
  27803. this._geometry.toLeftHanded();
  27804. return this;
  27805. };
  27806. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27807. if (!this._geometry) {
  27808. return this;
  27809. }
  27810. var engine = this.getScene().getEngine();
  27811. // Wireframe
  27812. var indexToBind;
  27813. if (this._unIndexed) {
  27814. indexToBind = null;
  27815. }
  27816. else {
  27817. switch (fillMode) {
  27818. case BABYLON.Material.PointFillMode:
  27819. indexToBind = null;
  27820. break;
  27821. case BABYLON.Material.WireFrameFillMode:
  27822. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27823. break;
  27824. default:
  27825. case BABYLON.Material.TriangleFillMode:
  27826. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27827. break;
  27828. }
  27829. }
  27830. // VBOs
  27831. this._geometry._bind(effect, indexToBind);
  27832. return this;
  27833. };
  27834. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27835. if (alternate === void 0) { alternate = false; }
  27836. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27837. return this;
  27838. }
  27839. this.onBeforeDrawObservable.notifyObservers(this);
  27840. var scene = this.getScene();
  27841. var engine = scene.getEngine();
  27842. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27843. // or triangles as points
  27844. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27845. }
  27846. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27847. // Triangles as wireframe
  27848. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27849. }
  27850. else {
  27851. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27852. }
  27853. if (scene._isAlternateRenderingEnabled && !alternate) {
  27854. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27855. if (!effect || !scene.activeCamera) {
  27856. return this;
  27857. }
  27858. scene._switchToAlternateCameraConfiguration(true);
  27859. this._effectiveMaterial.bindView(effect);
  27860. this._effectiveMaterial.bindViewProjection(effect);
  27861. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27862. this._draw(subMesh, fillMode, instancesCount, true);
  27863. engine.setViewport(scene.activeCamera.viewport);
  27864. scene._switchToAlternateCameraConfiguration(false);
  27865. this._effectiveMaterial.bindView(effect);
  27866. this._effectiveMaterial.bindViewProjection(effect);
  27867. }
  27868. return this;
  27869. };
  27870. /**
  27871. * Registers for this mesh a javascript function called just before the rendering process.
  27872. * This function is passed the current mesh.
  27873. * Return the Mesh.
  27874. */
  27875. Mesh.prototype.registerBeforeRender = function (func) {
  27876. this.onBeforeRenderObservable.add(func);
  27877. return this;
  27878. };
  27879. /**
  27880. * Disposes a previously registered javascript function called before the rendering.
  27881. * This function is passed the current mesh.
  27882. * Returns the Mesh.
  27883. */
  27884. Mesh.prototype.unregisterBeforeRender = function (func) {
  27885. this.onBeforeRenderObservable.removeCallback(func);
  27886. return this;
  27887. };
  27888. /**
  27889. * Registers for this mesh a javascript function called just after the rendering is complete.
  27890. * This function is passed the current mesh.
  27891. * Returns the Mesh.
  27892. */
  27893. Mesh.prototype.registerAfterRender = function (func) {
  27894. this.onAfterRenderObservable.add(func);
  27895. return this;
  27896. };
  27897. /**
  27898. * Disposes a previously registered javascript function called after the rendering.
  27899. * This function is passed the current mesh.
  27900. * Return the Mesh.
  27901. */
  27902. Mesh.prototype.unregisterAfterRender = function (func) {
  27903. this.onAfterRenderObservable.removeCallback(func);
  27904. return this;
  27905. };
  27906. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27907. var scene = this.getScene();
  27908. this._batchCache.mustReturn = false;
  27909. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27910. this._batchCache.visibleInstances[subMeshId] = null;
  27911. if (this._visibleInstances) {
  27912. var currentRenderId = scene.getRenderId();
  27913. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27914. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27915. var selfRenderId = this._renderId;
  27916. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27917. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27918. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27919. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27920. }
  27921. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27922. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27923. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27924. this._batchCache.mustReturn = true;
  27925. return this._batchCache;
  27926. }
  27927. if (currentRenderId !== selfRenderId) {
  27928. this._batchCache.renderSelf[subMeshId] = false;
  27929. }
  27930. }
  27931. this._renderIdForInstances[subMeshId] = currentRenderId;
  27932. }
  27933. return this._batchCache;
  27934. };
  27935. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27936. var visibleInstances = batch.visibleInstances[subMesh._id];
  27937. if (!visibleInstances) {
  27938. return this;
  27939. }
  27940. var matricesCount = visibleInstances.length + 1;
  27941. var bufferSize = matricesCount * 16 * 4;
  27942. var currentInstancesBufferSize = this._instancesBufferSize;
  27943. var instancesBuffer = this._instancesBuffer;
  27944. while (this._instancesBufferSize < bufferSize) {
  27945. this._instancesBufferSize *= 2;
  27946. }
  27947. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27948. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27949. }
  27950. var offset = 0;
  27951. var instancesCount = 0;
  27952. var world = this.getWorldMatrix();
  27953. if (batch.renderSelf[subMesh._id]) {
  27954. world.copyToArray(this._instancesData, offset);
  27955. offset += 16;
  27956. instancesCount++;
  27957. }
  27958. if (visibleInstances) {
  27959. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27960. var instance = visibleInstances[instanceIndex];
  27961. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27962. offset += 16;
  27963. instancesCount++;
  27964. }
  27965. }
  27966. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27967. if (instancesBuffer) {
  27968. instancesBuffer.dispose();
  27969. }
  27970. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27971. this._instancesBuffer = instancesBuffer;
  27972. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27973. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27974. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27975. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27976. }
  27977. else {
  27978. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27979. }
  27980. this._bind(subMesh, effect, fillMode);
  27981. this._draw(subMesh, fillMode, instancesCount);
  27982. engine.unbindInstanceAttributes();
  27983. return this;
  27984. };
  27985. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27986. var scene = this.getScene();
  27987. var engine = scene.getEngine();
  27988. if (hardwareInstancedRendering) {
  27989. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27990. }
  27991. else {
  27992. if (batch.renderSelf[subMesh._id]) {
  27993. // Draw
  27994. if (onBeforeDraw) {
  27995. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  27996. }
  27997. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  27998. }
  27999. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28000. if (visibleInstancesForSubMesh) {
  28001. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28002. var instance = visibleInstancesForSubMesh[instanceIndex];
  28003. // World
  28004. var world = instance.getWorldMatrix();
  28005. if (onBeforeDraw) {
  28006. onBeforeDraw(true, world, effectiveMaterial);
  28007. }
  28008. // Draw
  28009. this._draw(subMesh, fillMode);
  28010. }
  28011. }
  28012. }
  28013. return this;
  28014. };
  28015. /**
  28016. * Triggers the draw call for the mesh.
  28017. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28018. * Returns the Mesh.
  28019. */
  28020. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28021. this.checkOcclusionQuery();
  28022. if (this._isOccluded) {
  28023. return this;
  28024. }
  28025. var scene = this.getScene();
  28026. // Managing instances
  28027. var batch = this._getInstancesRenderList(subMesh._id);
  28028. if (batch.mustReturn) {
  28029. return this;
  28030. }
  28031. // Checking geometry state
  28032. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28033. return this;
  28034. }
  28035. this.onBeforeRenderObservable.notifyObservers(this);
  28036. var engine = scene.getEngine();
  28037. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28038. // Material
  28039. var material = subMesh.getMaterial();
  28040. if (!material) {
  28041. return this;
  28042. }
  28043. this._effectiveMaterial = material;
  28044. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28045. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28046. return this;
  28047. }
  28048. }
  28049. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28050. return this;
  28051. }
  28052. // Alpha mode
  28053. if (enableAlphaMode) {
  28054. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28055. }
  28056. // Outline - step 1
  28057. var savedDepthWrite = engine.getDepthWrite();
  28058. if (this.renderOutline) {
  28059. engine.setDepthWrite(false);
  28060. scene.getOutlineRenderer().render(subMesh, batch);
  28061. engine.setDepthWrite(savedDepthWrite);
  28062. }
  28063. var effect;
  28064. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28065. effect = subMesh.effect;
  28066. }
  28067. else {
  28068. effect = this._effectiveMaterial.getEffect();
  28069. }
  28070. if (!effect) {
  28071. return this;
  28072. }
  28073. var sideOrientation = this.overrideMaterialSideOrientation;
  28074. if (sideOrientation == null) {
  28075. sideOrientation = this._effectiveMaterial.sideOrientation;
  28076. if (this._getWorldMatrixDeterminant() < 0) {
  28077. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28078. }
  28079. }
  28080. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28081. if (this._effectiveMaterial.forceDepthWrite) {
  28082. engine.setDepthWrite(true);
  28083. }
  28084. // Bind
  28085. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28086. if (!hardwareInstancedRendering) {
  28087. this._bind(subMesh, effect, fillMode);
  28088. }
  28089. var world = this.getWorldMatrix();
  28090. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28091. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28092. }
  28093. else {
  28094. this._effectiveMaterial.bind(world, this);
  28095. }
  28096. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28097. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28098. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28099. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28100. }
  28101. // Draw
  28102. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28103. // Unbind
  28104. this._effectiveMaterial.unbind();
  28105. // Outline - step 2
  28106. if (this.renderOutline && savedDepthWrite) {
  28107. engine.setDepthWrite(true);
  28108. engine.setColorWrite(false);
  28109. scene.getOutlineRenderer().render(subMesh, batch);
  28110. engine.setColorWrite(true);
  28111. }
  28112. // Overlay
  28113. if (this.renderOverlay) {
  28114. var currentMode = engine.getAlphaMode();
  28115. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28116. scene.getOutlineRenderer().render(subMesh, batch, true);
  28117. engine.setAlphaMode(currentMode);
  28118. }
  28119. this.onAfterRenderObservable.notifyObservers(this);
  28120. return this;
  28121. };
  28122. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28123. if (isInstance && effectiveMaterial) {
  28124. effectiveMaterial.bindOnlyWorldMatrix(world);
  28125. }
  28126. };
  28127. /**
  28128. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28129. */
  28130. Mesh.prototype.getEmittedParticleSystems = function () {
  28131. var results = new Array();
  28132. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28133. var particleSystem = this.getScene().particleSystems[index];
  28134. if (particleSystem.emitter === this) {
  28135. results.push(particleSystem);
  28136. }
  28137. }
  28138. return results;
  28139. };
  28140. /**
  28141. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28142. */
  28143. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28144. var results = new Array();
  28145. var descendants = this.getDescendants();
  28146. descendants.push(this);
  28147. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28148. var particleSystem = this.getScene().particleSystems[index];
  28149. var emitter = particleSystem.emitter;
  28150. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28151. results.push(particleSystem);
  28152. }
  28153. }
  28154. return results;
  28155. };
  28156. Mesh.prototype._checkDelayState = function () {
  28157. var scene = this.getScene();
  28158. if (this._geometry) {
  28159. this._geometry.load(scene);
  28160. }
  28161. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28162. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28163. this._queueLoad(scene);
  28164. }
  28165. return this;
  28166. };
  28167. Mesh.prototype._queueLoad = function (scene) {
  28168. var _this = this;
  28169. scene._addPendingData(this);
  28170. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28171. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28172. if (data instanceof ArrayBuffer) {
  28173. _this._delayLoadingFunction(data, _this);
  28174. }
  28175. else {
  28176. _this._delayLoadingFunction(JSON.parse(data), _this);
  28177. }
  28178. _this.instances.forEach(function (instance) {
  28179. instance._syncSubMeshes();
  28180. });
  28181. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28182. scene._removePendingData(_this);
  28183. }, function () { }, scene.database, getBinaryData);
  28184. return this;
  28185. };
  28186. /**
  28187. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28188. */
  28189. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28190. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28191. return false;
  28192. }
  28193. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28194. return false;
  28195. }
  28196. this._checkDelayState();
  28197. return true;
  28198. };
  28199. /**
  28200. * Sets the mesh material by the material or multiMaterial `id` property.
  28201. * The material `id` is a string identifying the material or the multiMaterial.
  28202. * This method returns the Mesh.
  28203. */
  28204. Mesh.prototype.setMaterialByID = function (id) {
  28205. var materials = this.getScene().materials;
  28206. var index;
  28207. for (index = materials.length - 1; index > -1; index--) {
  28208. if (materials[index].id === id) {
  28209. this.material = materials[index];
  28210. return this;
  28211. }
  28212. }
  28213. // Multi
  28214. var multiMaterials = this.getScene().multiMaterials;
  28215. for (index = multiMaterials.length - 1; index > -1; index--) {
  28216. if (multiMaterials[index].id === id) {
  28217. this.material = multiMaterials[index];
  28218. return this;
  28219. }
  28220. }
  28221. return this;
  28222. };
  28223. /**
  28224. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28225. */
  28226. Mesh.prototype.getAnimatables = function () {
  28227. var results = new Array();
  28228. if (this.material) {
  28229. results.push(this.material);
  28230. }
  28231. if (this.skeleton) {
  28232. results.push(this.skeleton);
  28233. }
  28234. return results;
  28235. };
  28236. /**
  28237. * Modifies the mesh geometry according to the passed transformation matrix.
  28238. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28239. * The mesh normals are modified accordingly the same transformation.
  28240. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28241. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28242. * Returns the Mesh.
  28243. */
  28244. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28245. // Position
  28246. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28247. return this;
  28248. }
  28249. var submeshes = this.subMeshes.splice(0);
  28250. this._resetPointsArrayCache();
  28251. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28252. var temp = new Array();
  28253. var index;
  28254. for (index = 0; index < data.length; index += 3) {
  28255. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28256. }
  28257. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28258. // Normals
  28259. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28260. return this;
  28261. }
  28262. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28263. temp = [];
  28264. for (index = 0; index < data.length; index += 3) {
  28265. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28266. }
  28267. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28268. // flip faces?
  28269. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28270. this.flipFaces();
  28271. }
  28272. // Restore submeshes
  28273. this.releaseSubMeshes();
  28274. this.subMeshes = submeshes;
  28275. return this;
  28276. };
  28277. /**
  28278. * Modifies the mesh geometry according to its own current World Matrix.
  28279. * The mesh World Matrix is then reset.
  28280. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28281. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28282. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28283. * Returns the Mesh.
  28284. */
  28285. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28286. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28287. this.scaling.copyFromFloats(1, 1, 1);
  28288. this.position.copyFromFloats(0, 0, 0);
  28289. this.rotation.copyFromFloats(0, 0, 0);
  28290. //only if quaternion is already set
  28291. if (this.rotationQuaternion) {
  28292. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28293. }
  28294. this._worldMatrix = BABYLON.Matrix.Identity();
  28295. return this;
  28296. };
  28297. Object.defineProperty(Mesh.prototype, "_positions", {
  28298. // Cache
  28299. get: function () {
  28300. if (this._geometry) {
  28301. return this._geometry._positions;
  28302. }
  28303. return null;
  28304. },
  28305. enumerable: true,
  28306. configurable: true
  28307. });
  28308. Mesh.prototype._resetPointsArrayCache = function () {
  28309. if (this._geometry) {
  28310. this._geometry._resetPointsArrayCache();
  28311. }
  28312. return this;
  28313. };
  28314. Mesh.prototype._generatePointsArray = function () {
  28315. if (this._geometry) {
  28316. return this._geometry._generatePointsArray();
  28317. }
  28318. return false;
  28319. };
  28320. /**
  28321. * Returns a new Mesh object generated from the current mesh properties.
  28322. * This method must not get confused with createInstance().
  28323. * The parameter `name` is a string, the name given to the new mesh.
  28324. * The optional parameter `newParent` can be any Node object (default `null`).
  28325. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28326. * 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.
  28327. */
  28328. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28329. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28330. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28331. };
  28332. /**
  28333. * Disposes the Mesh.
  28334. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28335. * Returns nothing.
  28336. */
  28337. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28338. var _this = this;
  28339. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28340. this.morphTargetManager = null;
  28341. if (this._geometry) {
  28342. this._geometry.releaseForMesh(this, true);
  28343. }
  28344. // Sources
  28345. var meshes = this.getScene().meshes;
  28346. meshes.forEach(function (abstractMesh) {
  28347. var mesh = abstractMesh;
  28348. if (mesh._source && mesh._source === _this) {
  28349. mesh._source = null;
  28350. }
  28351. });
  28352. this._source = null;
  28353. // Instances
  28354. if (this._instancesBuffer) {
  28355. this._instancesBuffer.dispose();
  28356. this._instancesBuffer = null;
  28357. }
  28358. while (this.instances.length) {
  28359. this.instances[0].dispose();
  28360. }
  28361. // Effect layers.
  28362. var effectLayers = this.getScene().effectLayers;
  28363. for (var i = 0; i < effectLayers.length; i++) {
  28364. var effectLayer = effectLayers[i];
  28365. if (effectLayer) {
  28366. effectLayer._disposeMesh(this);
  28367. }
  28368. }
  28369. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28370. };
  28371. /**
  28372. * Modifies the mesh geometry according to a displacement map.
  28373. * 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.
  28374. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28375. * This method returns nothing.
  28376. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28377. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28378. * 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.
  28379. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28380. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28381. *
  28382. * Returns the Mesh.
  28383. */
  28384. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28385. var _this = this;
  28386. var scene = this.getScene();
  28387. var onload = function (img) {
  28388. // Getting height map data
  28389. var canvas = document.createElement("canvas");
  28390. var context = canvas.getContext("2d");
  28391. var heightMapWidth = img.width;
  28392. var heightMapHeight = img.height;
  28393. canvas.width = heightMapWidth;
  28394. canvas.height = heightMapHeight;
  28395. context.drawImage(img, 0, 0);
  28396. // Create VertexData from map data
  28397. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28398. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28399. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28400. //execute success callback, if set
  28401. if (onSuccess) {
  28402. onSuccess(_this);
  28403. }
  28404. };
  28405. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28406. return this;
  28407. };
  28408. /**
  28409. * Modifies the mesh geometry according to a displacementMap buffer.
  28410. * 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.
  28411. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28412. * This method returns nothing.
  28413. * 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.
  28414. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28415. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28416. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28417. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28418. *
  28419. * Returns the Mesh.
  28420. */
  28421. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28422. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28423. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28424. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28425. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28426. return this;
  28427. }
  28428. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28429. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28430. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28431. var position = BABYLON.Vector3.Zero();
  28432. var normal = BABYLON.Vector3.Zero();
  28433. var uv = BABYLON.Vector2.Zero();
  28434. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28435. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28436. for (var index = 0; index < positions.length; index += 3) {
  28437. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28438. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28439. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28440. // Compute height
  28441. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28442. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28443. var pos = (u + v * heightMapWidth) * 4;
  28444. var r = buffer[pos] / 255.0;
  28445. var g = buffer[pos + 1] / 255.0;
  28446. var b = buffer[pos + 2] / 255.0;
  28447. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28448. normal.normalize();
  28449. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28450. position = position.add(normal);
  28451. position.toArray(positions, index);
  28452. }
  28453. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28454. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28455. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28456. return this;
  28457. };
  28458. /**
  28459. * Modify the mesh to get a flat shading rendering.
  28460. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28461. * This method returns the Mesh.
  28462. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28463. */
  28464. Mesh.prototype.convertToFlatShadedMesh = function () {
  28465. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28466. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28467. var kinds = this.getVerticesDataKinds();
  28468. var vbs = {};
  28469. var data = {};
  28470. var newdata = {};
  28471. var updatableNormals = false;
  28472. var kindIndex;
  28473. var kind;
  28474. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28475. kind = kinds[kindIndex];
  28476. var vertexBuffer = this.getVertexBuffer(kind);
  28477. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28478. updatableNormals = vertexBuffer.isUpdatable();
  28479. kinds.splice(kindIndex, 1);
  28480. kindIndex--;
  28481. continue;
  28482. }
  28483. vbs[kind] = vertexBuffer;
  28484. data[kind] = vbs[kind].getData();
  28485. newdata[kind] = [];
  28486. }
  28487. // Save previous submeshes
  28488. var previousSubmeshes = this.subMeshes.slice(0);
  28489. var indices = this.getIndices();
  28490. var totalIndices = this.getTotalIndices();
  28491. // Generating unique vertices per face
  28492. var index;
  28493. for (index = 0; index < totalIndices; index++) {
  28494. var vertexIndex = indices[index];
  28495. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28496. kind = kinds[kindIndex];
  28497. var stride = vbs[kind].getStrideSize();
  28498. for (var offset = 0; offset < stride; offset++) {
  28499. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28500. }
  28501. }
  28502. }
  28503. // Updating faces & normal
  28504. var normals = [];
  28505. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28506. for (index = 0; index < totalIndices; index += 3) {
  28507. indices[index] = index;
  28508. indices[index + 1] = index + 1;
  28509. indices[index + 2] = index + 2;
  28510. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28511. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28512. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28513. var p1p2 = p1.subtract(p2);
  28514. var p3p2 = p3.subtract(p2);
  28515. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28516. // Store same normals for every vertex
  28517. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28518. normals.push(normal.x);
  28519. normals.push(normal.y);
  28520. normals.push(normal.z);
  28521. }
  28522. }
  28523. this.setIndices(indices);
  28524. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28525. // Updating vertex buffers
  28526. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28527. kind = kinds[kindIndex];
  28528. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28529. }
  28530. // Updating submeshes
  28531. this.releaseSubMeshes();
  28532. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28533. var previousOne = previousSubmeshes[submeshIndex];
  28534. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28535. }
  28536. this.synchronizeInstances();
  28537. return this;
  28538. };
  28539. /**
  28540. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28541. * In other words, more vertices, no more indices and a single bigger VBO.
  28542. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28543. * Returns the Mesh.
  28544. */
  28545. Mesh.prototype.convertToUnIndexedMesh = function () {
  28546. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28547. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28548. var kinds = this.getVerticesDataKinds();
  28549. var vbs = {};
  28550. var data = {};
  28551. var newdata = {};
  28552. var kindIndex;
  28553. var kind;
  28554. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28555. kind = kinds[kindIndex];
  28556. var vertexBuffer = this.getVertexBuffer(kind);
  28557. vbs[kind] = vertexBuffer;
  28558. data[kind] = vbs[kind].getData();
  28559. newdata[kind] = [];
  28560. }
  28561. // Save previous submeshes
  28562. var previousSubmeshes = this.subMeshes.slice(0);
  28563. var indices = this.getIndices();
  28564. var totalIndices = this.getTotalIndices();
  28565. // Generating unique vertices per face
  28566. var index;
  28567. for (index = 0; index < totalIndices; index++) {
  28568. var vertexIndex = indices[index];
  28569. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28570. kind = kinds[kindIndex];
  28571. var stride = vbs[kind].getStrideSize();
  28572. for (var offset = 0; offset < stride; offset++) {
  28573. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28574. }
  28575. }
  28576. }
  28577. // Updating indices
  28578. for (index = 0; index < totalIndices; index += 3) {
  28579. indices[index] = index;
  28580. indices[index + 1] = index + 1;
  28581. indices[index + 2] = index + 2;
  28582. }
  28583. this.setIndices(indices);
  28584. // Updating vertex buffers
  28585. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28586. kind = kinds[kindIndex];
  28587. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28588. }
  28589. // Updating submeshes
  28590. this.releaseSubMeshes();
  28591. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28592. var previousOne = previousSubmeshes[submeshIndex];
  28593. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28594. }
  28595. this._unIndexed = true;
  28596. this.synchronizeInstances();
  28597. return this;
  28598. };
  28599. /**
  28600. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28601. * This method returns the Mesh.
  28602. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28603. */
  28604. Mesh.prototype.flipFaces = function (flipNormals) {
  28605. if (flipNormals === void 0) { flipNormals = false; }
  28606. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28607. var i;
  28608. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28609. for (i = 0; i < vertex_data.normals.length; i++) {
  28610. vertex_data.normals[i] *= -1;
  28611. }
  28612. }
  28613. if (vertex_data.indices) {
  28614. var temp;
  28615. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28616. // reassign indices
  28617. temp = vertex_data.indices[i + 1];
  28618. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28619. vertex_data.indices[i + 2] = temp;
  28620. }
  28621. }
  28622. vertex_data.applyToMesh(this);
  28623. return this;
  28624. };
  28625. // Instances
  28626. /**
  28627. * Creates a new InstancedMesh object from the mesh model.
  28628. * An instance shares the same properties and the same material than its model.
  28629. * Only these properties of each instance can then be set individually :
  28630. * - position
  28631. * - rotation
  28632. * - rotationQuaternion
  28633. * - setPivotMatrix
  28634. * - scaling
  28635. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28636. * Warning : this method is not supported for Line mesh and LineSystem
  28637. */
  28638. Mesh.prototype.createInstance = function (name) {
  28639. return new BABYLON.InstancedMesh(name, this);
  28640. };
  28641. /**
  28642. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28643. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28644. * This method returns the Mesh.
  28645. */
  28646. Mesh.prototype.synchronizeInstances = function () {
  28647. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28648. var instance = this.instances[instanceIndex];
  28649. instance._syncSubMeshes();
  28650. }
  28651. return this;
  28652. };
  28653. /**
  28654. * Simplify the mesh according to the given array of settings.
  28655. * Function will return immediately and will simplify async. It returns the Mesh.
  28656. * @param settings a collection of simplification settings.
  28657. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28658. * @param type the type of simplification to run.
  28659. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28660. */
  28661. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28662. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28663. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28664. this.getScene().simplificationQueue.addTask({
  28665. settings: settings,
  28666. parallelProcessing: parallelProcessing,
  28667. mesh: this,
  28668. simplificationType: simplificationType,
  28669. successCallback: successCallback
  28670. });
  28671. return this;
  28672. };
  28673. /**
  28674. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28675. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28676. * This should be used together with the simplification to avoid disappearing triangles.
  28677. * Returns the Mesh.
  28678. * @param successCallback an optional success callback to be called after the optimization finished.
  28679. */
  28680. Mesh.prototype.optimizeIndices = function (successCallback) {
  28681. var _this = this;
  28682. var indices = this.getIndices();
  28683. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28684. if (!positions || !indices) {
  28685. return this;
  28686. }
  28687. var vectorPositions = new Array();
  28688. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28689. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28690. }
  28691. var dupes = new Array();
  28692. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28693. var realPos = vectorPositions.length - 1 - iteration;
  28694. var testedPosition = vectorPositions[realPos];
  28695. for (var j = 0; j < realPos; ++j) {
  28696. var againstPosition = vectorPositions[j];
  28697. if (testedPosition.equals(againstPosition)) {
  28698. dupes[realPos] = j;
  28699. break;
  28700. }
  28701. }
  28702. }, function () {
  28703. for (var i = 0; i < indices.length; ++i) {
  28704. indices[i] = dupes[indices[i]] || indices[i];
  28705. }
  28706. //indices are now reordered
  28707. var originalSubMeshes = _this.subMeshes.slice(0);
  28708. _this.setIndices(indices);
  28709. _this.subMeshes = originalSubMeshes;
  28710. if (successCallback) {
  28711. successCallback(_this);
  28712. }
  28713. });
  28714. return this;
  28715. };
  28716. Mesh.prototype.serialize = function (serializationObject) {
  28717. serializationObject.name = this.name;
  28718. serializationObject.id = this.id;
  28719. serializationObject.type = this.getClassName();
  28720. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28721. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28722. }
  28723. serializationObject.position = this.position.asArray();
  28724. if (this.rotationQuaternion) {
  28725. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28726. }
  28727. else if (this.rotation) {
  28728. serializationObject.rotation = this.rotation.asArray();
  28729. }
  28730. serializationObject.scaling = this.scaling.asArray();
  28731. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28732. serializationObject.isEnabled = this.isEnabled(false);
  28733. serializationObject.isVisible = this.isVisible;
  28734. serializationObject.infiniteDistance = this.infiniteDistance;
  28735. serializationObject.pickable = this.isPickable;
  28736. serializationObject.receiveShadows = this.receiveShadows;
  28737. serializationObject.billboardMode = this.billboardMode;
  28738. serializationObject.visibility = this.visibility;
  28739. serializationObject.checkCollisions = this.checkCollisions;
  28740. serializationObject.isBlocker = this.isBlocker;
  28741. // Parent
  28742. if (this.parent) {
  28743. serializationObject.parentId = this.parent.id;
  28744. }
  28745. // Geometry
  28746. serializationObject.isUnIndexed = this.isUnIndexed;
  28747. var geometry = this._geometry;
  28748. if (geometry) {
  28749. var geometryId = geometry.id;
  28750. serializationObject.geometryId = geometryId;
  28751. // SubMeshes
  28752. serializationObject.subMeshes = [];
  28753. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28754. var subMesh = this.subMeshes[subIndex];
  28755. serializationObject.subMeshes.push({
  28756. materialIndex: subMesh.materialIndex,
  28757. verticesStart: subMesh.verticesStart,
  28758. verticesCount: subMesh.verticesCount,
  28759. indexStart: subMesh.indexStart,
  28760. indexCount: subMesh.indexCount
  28761. });
  28762. }
  28763. }
  28764. // Material
  28765. if (this.material) {
  28766. serializationObject.materialId = this.material.id;
  28767. }
  28768. else {
  28769. this.material = null;
  28770. }
  28771. // Morph targets
  28772. if (this.morphTargetManager) {
  28773. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28774. }
  28775. // Skeleton
  28776. if (this.skeleton) {
  28777. serializationObject.skeletonId = this.skeleton.id;
  28778. }
  28779. // Physics
  28780. //TODO implement correct serialization for physics impostors.
  28781. var impostor = this.getPhysicsImpostor();
  28782. if (impostor) {
  28783. serializationObject.physicsMass = impostor.getParam("mass");
  28784. serializationObject.physicsFriction = impostor.getParam("friction");
  28785. serializationObject.physicsRestitution = impostor.getParam("mass");
  28786. serializationObject.physicsImpostor = impostor.type;
  28787. }
  28788. // Metadata
  28789. if (this.metadata) {
  28790. serializationObject.metadata = this.metadata;
  28791. }
  28792. // Instances
  28793. serializationObject.instances = [];
  28794. for (var index = 0; index < this.instances.length; index++) {
  28795. var instance = this.instances[index];
  28796. var serializationInstance = {
  28797. name: instance.name,
  28798. id: instance.id,
  28799. position: instance.position.asArray(),
  28800. scaling: instance.scaling.asArray()
  28801. };
  28802. if (instance.rotationQuaternion) {
  28803. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28804. }
  28805. else if (instance.rotation) {
  28806. serializationInstance.rotation = instance.rotation.asArray();
  28807. }
  28808. serializationObject.instances.push(serializationInstance);
  28809. // Animations
  28810. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28811. serializationInstance.ranges = instance.serializeAnimationRanges();
  28812. }
  28813. //
  28814. // Animations
  28815. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28816. serializationObject.ranges = this.serializeAnimationRanges();
  28817. // Layer mask
  28818. serializationObject.layerMask = this.layerMask;
  28819. // Alpha
  28820. serializationObject.alphaIndex = this.alphaIndex;
  28821. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28822. // Overlay
  28823. serializationObject.overlayAlpha = this.overlayAlpha;
  28824. serializationObject.overlayColor = this.overlayColor.asArray();
  28825. serializationObject.renderOverlay = this.renderOverlay;
  28826. // Fog
  28827. serializationObject.applyFog = this.applyFog;
  28828. // Action Manager
  28829. if (this.actionManager) {
  28830. serializationObject.actions = this.actionManager.serialize(this.name);
  28831. }
  28832. };
  28833. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28834. if (!this.geometry) {
  28835. return;
  28836. }
  28837. this._markSubMeshesAsAttributesDirty();
  28838. var morphTargetManager = this._morphTargetManager;
  28839. if (morphTargetManager && morphTargetManager.vertexCount) {
  28840. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28841. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28842. this.morphTargetManager = null;
  28843. return;
  28844. }
  28845. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28846. var morphTarget = morphTargetManager.getActiveTarget(index);
  28847. var positions = morphTarget.getPositions();
  28848. if (!positions) {
  28849. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28850. return;
  28851. }
  28852. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28853. var normals = morphTarget.getNormals();
  28854. if (normals) {
  28855. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28856. }
  28857. var tangents = morphTarget.getTangents();
  28858. if (tangents) {
  28859. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28860. }
  28861. }
  28862. }
  28863. else {
  28864. var index = 0;
  28865. // Positions
  28866. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28867. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28868. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28869. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28870. }
  28871. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28872. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28873. }
  28874. index++;
  28875. }
  28876. }
  28877. };
  28878. // Statics
  28879. /**
  28880. * Returns a new Mesh object parsed from the source provided.
  28881. * The parameter `parsedMesh` is the source.
  28882. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28883. */
  28884. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28885. var mesh;
  28886. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28887. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28888. }
  28889. else {
  28890. mesh = new Mesh(parsedMesh.name, scene);
  28891. }
  28892. mesh.id = parsedMesh.id;
  28893. if (BABYLON.Tags) {
  28894. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28895. }
  28896. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28897. if (parsedMesh.metadata !== undefined) {
  28898. mesh.metadata = parsedMesh.metadata;
  28899. }
  28900. if (parsedMesh.rotationQuaternion) {
  28901. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28902. }
  28903. else if (parsedMesh.rotation) {
  28904. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28905. }
  28906. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28907. if (parsedMesh.localMatrix) {
  28908. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28909. }
  28910. else if (parsedMesh.pivotMatrix) {
  28911. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28912. }
  28913. mesh.setEnabled(parsedMesh.isEnabled);
  28914. mesh.isVisible = parsedMesh.isVisible;
  28915. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28916. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28917. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28918. if (parsedMesh.applyFog !== undefined) {
  28919. mesh.applyFog = parsedMesh.applyFog;
  28920. }
  28921. if (parsedMesh.pickable !== undefined) {
  28922. mesh.isPickable = parsedMesh.pickable;
  28923. }
  28924. if (parsedMesh.alphaIndex !== undefined) {
  28925. mesh.alphaIndex = parsedMesh.alphaIndex;
  28926. }
  28927. mesh.receiveShadows = parsedMesh.receiveShadows;
  28928. mesh.billboardMode = parsedMesh.billboardMode;
  28929. if (parsedMesh.visibility !== undefined) {
  28930. mesh.visibility = parsedMesh.visibility;
  28931. }
  28932. mesh.checkCollisions = parsedMesh.checkCollisions;
  28933. if (parsedMesh.isBlocker !== undefined) {
  28934. mesh.isBlocker = parsedMesh.isBlocker;
  28935. }
  28936. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28937. // freezeWorldMatrix
  28938. if (parsedMesh.freezeWorldMatrix) {
  28939. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28940. }
  28941. // Parent
  28942. if (parsedMesh.parentId) {
  28943. mesh._waitingParentId = parsedMesh.parentId;
  28944. }
  28945. // Actions
  28946. if (parsedMesh.actions !== undefined) {
  28947. mesh._waitingActions = parsedMesh.actions;
  28948. }
  28949. // Overlay
  28950. if (parsedMesh.overlayAlpha !== undefined) {
  28951. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28952. }
  28953. if (parsedMesh.overlayColor !== undefined) {
  28954. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28955. }
  28956. if (parsedMesh.renderOverlay !== undefined) {
  28957. mesh.renderOverlay = parsedMesh.renderOverlay;
  28958. }
  28959. // Geometry
  28960. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28961. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28962. if (parsedMesh.delayLoadingFile) {
  28963. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28964. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28965. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28966. if (parsedMesh._binaryInfo) {
  28967. mesh._binaryInfo = parsedMesh._binaryInfo;
  28968. }
  28969. mesh._delayInfo = [];
  28970. if (parsedMesh.hasUVs) {
  28971. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28972. }
  28973. if (parsedMesh.hasUVs2) {
  28974. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28975. }
  28976. if (parsedMesh.hasUVs3) {
  28977. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28978. }
  28979. if (parsedMesh.hasUVs4) {
  28980. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28981. }
  28982. if (parsedMesh.hasUVs5) {
  28983. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28984. }
  28985. if (parsedMesh.hasUVs6) {
  28986. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28987. }
  28988. if (parsedMesh.hasColors) {
  28989. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28990. }
  28991. if (parsedMesh.hasMatricesIndices) {
  28992. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28993. }
  28994. if (parsedMesh.hasMatricesWeights) {
  28995. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28996. }
  28997. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  28998. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  28999. mesh._checkDelayState();
  29000. }
  29001. }
  29002. else {
  29003. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29004. }
  29005. // Material
  29006. if (parsedMesh.materialId) {
  29007. mesh.setMaterialByID(parsedMesh.materialId);
  29008. }
  29009. else {
  29010. mesh.material = null;
  29011. }
  29012. // Morph targets
  29013. if (parsedMesh.morphTargetManagerId > -1) {
  29014. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29015. }
  29016. // Skeleton
  29017. if (parsedMesh.skeletonId > -1) {
  29018. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29019. if (parsedMesh.numBoneInfluencers) {
  29020. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29021. }
  29022. }
  29023. // Animations
  29024. if (parsedMesh.animations) {
  29025. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29026. var parsedAnimation = parsedMesh.animations[animationIndex];
  29027. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29028. }
  29029. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29030. }
  29031. if (parsedMesh.autoAnimate) {
  29032. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29033. }
  29034. // Layer Mask
  29035. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29036. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29037. }
  29038. else {
  29039. mesh.layerMask = 0x0FFFFFFF;
  29040. }
  29041. // Physics
  29042. if (parsedMesh.physicsImpostor) {
  29043. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29044. mass: parsedMesh.physicsMass,
  29045. friction: parsedMesh.physicsFriction,
  29046. restitution: parsedMesh.physicsRestitution
  29047. }, scene);
  29048. }
  29049. // Instances
  29050. if (parsedMesh.instances) {
  29051. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29052. var parsedInstance = parsedMesh.instances[index];
  29053. var instance = mesh.createInstance(parsedInstance.name);
  29054. if (parsedInstance.id) {
  29055. instance.id = parsedInstance.id;
  29056. }
  29057. if (BABYLON.Tags) {
  29058. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29059. }
  29060. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29061. if (parsedInstance.parentId) {
  29062. instance._waitingParentId = parsedInstance.parentId;
  29063. }
  29064. if (parsedInstance.rotationQuaternion) {
  29065. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29066. }
  29067. else if (parsedInstance.rotation) {
  29068. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29069. }
  29070. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29071. instance.checkCollisions = mesh.checkCollisions;
  29072. if (parsedMesh.animations) {
  29073. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29074. parsedAnimation = parsedMesh.animations[animationIndex];
  29075. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29076. }
  29077. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29078. }
  29079. }
  29080. }
  29081. return mesh;
  29082. };
  29083. /**
  29084. * Creates a ribbon mesh.
  29085. * Please consider using the same method from the MeshBuilder class instead.
  29086. * 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.
  29087. *
  29088. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29089. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29090. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29091. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29092. * 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.
  29093. * 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.
  29094. * 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
  29095. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29096. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29097. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29098. */
  29099. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29100. if (closeArray === void 0) { closeArray = false; }
  29101. if (updatable === void 0) { updatable = false; }
  29102. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29103. pathArray: pathArray,
  29104. closeArray: closeArray,
  29105. closePath: closePath,
  29106. offset: offset,
  29107. updatable: updatable,
  29108. sideOrientation: sideOrientation,
  29109. instance: instance
  29110. }, scene);
  29111. };
  29112. /**
  29113. * Creates a plane polygonal mesh. By default, this is a disc.
  29114. * Please consider using the same method from the MeshBuilder class instead.
  29115. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29116. * 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.
  29117. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29118. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29120. */
  29121. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29122. if (scene === void 0) { scene = null; }
  29123. var options = {
  29124. radius: radius,
  29125. tessellation: tessellation,
  29126. sideOrientation: sideOrientation,
  29127. updatable: updatable
  29128. };
  29129. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29130. };
  29131. /**
  29132. * Creates a box mesh.
  29133. * Please consider using the same method from the MeshBuilder class instead.
  29134. * The parameter `size` sets the size (float) of each box side (default 1).
  29135. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29136. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29138. */
  29139. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29140. if (scene === void 0) { scene = null; }
  29141. var options = {
  29142. size: size,
  29143. sideOrientation: sideOrientation,
  29144. updatable: updatable
  29145. };
  29146. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29147. };
  29148. /**
  29149. * Creates a sphere mesh.
  29150. * Please consider using the same method from the MeshBuilder class instead.
  29151. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29152. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29153. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29154. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29156. */
  29157. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29158. var options = {
  29159. segments: segments,
  29160. diameterX: diameter,
  29161. diameterY: diameter,
  29162. diameterZ: diameter,
  29163. sideOrientation: sideOrientation,
  29164. updatable: updatable
  29165. };
  29166. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29167. };
  29168. /**
  29169. * Creates a cylinder or a cone mesh.
  29170. * Please consider using the same method from the MeshBuilder class instead.
  29171. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29172. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29173. * 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.
  29174. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29175. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29176. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29177. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29178. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29179. */
  29180. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29181. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29182. if (scene !== undefined) {
  29183. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29184. updatable = scene;
  29185. }
  29186. scene = subdivisions;
  29187. subdivisions = 1;
  29188. }
  29189. var options = {
  29190. height: height,
  29191. diameterTop: diameterTop,
  29192. diameterBottom: diameterBottom,
  29193. tessellation: tessellation,
  29194. subdivisions: subdivisions,
  29195. sideOrientation: sideOrientation,
  29196. updatable: updatable
  29197. };
  29198. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29199. };
  29200. // Torus (Code from SharpDX.org)
  29201. /**
  29202. * Creates a torus mesh.
  29203. * Please consider using the same method from the MeshBuilder class instead.
  29204. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29205. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29206. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29210. */
  29211. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29212. var options = {
  29213. diameter: diameter,
  29214. thickness: thickness,
  29215. tessellation: tessellation,
  29216. sideOrientation: sideOrientation,
  29217. updatable: updatable
  29218. };
  29219. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29220. };
  29221. /**
  29222. * Creates a torus knot mesh.
  29223. * Please consider using the same method from the MeshBuilder class instead.
  29224. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29225. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29226. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29227. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29228. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29229. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29230. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29231. */
  29232. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29233. var options = {
  29234. radius: radius,
  29235. tube: tube,
  29236. radialSegments: radialSegments,
  29237. tubularSegments: tubularSegments,
  29238. p: p,
  29239. q: q,
  29240. sideOrientation: sideOrientation,
  29241. updatable: updatable
  29242. };
  29243. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29244. };
  29245. /**
  29246. * Creates a line mesh.
  29247. * Please consider using the same method from the MeshBuilder class instead.
  29248. * 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.
  29249. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29250. * The parameter `points` is an array successive Vector3.
  29251. * 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
  29252. * When updating an instance, remember that only point positions can change, not the number of points.
  29253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29254. */
  29255. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29256. if (scene === void 0) { scene = null; }
  29257. if (updatable === void 0) { updatable = false; }
  29258. if (instance === void 0) { instance = null; }
  29259. var options = {
  29260. points: points,
  29261. updatable: updatable,
  29262. instance: instance
  29263. };
  29264. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29265. };
  29266. /**
  29267. * Creates a dashed line mesh.
  29268. * Please consider using the same method from the MeshBuilder class instead.
  29269. * 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.
  29270. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29271. * The parameter `points` is an array successive Vector3.
  29272. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29273. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29274. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29275. * 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
  29276. * When updating an instance, remember that only point positions can change, not the number of points.
  29277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29278. */
  29279. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29280. if (scene === void 0) { scene = null; }
  29281. var options = {
  29282. points: points,
  29283. dashSize: dashSize,
  29284. gapSize: gapSize,
  29285. dashNb: dashNb,
  29286. updatable: updatable,
  29287. instance: instance
  29288. };
  29289. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29290. };
  29291. /**
  29292. * Creates a polygon mesh.
  29293. * Please consider using the same method from the MeshBuilder class instead.
  29294. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29295. * 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.
  29296. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29297. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29298. * Remember you can only change the shape positions, not their number when updating a polygon.
  29299. */
  29300. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29301. var options = {
  29302. shape: shape,
  29303. holes: holes,
  29304. updatable: updatable,
  29305. sideOrientation: sideOrientation
  29306. };
  29307. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29308. };
  29309. /**
  29310. * Creates an extruded polygon mesh, with depth in the Y direction.
  29311. * Please consider using the same method from the MeshBuilder class instead.
  29312. */
  29313. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29314. var options = {
  29315. shape: shape,
  29316. holes: holes,
  29317. depth: depth,
  29318. updatable: updatable,
  29319. sideOrientation: sideOrientation
  29320. };
  29321. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29322. };
  29323. /**
  29324. * Creates an extruded shape mesh.
  29325. * 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.
  29326. * Please consider using the same method from the MeshBuilder class instead.
  29327. *
  29328. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29329. * 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
  29330. * extruded along the Z axis.
  29331. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29332. * 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.
  29333. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29334. * 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
  29335. * 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
  29336. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29337. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29338. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29340. */
  29341. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29342. if (scene === void 0) { scene = null; }
  29343. var options = {
  29344. shape: shape,
  29345. path: path,
  29346. scale: scale,
  29347. rotation: rotation,
  29348. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29349. sideOrientation: sideOrientation,
  29350. instance: instance,
  29351. updatable: updatable
  29352. };
  29353. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29354. };
  29355. /**
  29356. * Creates an custom extruded shape mesh.
  29357. * 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.
  29358. * Please consider using the same method from the MeshBuilder class instead.
  29359. *
  29360. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29361. * 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
  29362. * extruded along the Z axis.
  29363. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29364. * 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
  29365. * and the distance of this point from the begining of the path :
  29366. * ```javascript
  29367. * var rotationFunction = function(i, distance) {
  29368. * // do things
  29369. * return rotationValue; }
  29370. * ```
  29371. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29372. * 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
  29373. * and the distance of this point from the begining of the path :
  29374. * ```javascript
  29375. * var scaleFunction = function(i, distance) {
  29376. * // do things
  29377. * return scaleValue;}
  29378. * ```
  29379. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29380. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29381. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29382. * 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
  29383. * 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
  29384. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29385. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29386. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29387. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29388. */
  29389. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29390. var options = {
  29391. shape: shape,
  29392. path: path,
  29393. scaleFunction: scaleFunction,
  29394. rotationFunction: rotationFunction,
  29395. ribbonCloseArray: ribbonCloseArray,
  29396. ribbonClosePath: ribbonClosePath,
  29397. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29398. sideOrientation: sideOrientation,
  29399. instance: instance,
  29400. updatable: updatable
  29401. };
  29402. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29403. };
  29404. /**
  29405. * Creates lathe mesh.
  29406. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29407. * Please consider using the same method from the MeshBuilder class instead.
  29408. * 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
  29409. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29410. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29411. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29412. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29413. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29414. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29415. */
  29416. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29417. var options = {
  29418. shape: shape,
  29419. radius: radius,
  29420. tessellation: tessellation,
  29421. sideOrientation: sideOrientation,
  29422. updatable: updatable
  29423. };
  29424. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29425. };
  29426. /**
  29427. * Creates a plane mesh.
  29428. * Please consider using the same method from the MeshBuilder class instead.
  29429. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29430. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29431. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29432. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29433. */
  29434. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29435. var options = {
  29436. size: size,
  29437. width: size,
  29438. height: size,
  29439. sideOrientation: sideOrientation,
  29440. updatable: updatable
  29441. };
  29442. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29443. };
  29444. /**
  29445. * Creates a ground mesh.
  29446. * Please consider using the same method from the MeshBuilder class instead.
  29447. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29448. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29450. */
  29451. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29452. var options = {
  29453. width: width,
  29454. height: height,
  29455. subdivisions: subdivisions,
  29456. updatable: updatable
  29457. };
  29458. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29459. };
  29460. /**
  29461. * Creates a tiled ground mesh.
  29462. * Please consider using the same method from the MeshBuilder class instead.
  29463. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29464. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29465. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29466. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29467. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29468. * numbers of subdivisions on the ground width and height of each tile.
  29469. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29470. */
  29471. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29472. var options = {
  29473. xmin: xmin,
  29474. zmin: zmin,
  29475. xmax: xmax,
  29476. zmax: zmax,
  29477. subdivisions: subdivisions,
  29478. precision: precision,
  29479. updatable: updatable
  29480. };
  29481. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29482. };
  29483. /**
  29484. * Creates a ground mesh from a height map.
  29485. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29486. * Please consider using the same method from the MeshBuilder class instead.
  29487. * The parameter `url` sets the URL of the height map image resource.
  29488. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29489. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29490. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29491. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29492. * 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).
  29493. * This function is passed the newly built mesh :
  29494. * ```javascript
  29495. * function(mesh) { // do things
  29496. * return; }
  29497. * ```
  29498. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29499. */
  29500. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29501. var options = {
  29502. width: width,
  29503. height: height,
  29504. subdivisions: subdivisions,
  29505. minHeight: minHeight,
  29506. maxHeight: maxHeight,
  29507. updatable: updatable,
  29508. onReady: onReady
  29509. };
  29510. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29511. };
  29512. /**
  29513. * Creates a tube mesh.
  29514. * 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.
  29515. * Please consider using the same method from the MeshBuilder class instead.
  29516. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29517. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29518. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29519. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29520. * 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.
  29521. * It must return a radius value (positive float) :
  29522. * ```javascript
  29523. * var radiusFunction = function(i, distance) {
  29524. * // do things
  29525. * return radius; }
  29526. * ```
  29527. * 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
  29528. * 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
  29529. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29530. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29531. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29532. */
  29533. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29534. var options = {
  29535. path: path,
  29536. radius: radius,
  29537. tessellation: tessellation,
  29538. radiusFunction: radiusFunction,
  29539. arc: 1,
  29540. cap: cap,
  29541. updatable: updatable,
  29542. sideOrientation: sideOrientation,
  29543. instance: instance
  29544. };
  29545. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29546. };
  29547. /**
  29548. * Creates a polyhedron mesh.
  29549. * Please consider using the same method from the MeshBuilder class instead.
  29550. * 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
  29551. * to choose the wanted type.
  29552. * The parameter `size` (positive float, default 1) sets the polygon size.
  29553. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29554. * 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`.
  29555. * 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
  29556. * 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)`).
  29557. * 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
  29558. * 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.
  29559. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29560. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29561. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29562. */
  29563. Mesh.CreatePolyhedron = function (name, options, scene) {
  29564. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29565. };
  29566. /**
  29567. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29568. * Please consider using the same method from the MeshBuilder class instead.
  29569. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29570. * 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`).
  29571. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29572. * 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.
  29573. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29574. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29575. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29576. */
  29577. Mesh.CreateIcoSphere = function (name, options, scene) {
  29578. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29579. };
  29580. /**
  29581. * Creates a decal mesh.
  29582. * Please consider using the same method from the MeshBuilder class instead.
  29583. * 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.
  29584. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29585. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29586. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29587. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29588. */
  29589. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29590. var options = {
  29591. position: position,
  29592. normal: normal,
  29593. size: size,
  29594. angle: angle
  29595. };
  29596. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29597. };
  29598. // Skeletons
  29599. /**
  29600. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29601. */
  29602. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29603. if (!this._sourcePositions) {
  29604. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29605. if (!source) {
  29606. return this._sourcePositions;
  29607. }
  29608. this._sourcePositions = new Float32Array(source);
  29609. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29610. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29611. }
  29612. }
  29613. return this._sourcePositions;
  29614. };
  29615. /**
  29616. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29617. */
  29618. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29619. if (!this._sourceNormals) {
  29620. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29621. if (!source) {
  29622. return this._sourceNormals;
  29623. }
  29624. this._sourceNormals = new Float32Array(source);
  29625. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29626. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29627. }
  29628. }
  29629. return this._sourceNormals;
  29630. };
  29631. /**
  29632. * Updates the vertex buffer by applying transformation from the bones.
  29633. * Returns the Mesh.
  29634. *
  29635. * @param {skeleton} skeleton to apply
  29636. */
  29637. Mesh.prototype.applySkeleton = function (skeleton) {
  29638. if (!this.geometry) {
  29639. return this;
  29640. }
  29641. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29642. return this;
  29643. }
  29644. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29645. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29646. return this;
  29647. }
  29648. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29649. return this;
  29650. }
  29651. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29652. return this;
  29653. }
  29654. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29655. return this;
  29656. }
  29657. if (!this._sourcePositions) {
  29658. var submeshes = this.subMeshes.slice();
  29659. this.setPositionsForCPUSkinning();
  29660. this.subMeshes = submeshes;
  29661. }
  29662. if (!this._sourceNormals) {
  29663. this.setNormalsForCPUSkinning();
  29664. }
  29665. // positionsData checks for not being Float32Array will only pass at most once
  29666. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29667. if (!positionsData) {
  29668. return this;
  29669. }
  29670. if (!(positionsData instanceof Float32Array)) {
  29671. positionsData = new Float32Array(positionsData);
  29672. }
  29673. // normalsData checks for not being Float32Array will only pass at most once
  29674. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29675. if (!normalsData) {
  29676. return this;
  29677. }
  29678. if (!(normalsData instanceof Float32Array)) {
  29679. normalsData = new Float32Array(normalsData);
  29680. }
  29681. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29682. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29683. if (!matricesWeightsData || !matricesIndicesData) {
  29684. return this;
  29685. }
  29686. var needExtras = this.numBoneInfluencers > 4;
  29687. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29688. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29689. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29690. var tempVector3 = BABYLON.Vector3.Zero();
  29691. var finalMatrix = new BABYLON.Matrix();
  29692. var tempMatrix = new BABYLON.Matrix();
  29693. var matWeightIdx = 0;
  29694. var inf;
  29695. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29696. var weight;
  29697. for (inf = 0; inf < 4; inf++) {
  29698. weight = matricesWeightsData[matWeightIdx + inf];
  29699. if (weight > 0) {
  29700. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29701. finalMatrix.addToSelf(tempMatrix);
  29702. }
  29703. else
  29704. break;
  29705. }
  29706. if (needExtras) {
  29707. for (inf = 0; inf < 4; inf++) {
  29708. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29709. if (weight > 0) {
  29710. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29711. finalMatrix.addToSelf(tempMatrix);
  29712. }
  29713. else
  29714. break;
  29715. }
  29716. }
  29717. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29718. tempVector3.toArray(positionsData, index);
  29719. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29720. tempVector3.toArray(normalsData, index);
  29721. finalMatrix.reset();
  29722. }
  29723. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29724. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29725. return this;
  29726. };
  29727. // Tools
  29728. /**
  29729. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29730. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29731. */
  29732. Mesh.MinMax = function (meshes) {
  29733. var minVector = null;
  29734. var maxVector = null;
  29735. meshes.forEach(function (mesh, index, array) {
  29736. var boundingInfo = mesh.getBoundingInfo();
  29737. var boundingBox = boundingInfo.boundingBox;
  29738. if (!minVector || !maxVector) {
  29739. minVector = boundingBox.minimumWorld;
  29740. maxVector = boundingBox.maximumWorld;
  29741. }
  29742. else {
  29743. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29744. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29745. }
  29746. });
  29747. if (!minVector || !maxVector) {
  29748. return {
  29749. min: BABYLON.Vector3.Zero(),
  29750. max: BABYLON.Vector3.Zero()
  29751. };
  29752. }
  29753. return {
  29754. min: minVector,
  29755. max: maxVector
  29756. };
  29757. };
  29758. /**
  29759. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29760. */
  29761. Mesh.Center = function (meshesOrMinMaxVector) {
  29762. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29763. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29764. };
  29765. /**
  29766. * Merge the array of meshes into a single mesh for performance reasons.
  29767. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29768. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29769. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29770. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29771. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29772. */
  29773. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29774. if (disposeSource === void 0) { disposeSource = true; }
  29775. var index;
  29776. if (!allow32BitsIndices) {
  29777. var totalVertices = 0;
  29778. // Counting vertices
  29779. for (index = 0; index < meshes.length; index++) {
  29780. if (meshes[index]) {
  29781. totalVertices += meshes[index].getTotalVertices();
  29782. if (totalVertices > 65536) {
  29783. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29784. return null;
  29785. }
  29786. }
  29787. }
  29788. }
  29789. // Merge
  29790. var vertexData = null;
  29791. var otherVertexData;
  29792. var indiceArray = new Array();
  29793. var source = null;
  29794. for (index = 0; index < meshes.length; index++) {
  29795. if (meshes[index]) {
  29796. meshes[index].computeWorldMatrix(true);
  29797. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29798. otherVertexData.transform(meshes[index].getWorldMatrix());
  29799. if (vertexData) {
  29800. vertexData.merge(otherVertexData);
  29801. }
  29802. else {
  29803. vertexData = otherVertexData;
  29804. source = meshes[index];
  29805. }
  29806. if (subdivideWithSubMeshes) {
  29807. indiceArray.push(meshes[index].getTotalIndices());
  29808. }
  29809. }
  29810. }
  29811. source = source;
  29812. if (!meshSubclass) {
  29813. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29814. }
  29815. vertexData.applyToMesh(meshSubclass);
  29816. // Setting properties
  29817. meshSubclass.material = source.material;
  29818. meshSubclass.checkCollisions = source.checkCollisions;
  29819. // Cleaning
  29820. if (disposeSource) {
  29821. for (index = 0; index < meshes.length; index++) {
  29822. if (meshes[index]) {
  29823. meshes[index].dispose();
  29824. }
  29825. }
  29826. }
  29827. // Subdivide
  29828. if (subdivideWithSubMeshes) {
  29829. //-- Suppresions du submesh global
  29830. meshSubclass.releaseSubMeshes();
  29831. index = 0;
  29832. var offset = 0;
  29833. //-- aplique la subdivision en fonction du tableau d'indices
  29834. while (index < indiceArray.length) {
  29835. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29836. offset += indiceArray[index];
  29837. index++;
  29838. }
  29839. }
  29840. return meshSubclass;
  29841. };
  29842. // Consts
  29843. Mesh._FRONTSIDE = 0;
  29844. Mesh._BACKSIDE = 1;
  29845. Mesh._DOUBLESIDE = 2;
  29846. Mesh._DEFAULTSIDE = 0;
  29847. Mesh._NO_CAP = 0;
  29848. Mesh._CAP_START = 1;
  29849. Mesh._CAP_END = 2;
  29850. Mesh._CAP_ALL = 3;
  29851. return Mesh;
  29852. }(BABYLON.AbstractMesh));
  29853. BABYLON.Mesh = Mesh;
  29854. })(BABYLON || (BABYLON = {}));
  29855. //# sourceMappingURL=babylon.mesh.js.map
  29856. var BABYLON;
  29857. (function (BABYLON) {
  29858. var BaseSubMesh = /** @class */ (function () {
  29859. function BaseSubMesh() {
  29860. }
  29861. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29862. get: function () {
  29863. return this._materialEffect;
  29864. },
  29865. enumerable: true,
  29866. configurable: true
  29867. });
  29868. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29869. if (defines === void 0) { defines = null; }
  29870. if (this._materialEffect === effect) {
  29871. if (!effect) {
  29872. this._materialDefines = null;
  29873. }
  29874. return;
  29875. }
  29876. this._materialDefines = defines;
  29877. this._materialEffect = effect;
  29878. };
  29879. return BaseSubMesh;
  29880. }());
  29881. BABYLON.BaseSubMesh = BaseSubMesh;
  29882. var SubMesh = /** @class */ (function (_super) {
  29883. __extends(SubMesh, _super);
  29884. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29885. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29886. var _this = _super.call(this) || this;
  29887. _this.materialIndex = materialIndex;
  29888. _this.verticesStart = verticesStart;
  29889. _this.verticesCount = verticesCount;
  29890. _this.indexStart = indexStart;
  29891. _this.indexCount = indexCount;
  29892. _this._renderId = 0;
  29893. _this._mesh = mesh;
  29894. _this._renderingMesh = renderingMesh || mesh;
  29895. mesh.subMeshes.push(_this);
  29896. _this._trianglePlanes = [];
  29897. _this._id = mesh.subMeshes.length - 1;
  29898. if (createBoundingBox) {
  29899. _this.refreshBoundingInfo();
  29900. mesh.computeWorldMatrix(true);
  29901. }
  29902. return _this;
  29903. }
  29904. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29905. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29906. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29907. };
  29908. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29909. get: function () {
  29910. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29911. },
  29912. enumerable: true,
  29913. configurable: true
  29914. });
  29915. /**
  29916. * Returns the submesh BoudingInfo object.
  29917. */
  29918. SubMesh.prototype.getBoundingInfo = function () {
  29919. if (this.IsGlobal) {
  29920. return this._mesh.getBoundingInfo();
  29921. }
  29922. return this._boundingInfo;
  29923. };
  29924. /**
  29925. * Sets the submesh BoundingInfo.
  29926. * Return the SubMesh.
  29927. */
  29928. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29929. this._boundingInfo = boundingInfo;
  29930. return this;
  29931. };
  29932. /**
  29933. * Returns the mesh of the current submesh.
  29934. */
  29935. SubMesh.prototype.getMesh = function () {
  29936. return this._mesh;
  29937. };
  29938. /**
  29939. * Returns the rendering mesh of the submesh.
  29940. */
  29941. SubMesh.prototype.getRenderingMesh = function () {
  29942. return this._renderingMesh;
  29943. };
  29944. /**
  29945. * Returns the submesh material.
  29946. */
  29947. SubMesh.prototype.getMaterial = function () {
  29948. var rootMaterial = this._renderingMesh.material;
  29949. if (rootMaterial === null || rootMaterial === undefined) {
  29950. return this._mesh.getScene().defaultMaterial;
  29951. }
  29952. else if (rootMaterial.getSubMaterial) {
  29953. var multiMaterial = rootMaterial;
  29954. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29955. if (this._currentMaterial !== effectiveMaterial) {
  29956. this._currentMaterial = effectiveMaterial;
  29957. this._materialDefines = null;
  29958. }
  29959. return effectiveMaterial;
  29960. }
  29961. return rootMaterial;
  29962. };
  29963. // Methods
  29964. /**
  29965. * Sets a new updated BoundingInfo object to the submesh.
  29966. * Returns the SubMesh.
  29967. */
  29968. SubMesh.prototype.refreshBoundingInfo = function () {
  29969. this._lastColliderWorldVertices = null;
  29970. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29971. return this;
  29972. }
  29973. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29974. if (!data) {
  29975. this._boundingInfo = this._mesh.getBoundingInfo();
  29976. return this;
  29977. }
  29978. var indices = this._renderingMesh.getIndices();
  29979. var extend;
  29980. //is this the only submesh?
  29981. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29982. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29983. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29984. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29985. }
  29986. else {
  29987. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29988. }
  29989. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29990. return this;
  29991. };
  29992. SubMesh.prototype._checkCollision = function (collider) {
  29993. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29994. return boundingInfo._checkCollision(collider);
  29995. };
  29996. /**
  29997. * Updates the submesh BoundingInfo.
  29998. * Returns the Submesh.
  29999. */
  30000. SubMesh.prototype.updateBoundingInfo = function (world) {
  30001. var boundingInfo = this.getBoundingInfo();
  30002. if (!boundingInfo) {
  30003. this.refreshBoundingInfo();
  30004. boundingInfo = this.getBoundingInfo();
  30005. }
  30006. boundingInfo.update(world);
  30007. return this;
  30008. };
  30009. /**
  30010. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30011. * Boolean returned.
  30012. */
  30013. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30014. var boundingInfo = this.getBoundingInfo();
  30015. if (!boundingInfo) {
  30016. return false;
  30017. }
  30018. return boundingInfo.isInFrustum(frustumPlanes);
  30019. };
  30020. /**
  30021. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30022. * Boolean returned.
  30023. */
  30024. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30025. var boundingInfo = this.getBoundingInfo();
  30026. if (!boundingInfo) {
  30027. return false;
  30028. }
  30029. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30030. };
  30031. /**
  30032. * Renders the submesh.
  30033. * Returns it.
  30034. */
  30035. SubMesh.prototype.render = function (enableAlphaMode) {
  30036. this._renderingMesh.render(this, enableAlphaMode);
  30037. return this;
  30038. };
  30039. /**
  30040. * Returns a new Index Buffer.
  30041. * Type returned : WebGLBuffer.
  30042. */
  30043. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30044. if (!this._linesIndexBuffer) {
  30045. var linesIndices = [];
  30046. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30047. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30048. }
  30049. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30050. this.linesIndexCount = linesIndices.length;
  30051. }
  30052. return this._linesIndexBuffer;
  30053. };
  30054. /**
  30055. * True is the passed Ray intersects the submesh bounding box.
  30056. * Boolean returned.
  30057. */
  30058. SubMesh.prototype.canIntersects = function (ray) {
  30059. var boundingInfo = this.getBoundingInfo();
  30060. if (!boundingInfo) {
  30061. return false;
  30062. }
  30063. return ray.intersectsBox(boundingInfo.boundingBox);
  30064. };
  30065. /**
  30066. * Returns an object IntersectionInfo.
  30067. */
  30068. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30069. var intersectInfo = null;
  30070. // LineMesh first as it's also a Mesh...
  30071. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30072. var lineMesh = this._mesh;
  30073. // Line test
  30074. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30075. var p0 = positions[indices[index]];
  30076. var p1 = positions[indices[index + 1]];
  30077. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30078. if (length < 0) {
  30079. continue;
  30080. }
  30081. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30082. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30083. if (fastCheck) {
  30084. break;
  30085. }
  30086. }
  30087. }
  30088. }
  30089. else {
  30090. // Triangles test
  30091. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30092. var p0 = positions[indices[index]];
  30093. var p1 = positions[indices[index + 1]];
  30094. var p2 = positions[indices[index + 2]];
  30095. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30096. if (currentIntersectInfo) {
  30097. if (currentIntersectInfo.distance < 0) {
  30098. continue;
  30099. }
  30100. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30101. intersectInfo = currentIntersectInfo;
  30102. intersectInfo.faceId = index / 3;
  30103. if (fastCheck) {
  30104. break;
  30105. }
  30106. }
  30107. }
  30108. }
  30109. }
  30110. return intersectInfo;
  30111. };
  30112. SubMesh.prototype._rebuild = function () {
  30113. if (this._linesIndexBuffer) {
  30114. this._linesIndexBuffer = null;
  30115. }
  30116. };
  30117. // Clone
  30118. /**
  30119. * Creates a new Submesh from the passed Mesh.
  30120. */
  30121. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30122. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30123. if (!this.IsGlobal) {
  30124. var boundingInfo = this.getBoundingInfo();
  30125. if (!boundingInfo) {
  30126. return result;
  30127. }
  30128. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30129. }
  30130. return result;
  30131. };
  30132. // Dispose
  30133. /**
  30134. * Disposes the Submesh.
  30135. * Returns nothing.
  30136. */
  30137. SubMesh.prototype.dispose = function () {
  30138. if (this._linesIndexBuffer) {
  30139. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30140. this._linesIndexBuffer = null;
  30141. }
  30142. // Remove from mesh
  30143. var index = this._mesh.subMeshes.indexOf(this);
  30144. this._mesh.subMeshes.splice(index, 1);
  30145. };
  30146. // Statics
  30147. /**
  30148. * Creates a new Submesh from the passed parameters :
  30149. * - materialIndex (integer) : the index of the main mesh material.
  30150. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30151. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30152. * - mesh (Mesh) : the main mesh to create the submesh from.
  30153. * - renderingMesh (optional Mesh) : rendering mesh.
  30154. */
  30155. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30156. var minVertexIndex = Number.MAX_VALUE;
  30157. var maxVertexIndex = -Number.MAX_VALUE;
  30158. renderingMesh = (renderingMesh || mesh);
  30159. var indices = renderingMesh.getIndices();
  30160. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30161. var vertexIndex = indices[index];
  30162. if (vertexIndex < minVertexIndex)
  30163. minVertexIndex = vertexIndex;
  30164. if (vertexIndex > maxVertexIndex)
  30165. maxVertexIndex = vertexIndex;
  30166. }
  30167. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30168. };
  30169. return SubMesh;
  30170. }(BaseSubMesh));
  30171. BABYLON.SubMesh = SubMesh;
  30172. })(BABYLON || (BABYLON = {}));
  30173. //# sourceMappingURL=babylon.subMesh.js.map
  30174. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30175. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30176. s = arguments[i];
  30177. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30178. t[p] = s[p];
  30179. }
  30180. return t;
  30181. };
  30182. var BABYLON;
  30183. (function (BABYLON) {
  30184. /**
  30185. * Manages the defines for the Material.
  30186. */
  30187. var MaterialDefines = /** @class */ (function () {
  30188. function MaterialDefines() {
  30189. this._isDirty = true;
  30190. this._areLightsDirty = true;
  30191. this._areAttributesDirty = true;
  30192. this._areTexturesDirty = true;
  30193. this._areFresnelDirty = true;
  30194. this._areMiscDirty = true;
  30195. this._areImageProcessingDirty = true;
  30196. this._normals = false;
  30197. this._uvs = false;
  30198. this._needNormals = false;
  30199. this._needUVs = false;
  30200. }
  30201. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30202. /**
  30203. * Specifies if the material needs to be re-calculated.
  30204. */
  30205. get: function () {
  30206. return this._isDirty;
  30207. },
  30208. enumerable: true,
  30209. configurable: true
  30210. });
  30211. /**
  30212. * Marks the material to indicate that it has been re-calculated.
  30213. */
  30214. MaterialDefines.prototype.markAsProcessed = function () {
  30215. this._isDirty = false;
  30216. this._areAttributesDirty = false;
  30217. this._areTexturesDirty = false;
  30218. this._areFresnelDirty = false;
  30219. this._areLightsDirty = false;
  30220. this._areMiscDirty = false;
  30221. this._areImageProcessingDirty = false;
  30222. };
  30223. /**
  30224. * Marks the material to indicate that it needs to be re-calculated.
  30225. */
  30226. MaterialDefines.prototype.markAsUnprocessed = function () {
  30227. this._isDirty = true;
  30228. };
  30229. /**
  30230. * Marks the material to indicate all of its defines need to be re-calculated.
  30231. */
  30232. MaterialDefines.prototype.markAllAsDirty = function () {
  30233. this._areTexturesDirty = true;
  30234. this._areAttributesDirty = true;
  30235. this._areLightsDirty = true;
  30236. this._areFresnelDirty = true;
  30237. this._areMiscDirty = true;
  30238. this._areImageProcessingDirty = true;
  30239. this._isDirty = true;
  30240. };
  30241. /**
  30242. * Marks the material to indicate that image processing needs to be re-calculated.
  30243. */
  30244. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30245. this._areImageProcessingDirty = true;
  30246. this._isDirty = true;
  30247. };
  30248. /**
  30249. * Marks the material to indicate the lights need to be re-calculated.
  30250. */
  30251. MaterialDefines.prototype.markAsLightDirty = function () {
  30252. this._areLightsDirty = true;
  30253. this._isDirty = true;
  30254. };
  30255. /**
  30256. * Marks the attribute state as changed.
  30257. */
  30258. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30259. this._areAttributesDirty = true;
  30260. this._isDirty = true;
  30261. };
  30262. /**
  30263. * Marks the texture state as changed.
  30264. */
  30265. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30266. this._areTexturesDirty = true;
  30267. this._isDirty = true;
  30268. };
  30269. /**
  30270. * Marks the fresnel state as changed.
  30271. */
  30272. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30273. this._areFresnelDirty = true;
  30274. this._isDirty = true;
  30275. };
  30276. /**
  30277. * Marks the misc state as changed.
  30278. */
  30279. MaterialDefines.prototype.markAsMiscDirty = function () {
  30280. this._areMiscDirty = true;
  30281. this._isDirty = true;
  30282. };
  30283. /**
  30284. * Rebuilds the material defines.
  30285. */
  30286. MaterialDefines.prototype.rebuild = function () {
  30287. if (this._keys) {
  30288. delete this._keys;
  30289. }
  30290. this._keys = [];
  30291. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30292. var key = _a[_i];
  30293. if (key[0] === "_") {
  30294. continue;
  30295. }
  30296. this._keys.push(key);
  30297. }
  30298. };
  30299. /**
  30300. * Specifies if two material defines are equal.
  30301. * @param other - A material define instance to compare to.
  30302. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30303. */
  30304. MaterialDefines.prototype.isEqual = function (other) {
  30305. if (this._keys.length !== other._keys.length) {
  30306. return false;
  30307. }
  30308. for (var index = 0; index < this._keys.length; index++) {
  30309. var prop = this._keys[index];
  30310. if (this[prop] !== other[prop]) {
  30311. return false;
  30312. }
  30313. }
  30314. return true;
  30315. };
  30316. /**
  30317. * Clones this instance's defines to another instance.
  30318. * @param other - material defines to clone values to.
  30319. */
  30320. MaterialDefines.prototype.cloneTo = function (other) {
  30321. if (this._keys.length !== other._keys.length) {
  30322. other._keys = this._keys.slice(0);
  30323. }
  30324. for (var index = 0; index < this._keys.length; index++) {
  30325. var prop = this._keys[index];
  30326. other[prop] = this[prop];
  30327. }
  30328. };
  30329. /**
  30330. * Resets the material define values.
  30331. */
  30332. MaterialDefines.prototype.reset = function () {
  30333. for (var index = 0; index < this._keys.length; index++) {
  30334. var prop = this._keys[index];
  30335. if (typeof (this[prop]) === "number") {
  30336. this[prop] = 0;
  30337. }
  30338. else {
  30339. this[prop] = false;
  30340. }
  30341. }
  30342. };
  30343. /**
  30344. * Converts the material define values to a string.
  30345. * @returns - String of material define information.
  30346. */
  30347. MaterialDefines.prototype.toString = function () {
  30348. var result = "";
  30349. for (var index = 0; index < this._keys.length; index++) {
  30350. var prop = this._keys[index];
  30351. var value = this[prop];
  30352. if (typeof (value) === "number") {
  30353. result += "#define " + prop + " " + this[prop] + "\n";
  30354. }
  30355. else if (value) {
  30356. result += "#define " + prop + "\n";
  30357. }
  30358. }
  30359. return result;
  30360. };
  30361. return MaterialDefines;
  30362. }());
  30363. BABYLON.MaterialDefines = MaterialDefines;
  30364. /**
  30365. * This offers the main features of a material in BJS.
  30366. */
  30367. var Material = /** @class */ (function () {
  30368. /**
  30369. * Creates a material instance.
  30370. * @param name - The name of the material.
  30371. * @param scene - The BJS scene to reference.
  30372. * @param doNotAdd - Specifies if the material should be added to the scene.
  30373. */
  30374. function Material(name, scene, doNotAdd) {
  30375. /**
  30376. * Specifies if the ready state should be checked on each call.
  30377. */
  30378. this.checkReadyOnEveryCall = false;
  30379. /**
  30380. * Specifies if the ready state should be checked once.
  30381. */
  30382. this.checkReadyOnlyOnce = false;
  30383. /**
  30384. * The state of the material.
  30385. */
  30386. this.state = "";
  30387. /**
  30388. * The alpha value of the material.
  30389. */
  30390. this._alpha = 1.0;
  30391. /**
  30392. * Specifies if back face culling is enabled.
  30393. */
  30394. this._backFaceCulling = true;
  30395. /**
  30396. * Specifies if the material should be serialized.
  30397. */
  30398. this.doNotSerialize = false;
  30399. /**
  30400. * Specifies if the effect should be stored on sub meshes.
  30401. */
  30402. this.storeEffectOnSubMeshes = false;
  30403. /**
  30404. * An event triggered when the material is disposed.
  30405. * @type {BABYLON.Observable}
  30406. */
  30407. this.onDisposeObservable = new BABYLON.Observable();
  30408. /**
  30409. * An event triggered when the material is bound.
  30410. * @type {BABYLON.Observable}
  30411. */
  30412. this.onBindObservable = new BABYLON.Observable();
  30413. /**
  30414. * An event triggered when the material is unbound.
  30415. * @type {BABYLON.Observable}
  30416. */
  30417. this.onUnBindObservable = new BABYLON.Observable();
  30418. /**
  30419. * Stores the value of the alpha mode.
  30420. */
  30421. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30422. /**
  30423. * Stores the state of the need depth pre-pass value.
  30424. */
  30425. this._needDepthPrePass = false;
  30426. /**
  30427. * Specifies if depth writing should be disabled.
  30428. */
  30429. this.disableDepthWrite = false;
  30430. /**
  30431. * Specifies if depth writing should be forced.
  30432. */
  30433. this.forceDepthWrite = false;
  30434. /**
  30435. * Specifies if there should be a separate pass for culling.
  30436. */
  30437. this.separateCullingPass = false;
  30438. /**
  30439. * Stores the state specifing if fog should be enabled.
  30440. */
  30441. this._fogEnabled = true;
  30442. /**
  30443. * Stores the size of points.
  30444. */
  30445. this.pointSize = 1.0;
  30446. /**
  30447. * Stores the z offset value.
  30448. */
  30449. this.zOffset = 0;
  30450. /**
  30451. * Specifies if the material was previously ready.
  30452. */
  30453. this._wasPreviouslyReady = false;
  30454. /**
  30455. * Stores the fill mode state.
  30456. */
  30457. this._fillMode = Material.TriangleFillMode;
  30458. this.name = name;
  30459. this.id = name || BABYLON.Tools.RandomId();
  30460. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30461. if (this._scene.useRightHandedSystem) {
  30462. this.sideOrientation = Material.ClockWiseSideOrientation;
  30463. }
  30464. else {
  30465. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30466. }
  30467. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30468. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30469. if (!doNotAdd) {
  30470. this._scene.materials.push(this);
  30471. }
  30472. }
  30473. Object.defineProperty(Material, "TriangleFillMode", {
  30474. /**
  30475. * Returns the triangle fill mode.
  30476. */
  30477. get: function () {
  30478. return Material._TriangleFillMode;
  30479. },
  30480. enumerable: true,
  30481. configurable: true
  30482. });
  30483. Object.defineProperty(Material, "WireFrameFillMode", {
  30484. /**
  30485. * Returns the wireframe mode.
  30486. */
  30487. get: function () {
  30488. return Material._WireFrameFillMode;
  30489. },
  30490. enumerable: true,
  30491. configurable: true
  30492. });
  30493. Object.defineProperty(Material, "PointFillMode", {
  30494. /**
  30495. * Returns the point fill mode.
  30496. */
  30497. get: function () {
  30498. return Material._PointFillMode;
  30499. },
  30500. enumerable: true,
  30501. configurable: true
  30502. });
  30503. Object.defineProperty(Material, "PointListDrawMode", {
  30504. /**
  30505. * Returns the point list draw mode.
  30506. */
  30507. get: function () {
  30508. return Material._PointListDrawMode;
  30509. },
  30510. enumerable: true,
  30511. configurable: true
  30512. });
  30513. Object.defineProperty(Material, "LineListDrawMode", {
  30514. /**
  30515. * Returns the line list draw mode.
  30516. */
  30517. get: function () {
  30518. return Material._LineListDrawMode;
  30519. },
  30520. enumerable: true,
  30521. configurable: true
  30522. });
  30523. Object.defineProperty(Material, "LineLoopDrawMode", {
  30524. /**
  30525. * Returns the line loop draw mode.
  30526. */
  30527. get: function () {
  30528. return Material._LineLoopDrawMode;
  30529. },
  30530. enumerable: true,
  30531. configurable: true
  30532. });
  30533. Object.defineProperty(Material, "LineStripDrawMode", {
  30534. /**
  30535. * Returns the line strip draw mode.
  30536. */
  30537. get: function () {
  30538. return Material._LineStripDrawMode;
  30539. },
  30540. enumerable: true,
  30541. configurable: true
  30542. });
  30543. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30544. /**
  30545. * Returns the triangle strip draw mode.
  30546. */
  30547. get: function () {
  30548. return Material._TriangleStripDrawMode;
  30549. },
  30550. enumerable: true,
  30551. configurable: true
  30552. });
  30553. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30554. /**
  30555. * Returns the triangle fan draw mode.
  30556. */
  30557. get: function () {
  30558. return Material._TriangleFanDrawMode;
  30559. },
  30560. enumerable: true,
  30561. configurable: true
  30562. });
  30563. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30564. /**
  30565. * Returns the clock-wise side orientation.
  30566. */
  30567. get: function () {
  30568. return Material._ClockWiseSideOrientation;
  30569. },
  30570. enumerable: true,
  30571. configurable: true
  30572. });
  30573. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30574. /**
  30575. * Returns the counter clock-wise side orientation.
  30576. */
  30577. get: function () {
  30578. return Material._CounterClockWiseSideOrientation;
  30579. },
  30580. enumerable: true,
  30581. configurable: true
  30582. });
  30583. Object.defineProperty(Material, "TextureDirtyFlag", {
  30584. /**
  30585. * Returns the dirty texture flag value.
  30586. */
  30587. get: function () {
  30588. return Material._TextureDirtyFlag;
  30589. },
  30590. enumerable: true,
  30591. configurable: true
  30592. });
  30593. Object.defineProperty(Material, "LightDirtyFlag", {
  30594. /**
  30595. * Returns the dirty light flag value.
  30596. */
  30597. get: function () {
  30598. return Material._LightDirtyFlag;
  30599. },
  30600. enumerable: true,
  30601. configurable: true
  30602. });
  30603. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30604. /**
  30605. * Returns the dirty fresnel flag value.
  30606. */
  30607. get: function () {
  30608. return Material._FresnelDirtyFlag;
  30609. },
  30610. enumerable: true,
  30611. configurable: true
  30612. });
  30613. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30614. /**
  30615. * Returns the dirty attributes flag value.
  30616. */
  30617. get: function () {
  30618. return Material._AttributesDirtyFlag;
  30619. },
  30620. enumerable: true,
  30621. configurable: true
  30622. });
  30623. Object.defineProperty(Material, "MiscDirtyFlag", {
  30624. /**
  30625. * Returns the dirty misc flag value.
  30626. */
  30627. get: function () {
  30628. return Material._MiscDirtyFlag;
  30629. },
  30630. enumerable: true,
  30631. configurable: true
  30632. });
  30633. Object.defineProperty(Material.prototype, "alpha", {
  30634. /**
  30635. * Gets the alpha value of the material.
  30636. */
  30637. get: function () {
  30638. return this._alpha;
  30639. },
  30640. /**
  30641. * Sets the alpha value of the material.
  30642. */
  30643. set: function (value) {
  30644. if (this._alpha === value) {
  30645. return;
  30646. }
  30647. this._alpha = value;
  30648. this.markAsDirty(Material.MiscDirtyFlag);
  30649. },
  30650. enumerable: true,
  30651. configurable: true
  30652. });
  30653. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30654. /**
  30655. * Gets the back-face culling state.
  30656. */
  30657. get: function () {
  30658. return this._backFaceCulling;
  30659. },
  30660. /**
  30661. * Sets the back-face culling state.
  30662. */
  30663. set: function (value) {
  30664. if (this._backFaceCulling === value) {
  30665. return;
  30666. }
  30667. this._backFaceCulling = value;
  30668. this.markAsDirty(Material.TextureDirtyFlag);
  30669. },
  30670. enumerable: true,
  30671. configurable: true
  30672. });
  30673. Object.defineProperty(Material.prototype, "onDispose", {
  30674. /**
  30675. * Called during a dispose event.
  30676. */
  30677. set: function (callback) {
  30678. if (this._onDisposeObserver) {
  30679. this.onDisposeObservable.remove(this._onDisposeObserver);
  30680. }
  30681. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30682. },
  30683. enumerable: true,
  30684. configurable: true
  30685. });
  30686. Object.defineProperty(Material.prototype, "onBind", {
  30687. /**
  30688. * Called during a bind event.
  30689. */
  30690. set: function (callback) {
  30691. if (this._onBindObserver) {
  30692. this.onBindObservable.remove(this._onBindObserver);
  30693. }
  30694. this._onBindObserver = this.onBindObservable.add(callback);
  30695. },
  30696. enumerable: true,
  30697. configurable: true
  30698. });
  30699. Object.defineProperty(Material.prototype, "alphaMode", {
  30700. /**
  30701. * Gets the value of the alpha mode.
  30702. */
  30703. get: function () {
  30704. return this._alphaMode;
  30705. },
  30706. /**
  30707. * Sets the value of the alpha mode.
  30708. */
  30709. set: function (value) {
  30710. if (this._alphaMode === value) {
  30711. return;
  30712. }
  30713. this._alphaMode = value;
  30714. this.markAsDirty(Material.TextureDirtyFlag);
  30715. },
  30716. enumerable: true,
  30717. configurable: true
  30718. });
  30719. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30720. /**
  30721. * Gets the depth pre-pass value.
  30722. */
  30723. get: function () {
  30724. return this._needDepthPrePass;
  30725. },
  30726. /**
  30727. * Sets the need depth pre-pass value.
  30728. */
  30729. set: function (value) {
  30730. if (this._needDepthPrePass === value) {
  30731. return;
  30732. }
  30733. this._needDepthPrePass = value;
  30734. if (this._needDepthPrePass) {
  30735. this.checkReadyOnEveryCall = true;
  30736. }
  30737. },
  30738. enumerable: true,
  30739. configurable: true
  30740. });
  30741. Object.defineProperty(Material.prototype, "fogEnabled", {
  30742. /**
  30743. * Gets the value of the fog enabled state.
  30744. */
  30745. get: function () {
  30746. return this._fogEnabled;
  30747. },
  30748. /**
  30749. * Sets the state for enabling fog.
  30750. */
  30751. set: function (value) {
  30752. if (this._fogEnabled === value) {
  30753. return;
  30754. }
  30755. this._fogEnabled = value;
  30756. this.markAsDirty(Material.MiscDirtyFlag);
  30757. },
  30758. enumerable: true,
  30759. configurable: true
  30760. });
  30761. Object.defineProperty(Material.prototype, "wireframe", {
  30762. /**
  30763. * Gets a value specifying if wireframe mode is enabled.
  30764. */
  30765. get: function () {
  30766. return this._fillMode === Material.WireFrameFillMode;
  30767. },
  30768. /**
  30769. * Sets the state of wireframe mode.
  30770. */
  30771. set: function (value) {
  30772. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30773. },
  30774. enumerable: true,
  30775. configurable: true
  30776. });
  30777. Object.defineProperty(Material.prototype, "pointsCloud", {
  30778. /**
  30779. * Gets the value specifying if point clouds are enabled.
  30780. */
  30781. get: function () {
  30782. return this._fillMode === Material.PointFillMode;
  30783. },
  30784. /**
  30785. * Sets the state of point cloud mode.
  30786. */
  30787. set: function (value) {
  30788. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30789. },
  30790. enumerable: true,
  30791. configurable: true
  30792. });
  30793. Object.defineProperty(Material.prototype, "fillMode", {
  30794. /**
  30795. * Gets the material fill mode.
  30796. */
  30797. get: function () {
  30798. return this._fillMode;
  30799. },
  30800. /**
  30801. * Sets the material fill mode.
  30802. */
  30803. set: function (value) {
  30804. if (this._fillMode === value) {
  30805. return;
  30806. }
  30807. this._fillMode = value;
  30808. this.markAsDirty(Material.MiscDirtyFlag);
  30809. },
  30810. enumerable: true,
  30811. configurable: true
  30812. });
  30813. /**
  30814. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30815. * subclasses should override adding information pertainent to themselves.
  30816. * @returns - String with material information.
  30817. */
  30818. Material.prototype.toString = function (fullDetails) {
  30819. var ret = "Name: " + this.name;
  30820. if (fullDetails) {
  30821. }
  30822. return ret;
  30823. };
  30824. /**
  30825. * Gets the class name of the material.
  30826. * @returns - String with the class name of the material.
  30827. */
  30828. Material.prototype.getClassName = function () {
  30829. return "Material";
  30830. };
  30831. Object.defineProperty(Material.prototype, "isFrozen", {
  30832. /**
  30833. * Specifies if updates for the material been locked.
  30834. */
  30835. get: function () {
  30836. return this.checkReadyOnlyOnce;
  30837. },
  30838. enumerable: true,
  30839. configurable: true
  30840. });
  30841. /**
  30842. * Locks updates for the material.
  30843. */
  30844. Material.prototype.freeze = function () {
  30845. this.checkReadyOnlyOnce = true;
  30846. };
  30847. /**
  30848. * Unlocks updates for the material.
  30849. */
  30850. Material.prototype.unfreeze = function () {
  30851. this.checkReadyOnlyOnce = false;
  30852. };
  30853. /**
  30854. * Specifies if the material is ready to be used.
  30855. * @param mesh - BJS mesh.
  30856. * @param useInstances - Specifies if instances should be used.
  30857. * @returns - Boolean indicating if the material is ready to be used.
  30858. */
  30859. Material.prototype.isReady = function (mesh, useInstances) {
  30860. return true;
  30861. };
  30862. /**
  30863. * Specifies that the submesh is ready to be used.
  30864. * @param mesh - BJS mesh.
  30865. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30866. * @param useInstances - Specifies that instances should be used.
  30867. * @returns - boolean indicating that the submesh is ready or not.
  30868. */
  30869. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30870. return false;
  30871. };
  30872. /**
  30873. * Returns the material effect.
  30874. * @returns - Nullable material effect.
  30875. */
  30876. Material.prototype.getEffect = function () {
  30877. return this._effect;
  30878. };
  30879. /**
  30880. * Returns the BJS scene.
  30881. * @returns - BJS Scene.
  30882. */
  30883. Material.prototype.getScene = function () {
  30884. return this._scene;
  30885. };
  30886. /**
  30887. * Specifies if the material will require alpha blending
  30888. * @returns - Boolean specifying if alpha blending is needed.
  30889. */
  30890. Material.prototype.needAlphaBlending = function () {
  30891. return (this.alpha < 1.0);
  30892. };
  30893. /**
  30894. * Specifies if the mesh will require alpha blending.
  30895. * @param mesh - BJS mesh.
  30896. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30897. */
  30898. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30899. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30900. };
  30901. /**
  30902. * Specifies if this material should be rendered in alpha test mode.
  30903. * @returns - Boolean specifying if an alpha test is needed.
  30904. */
  30905. Material.prototype.needAlphaTesting = function () {
  30906. return false;
  30907. };
  30908. /**
  30909. * Gets the texture used for the alpha test.
  30910. * @returns - Nullable alpha test texture.
  30911. */
  30912. Material.prototype.getAlphaTestTexture = function () {
  30913. return null;
  30914. };
  30915. /**
  30916. * Marks the material to indicate that it needs to be re-calculated.
  30917. */
  30918. Material.prototype.markDirty = function () {
  30919. this._wasPreviouslyReady = false;
  30920. };
  30921. Material.prototype._preBind = function (effect, overrideOrientation) {
  30922. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30923. var engine = this._scene.getEngine();
  30924. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30925. var reverse = orientation === Material.ClockWiseSideOrientation;
  30926. engine.enableEffect(effect ? effect : this._effect);
  30927. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30928. return reverse;
  30929. };
  30930. /**
  30931. * Binds the material to the mesh.
  30932. * @param world - World transformation matrix.
  30933. * @param mesh - Mesh to bind the material to.
  30934. */
  30935. Material.prototype.bind = function (world, mesh) {
  30936. };
  30937. /**
  30938. * Binds the submesh to the material.
  30939. * @param world - World transformation matrix.
  30940. * @param mesh - Mesh containing the submesh.
  30941. * @param subMesh - Submesh to bind the material to.
  30942. */
  30943. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30944. };
  30945. /**
  30946. * Binds the world matrix to the material.
  30947. * @param world - World transformation matrix.
  30948. */
  30949. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30950. };
  30951. /**
  30952. * Binds the scene's uniform buffer to the effect.
  30953. * @param effect - Effect to bind to the scene uniform buffer.
  30954. * @param sceneUbo - Scene uniform buffer.
  30955. */
  30956. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30957. sceneUbo.bindToEffect(effect, "Scene");
  30958. };
  30959. /**
  30960. * Binds the view matrix to the effect.
  30961. * @param effect - Effect to bind the view matrix to.
  30962. */
  30963. Material.prototype.bindView = function (effect) {
  30964. if (!this._useUBO) {
  30965. effect.setMatrix("view", this.getScene().getViewMatrix());
  30966. }
  30967. else {
  30968. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30969. }
  30970. };
  30971. /**
  30972. * Binds the view projection matrix to the effect.
  30973. * @param effect - Effect to bind the view projection matrix to.
  30974. */
  30975. Material.prototype.bindViewProjection = function (effect) {
  30976. if (!this._useUBO) {
  30977. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30978. }
  30979. else {
  30980. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30981. }
  30982. };
  30983. /**
  30984. * Specifies if material alpha testing should be turned on for the mesh.
  30985. * @param mesh - BJS mesh.
  30986. */
  30987. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30988. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30989. };
  30990. /**
  30991. * Processes to execute after binding the material to a mesh.
  30992. * @param mesh - BJS mesh.
  30993. */
  30994. Material.prototype._afterBind = function (mesh) {
  30995. this._scene._cachedMaterial = this;
  30996. if (mesh) {
  30997. this._scene._cachedVisibility = mesh.visibility;
  30998. }
  30999. else {
  31000. this._scene._cachedVisibility = 1;
  31001. }
  31002. if (mesh) {
  31003. this.onBindObservable.notifyObservers(mesh);
  31004. }
  31005. if (this.disableDepthWrite) {
  31006. var engine = this._scene.getEngine();
  31007. this._cachedDepthWriteState = engine.getDepthWrite();
  31008. engine.setDepthWrite(false);
  31009. }
  31010. };
  31011. /**
  31012. * Unbinds the material from the mesh.
  31013. */
  31014. Material.prototype.unbind = function () {
  31015. this.onUnBindObservable.notifyObservers(this);
  31016. if (this.disableDepthWrite) {
  31017. var engine = this._scene.getEngine();
  31018. engine.setDepthWrite(this._cachedDepthWriteState);
  31019. }
  31020. };
  31021. /**
  31022. * Gets the active textures from the material.
  31023. * @returns - Array of textures.
  31024. */
  31025. Material.prototype.getActiveTextures = function () {
  31026. return [];
  31027. };
  31028. /**
  31029. * Specifies if the material uses a texture.
  31030. * @param texture - Texture to check against the material.
  31031. * @returns - Boolean specifying if the material uses the texture.
  31032. */
  31033. Material.prototype.hasTexture = function (texture) {
  31034. return false;
  31035. };
  31036. /**
  31037. * Makes a duplicate of the material, and gives it a new name.
  31038. * @param name - Name to call the duplicated material.
  31039. * @returns - Nullable cloned material
  31040. */
  31041. Material.prototype.clone = function (name) {
  31042. return null;
  31043. };
  31044. /**
  31045. * Gets the meshes bound to the material.
  31046. * @returns - Array of meshes bound to the material.
  31047. */
  31048. Material.prototype.getBindedMeshes = function () {
  31049. var result = new Array();
  31050. for (var index = 0; index < this._scene.meshes.length; index++) {
  31051. var mesh = this._scene.meshes[index];
  31052. if (mesh.material === this) {
  31053. result.push(mesh);
  31054. }
  31055. }
  31056. return result;
  31057. };
  31058. /**
  31059. * Force shader compilation
  31060. * @param mesh - BJS mesh.
  31061. * @param onCompiled - function to execute once the material is compiled.
  31062. * @param options - options to pass to this function.
  31063. */
  31064. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31065. var _this = this;
  31066. var localOptions = __assign({ clipPlane: false }, options);
  31067. var subMesh = new BABYLON.BaseSubMesh();
  31068. var scene = this.getScene();
  31069. var checkReady = function () {
  31070. if (!_this._scene || !_this._scene.getEngine()) {
  31071. return;
  31072. }
  31073. if (subMesh._materialDefines) {
  31074. subMesh._materialDefines._renderId = -1;
  31075. }
  31076. var clipPlaneState = scene.clipPlane;
  31077. if (localOptions.clipPlane) {
  31078. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31079. }
  31080. if (_this.storeEffectOnSubMeshes) {
  31081. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31082. if (onCompiled) {
  31083. onCompiled(_this);
  31084. }
  31085. }
  31086. else {
  31087. setTimeout(checkReady, 16);
  31088. }
  31089. }
  31090. else {
  31091. if (_this.isReady(mesh)) {
  31092. if (onCompiled) {
  31093. onCompiled(_this);
  31094. }
  31095. }
  31096. else {
  31097. setTimeout(checkReady, 16);
  31098. }
  31099. }
  31100. if (localOptions.clipPlane) {
  31101. scene.clipPlane = clipPlaneState;
  31102. }
  31103. };
  31104. checkReady();
  31105. };
  31106. /**
  31107. * Force shader compilation.
  31108. * @param mesh The mesh that will use this material
  31109. * @param options Additional options for compiling the shaders
  31110. * @returns A promise that resolves when the compilation completes
  31111. */
  31112. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31113. var _this = this;
  31114. return new Promise(function (resolve) {
  31115. _this.forceCompilation(mesh, function () {
  31116. resolve();
  31117. }, options);
  31118. });
  31119. };
  31120. /**
  31121. * Marks a define in the material to indicate that it needs to be re-computed.
  31122. * @param flag - Material define flag.
  31123. */
  31124. Material.prototype.markAsDirty = function (flag) {
  31125. if (flag & Material.TextureDirtyFlag) {
  31126. this._markAllSubMeshesAsTexturesDirty();
  31127. }
  31128. if (flag & Material.LightDirtyFlag) {
  31129. this._markAllSubMeshesAsLightsDirty();
  31130. }
  31131. if (flag & Material.FresnelDirtyFlag) {
  31132. this._markAllSubMeshesAsFresnelDirty();
  31133. }
  31134. if (flag & Material.AttributesDirtyFlag) {
  31135. this._markAllSubMeshesAsAttributesDirty();
  31136. }
  31137. if (flag & Material.MiscDirtyFlag) {
  31138. this._markAllSubMeshesAsMiscDirty();
  31139. }
  31140. this.getScene().resetCachedMaterial();
  31141. };
  31142. /**
  31143. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31144. * @param func - function which checks material defines against the submeshes.
  31145. */
  31146. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31147. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31148. var mesh = _a[_i];
  31149. if (!mesh.subMeshes) {
  31150. continue;
  31151. }
  31152. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31153. var subMesh = _c[_b];
  31154. if (subMesh.getMaterial() !== this) {
  31155. continue;
  31156. }
  31157. if (!subMesh._materialDefines) {
  31158. continue;
  31159. }
  31160. func(subMesh._materialDefines);
  31161. }
  31162. }
  31163. };
  31164. /**
  31165. * Indicates that image processing needs to be re-calculated for all submeshes.
  31166. */
  31167. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31168. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31169. };
  31170. /**
  31171. * Indicates that textures need to be re-calculated for all submeshes.
  31172. */
  31173. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31174. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31175. };
  31176. /**
  31177. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31178. */
  31179. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31180. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31181. };
  31182. /**
  31183. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31184. */
  31185. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31186. this._markAllSubMeshesAsDirty(function (defines) {
  31187. defines.markAsFresnelDirty();
  31188. defines.markAsMiscDirty();
  31189. });
  31190. };
  31191. /**
  31192. * Indicates that lights need to be re-calculated for all submeshes.
  31193. */
  31194. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31195. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31196. };
  31197. /**
  31198. * Indicates that attributes need to be re-calculated for all submeshes.
  31199. */
  31200. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31201. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31202. };
  31203. /**
  31204. * Indicates that misc needs to be re-calculated for all submeshes.
  31205. */
  31206. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31207. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31208. };
  31209. /**
  31210. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31211. */
  31212. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31213. this._markAllSubMeshesAsDirty(function (defines) {
  31214. defines.markAsTexturesDirty();
  31215. defines.markAsMiscDirty();
  31216. });
  31217. };
  31218. /**
  31219. * Disposes the material.
  31220. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31221. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31222. */
  31223. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31224. // Animations
  31225. this.getScene().stopAnimation(this);
  31226. // Remove from scene
  31227. var index = this._scene.materials.indexOf(this);
  31228. if (index >= 0) {
  31229. this._scene.materials.splice(index, 1);
  31230. }
  31231. // Remove from meshes
  31232. for (index = 0; index < this._scene.meshes.length; index++) {
  31233. var mesh = this._scene.meshes[index];
  31234. if (mesh.material === this) {
  31235. mesh.material = null;
  31236. if (mesh.geometry) {
  31237. var geometry = (mesh.geometry);
  31238. if (this.storeEffectOnSubMeshes) {
  31239. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31240. var subMesh = _a[_i];
  31241. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31242. if (forceDisposeEffect && subMesh._materialEffect) {
  31243. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31244. }
  31245. }
  31246. }
  31247. else {
  31248. geometry._releaseVertexArrayObject(this._effect);
  31249. }
  31250. }
  31251. }
  31252. }
  31253. this._uniformBuffer.dispose();
  31254. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31255. if (forceDisposeEffect && this._effect) {
  31256. if (!this.storeEffectOnSubMeshes) {
  31257. this._scene.getEngine()._releaseEffect(this._effect);
  31258. }
  31259. this._effect = null;
  31260. }
  31261. // Callback
  31262. this.onDisposeObservable.notifyObservers(this);
  31263. this.onDisposeObservable.clear();
  31264. this.onBindObservable.clear();
  31265. this.onUnBindObservable.clear();
  31266. };
  31267. /**
  31268. * Serializes this material.
  31269. * @returns - serialized material object.
  31270. */
  31271. Material.prototype.serialize = function () {
  31272. return BABYLON.SerializationHelper.Serialize(this);
  31273. };
  31274. /**
  31275. * Creates a MultiMaterial from parse MultiMaterial data.
  31276. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31277. * @param scene - BJS scene.
  31278. * @returns - MultiMaterial.
  31279. */
  31280. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31281. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31282. multiMaterial.id = parsedMultiMaterial.id;
  31283. if (BABYLON.Tags) {
  31284. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31285. }
  31286. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31287. var subMatId = parsedMultiMaterial.materials[matIndex];
  31288. if (subMatId) {
  31289. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31290. }
  31291. else {
  31292. multiMaterial.subMaterials.push(null);
  31293. }
  31294. }
  31295. return multiMaterial;
  31296. };
  31297. /**
  31298. * Creates a material from parsed material data.
  31299. * @param parsedMaterial - Parsed material data.
  31300. * @param scene - BJS scene.
  31301. * @param rootUrl - Root URL containing the material information.
  31302. * @returns - Parsed material.
  31303. */
  31304. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31305. if (!parsedMaterial.customType) {
  31306. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31307. }
  31308. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31309. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31310. if (!BABYLON.LegacyPBRMaterial) {
  31311. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31312. return;
  31313. }
  31314. }
  31315. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31316. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31317. ;
  31318. };
  31319. // Triangle views
  31320. Material._TriangleFillMode = 0;
  31321. Material._WireFrameFillMode = 1;
  31322. Material._PointFillMode = 2;
  31323. // Draw modes
  31324. Material._PointListDrawMode = 3;
  31325. Material._LineListDrawMode = 4;
  31326. Material._LineLoopDrawMode = 5;
  31327. Material._LineStripDrawMode = 6;
  31328. Material._TriangleStripDrawMode = 7;
  31329. Material._TriangleFanDrawMode = 8;
  31330. /**
  31331. * Stores the clock-wise side orientation.
  31332. */
  31333. Material._ClockWiseSideOrientation = 0;
  31334. /**
  31335. * Stores the counter clock-wise side orientation.
  31336. */
  31337. Material._CounterClockWiseSideOrientation = 1;
  31338. /**
  31339. * The dirty texture flag value.
  31340. */
  31341. Material._TextureDirtyFlag = 1;
  31342. /**
  31343. * The dirty light flag value.
  31344. */
  31345. Material._LightDirtyFlag = 2;
  31346. /**
  31347. * The dirty fresnel flag value.
  31348. */
  31349. Material._FresnelDirtyFlag = 4;
  31350. /**
  31351. * The dirty attribute flag value.
  31352. */
  31353. Material._AttributesDirtyFlag = 8;
  31354. /**
  31355. * The dirty misc flag value.
  31356. */
  31357. Material._MiscDirtyFlag = 16;
  31358. __decorate([
  31359. BABYLON.serialize()
  31360. ], Material.prototype, "id", void 0);
  31361. __decorate([
  31362. BABYLON.serialize()
  31363. ], Material.prototype, "name", void 0);
  31364. __decorate([
  31365. BABYLON.serialize()
  31366. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31367. __decorate([
  31368. BABYLON.serialize()
  31369. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31370. __decorate([
  31371. BABYLON.serialize()
  31372. ], Material.prototype, "state", void 0);
  31373. __decorate([
  31374. BABYLON.serialize("alpha")
  31375. ], Material.prototype, "_alpha", void 0);
  31376. __decorate([
  31377. BABYLON.serialize("backFaceCulling")
  31378. ], Material.prototype, "_backFaceCulling", void 0);
  31379. __decorate([
  31380. BABYLON.serialize()
  31381. ], Material.prototype, "sideOrientation", void 0);
  31382. __decorate([
  31383. BABYLON.serialize("alphaMode")
  31384. ], Material.prototype, "_alphaMode", void 0);
  31385. __decorate([
  31386. BABYLON.serialize()
  31387. ], Material.prototype, "_needDepthPrePass", void 0);
  31388. __decorate([
  31389. BABYLON.serialize()
  31390. ], Material.prototype, "disableDepthWrite", void 0);
  31391. __decorate([
  31392. BABYLON.serialize()
  31393. ], Material.prototype, "forceDepthWrite", void 0);
  31394. __decorate([
  31395. BABYLON.serialize()
  31396. ], Material.prototype, "separateCullingPass", void 0);
  31397. __decorate([
  31398. BABYLON.serialize("fogEnabled")
  31399. ], Material.prototype, "_fogEnabled", void 0);
  31400. __decorate([
  31401. BABYLON.serialize()
  31402. ], Material.prototype, "pointSize", void 0);
  31403. __decorate([
  31404. BABYLON.serialize()
  31405. ], Material.prototype, "zOffset", void 0);
  31406. __decorate([
  31407. BABYLON.serialize()
  31408. ], Material.prototype, "wireframe", null);
  31409. __decorate([
  31410. BABYLON.serialize()
  31411. ], Material.prototype, "pointsCloud", null);
  31412. __decorate([
  31413. BABYLON.serialize()
  31414. ], Material.prototype, "fillMode", null);
  31415. return Material;
  31416. }());
  31417. BABYLON.Material = Material;
  31418. })(BABYLON || (BABYLON = {}));
  31419. //# sourceMappingURL=babylon.material.js.map
  31420. var BABYLON;
  31421. (function (BABYLON) {
  31422. var UniformBuffer = /** @class */ (function () {
  31423. /**
  31424. * Uniform buffer objects.
  31425. *
  31426. * Handles blocks of uniform on the GPU.
  31427. *
  31428. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31429. *
  31430. * For more information, please refer to :
  31431. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31432. */
  31433. function UniformBuffer(engine, data, dynamic) {
  31434. this._engine = engine;
  31435. this._noUBO = !engine.supportsUniformBuffers;
  31436. this._dynamic = dynamic;
  31437. this._data = data || [];
  31438. this._uniformLocations = {};
  31439. this._uniformSizes = {};
  31440. this._uniformLocationPointer = 0;
  31441. this._needSync = false;
  31442. if (this._noUBO) {
  31443. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31444. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31445. this.updateFloat = this._updateFloatForEffect;
  31446. this.updateFloat2 = this._updateFloat2ForEffect;
  31447. this.updateFloat3 = this._updateFloat3ForEffect;
  31448. this.updateFloat4 = this._updateFloat4ForEffect;
  31449. this.updateMatrix = this._updateMatrixForEffect;
  31450. this.updateVector3 = this._updateVector3ForEffect;
  31451. this.updateVector4 = this._updateVector4ForEffect;
  31452. this.updateColor3 = this._updateColor3ForEffect;
  31453. this.updateColor4 = this._updateColor4ForEffect;
  31454. }
  31455. else {
  31456. this._engine._uniformBuffers.push(this);
  31457. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31458. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31459. this.updateFloat = this._updateFloatForUniform;
  31460. this.updateFloat2 = this._updateFloat2ForUniform;
  31461. this.updateFloat3 = this._updateFloat3ForUniform;
  31462. this.updateFloat4 = this._updateFloat4ForUniform;
  31463. this.updateMatrix = this._updateMatrixForUniform;
  31464. this.updateVector3 = this._updateVector3ForUniform;
  31465. this.updateVector4 = this._updateVector4ForUniform;
  31466. this.updateColor3 = this._updateColor3ForUniform;
  31467. this.updateColor4 = this._updateColor4ForUniform;
  31468. }
  31469. }
  31470. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31471. // Properties
  31472. /**
  31473. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31474. * or just falling back on setUniformXXX calls.
  31475. */
  31476. get: function () {
  31477. return !this._noUBO;
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31483. /**
  31484. * Indicates if the WebGL underlying uniform buffer is in sync
  31485. * with the javascript cache data.
  31486. */
  31487. get: function () {
  31488. return !this._needSync;
  31489. },
  31490. enumerable: true,
  31491. configurable: true
  31492. });
  31493. /**
  31494. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31495. * Also, a dynamic UniformBuffer will disable cache verification and always
  31496. * update the underlying WebGL uniform buffer to the GPU.
  31497. */
  31498. UniformBuffer.prototype.isDynamic = function () {
  31499. return this._dynamic !== undefined;
  31500. };
  31501. /**
  31502. * The data cache on JS side.
  31503. */
  31504. UniformBuffer.prototype.getData = function () {
  31505. return this._bufferData;
  31506. };
  31507. /**
  31508. * The underlying WebGL Uniform buffer.
  31509. */
  31510. UniformBuffer.prototype.getBuffer = function () {
  31511. return this._buffer;
  31512. };
  31513. /**
  31514. * std140 layout specifies how to align data within an UBO structure.
  31515. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31516. * for specs.
  31517. */
  31518. UniformBuffer.prototype._fillAlignment = function (size) {
  31519. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31520. // and 4x4 matrices
  31521. // TODO : change if other types are used
  31522. var alignment;
  31523. if (size <= 2) {
  31524. alignment = size;
  31525. }
  31526. else {
  31527. alignment = 4;
  31528. }
  31529. if ((this._uniformLocationPointer % alignment) !== 0) {
  31530. var oldPointer = this._uniformLocationPointer;
  31531. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31532. var diff = this._uniformLocationPointer - oldPointer;
  31533. for (var i = 0; i < diff; i++) {
  31534. this._data.push(0);
  31535. }
  31536. }
  31537. };
  31538. /**
  31539. * Adds an uniform in the buffer.
  31540. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31541. * for the layout to be correct !
  31542. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31543. * @param {number|number[]} size Data size, or data directly.
  31544. */
  31545. UniformBuffer.prototype.addUniform = function (name, size) {
  31546. if (this._noUBO) {
  31547. return;
  31548. }
  31549. if (this._uniformLocations[name] !== undefined) {
  31550. // Already existing uniform
  31551. return;
  31552. }
  31553. // This function must be called in the order of the shader layout !
  31554. // size can be the size of the uniform, or data directly
  31555. var data;
  31556. if (size instanceof Array) {
  31557. data = size;
  31558. size = data.length;
  31559. }
  31560. else {
  31561. size = size;
  31562. data = [];
  31563. // Fill with zeros
  31564. for (var i = 0; i < size; i++) {
  31565. data.push(0);
  31566. }
  31567. }
  31568. this._fillAlignment(size);
  31569. this._uniformSizes[name] = size;
  31570. this._uniformLocations[name] = this._uniformLocationPointer;
  31571. this._uniformLocationPointer += size;
  31572. for (var i = 0; i < size; i++) {
  31573. this._data.push(data[i]);
  31574. }
  31575. this._needSync = true;
  31576. };
  31577. /**
  31578. * Wrapper for addUniform.
  31579. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31580. * @param {Matrix} mat A 4x4 matrix.
  31581. */
  31582. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31583. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31584. };
  31585. /**
  31586. * Wrapper for addUniform.
  31587. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31588. * @param {number} x
  31589. * @param {number} y
  31590. */
  31591. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31592. var temp = [x, y];
  31593. this.addUniform(name, temp);
  31594. };
  31595. /**
  31596. * Wrapper for addUniform.
  31597. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31598. * @param {number} x
  31599. * @param {number} y
  31600. * @param {number} z
  31601. */
  31602. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31603. var temp = [x, y, z];
  31604. this.addUniform(name, temp);
  31605. };
  31606. /**
  31607. * Wrapper for addUniform.
  31608. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31609. * @param {Color3} color
  31610. */
  31611. UniformBuffer.prototype.addColor3 = function (name, color) {
  31612. var temp = new Array();
  31613. color.toArray(temp);
  31614. this.addUniform(name, temp);
  31615. };
  31616. /**
  31617. * Wrapper for addUniform.
  31618. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31619. * @param {Color3} color
  31620. * @param {number} alpha
  31621. */
  31622. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31623. var temp = new Array();
  31624. color.toArray(temp);
  31625. temp.push(alpha);
  31626. this.addUniform(name, temp);
  31627. };
  31628. /**
  31629. * Wrapper for addUniform.
  31630. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31631. * @param {Vector3} vector
  31632. */
  31633. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31634. var temp = new Array();
  31635. vector.toArray(temp);
  31636. this.addUniform(name, temp);
  31637. };
  31638. /**
  31639. * Wrapper for addUniform.
  31640. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31641. */
  31642. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31643. this.addUniform(name, 12);
  31644. };
  31645. /**
  31646. * Wrapper for addUniform.
  31647. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31648. */
  31649. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31650. this.addUniform(name, 8);
  31651. };
  31652. /**
  31653. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31654. */
  31655. UniformBuffer.prototype.create = function () {
  31656. if (this._noUBO) {
  31657. return;
  31658. }
  31659. if (this._buffer) {
  31660. return; // nothing to do
  31661. }
  31662. // See spec, alignment must be filled as a vec4
  31663. this._fillAlignment(4);
  31664. this._bufferData = new Float32Array(this._data);
  31665. this._rebuild();
  31666. this._needSync = true;
  31667. };
  31668. UniformBuffer.prototype._rebuild = function () {
  31669. if (this._noUBO) {
  31670. return;
  31671. }
  31672. if (this._dynamic) {
  31673. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31674. }
  31675. else {
  31676. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31677. }
  31678. };
  31679. /**
  31680. * Updates the WebGL Uniform Buffer on the GPU.
  31681. * If the `dynamic` flag is set to true, no cache comparison is done.
  31682. * Otherwise, the buffer will be updated only if the cache differs.
  31683. */
  31684. UniformBuffer.prototype.update = function () {
  31685. if (!this._buffer) {
  31686. this.create();
  31687. return;
  31688. }
  31689. if (!this._dynamic && !this._needSync) {
  31690. return;
  31691. }
  31692. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31693. this._needSync = false;
  31694. };
  31695. /**
  31696. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31697. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31698. * @param {number[]|Float32Array} data Flattened data
  31699. * @param {number} size Size of the data.
  31700. */
  31701. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31702. var location = this._uniformLocations[uniformName];
  31703. if (location === undefined) {
  31704. if (this._buffer) {
  31705. // Cannot add an uniform if the buffer is already created
  31706. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31707. return;
  31708. }
  31709. this.addUniform(uniformName, size);
  31710. location = this._uniformLocations[uniformName];
  31711. }
  31712. if (!this._buffer) {
  31713. this.create();
  31714. }
  31715. if (!this._dynamic) {
  31716. // Cache for static uniform buffers
  31717. var changed = false;
  31718. for (var i = 0; i < size; i++) {
  31719. if (this._bufferData[location + i] !== data[i]) {
  31720. changed = true;
  31721. this._bufferData[location + i] = data[i];
  31722. }
  31723. }
  31724. this._needSync = this._needSync || changed;
  31725. }
  31726. else {
  31727. // No cache for dynamic
  31728. for (var i = 0; i < size; i++) {
  31729. this._bufferData[location + i] = data[i];
  31730. }
  31731. }
  31732. };
  31733. // Update methods
  31734. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31735. // To match std140, matrix must be realigned
  31736. for (var i = 0; i < 3; i++) {
  31737. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31738. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31739. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31740. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31741. }
  31742. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31743. };
  31744. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31745. this._currentEffect.setMatrix3x3(name, matrix);
  31746. };
  31747. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31748. this._currentEffect.setMatrix2x2(name, matrix);
  31749. };
  31750. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31751. // To match std140, matrix must be realigned
  31752. for (var i = 0; i < 2; i++) {
  31753. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31754. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31755. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31756. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31757. }
  31758. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31759. };
  31760. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31761. this._currentEffect.setFloat(name, x);
  31762. };
  31763. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31764. UniformBuffer._tempBuffer[0] = x;
  31765. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31766. };
  31767. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31768. if (suffix === void 0) { suffix = ""; }
  31769. this._currentEffect.setFloat2(name + suffix, x, y);
  31770. };
  31771. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31772. if (suffix === void 0) { suffix = ""; }
  31773. UniformBuffer._tempBuffer[0] = x;
  31774. UniformBuffer._tempBuffer[1] = y;
  31775. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31776. };
  31777. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31778. if (suffix === void 0) { suffix = ""; }
  31779. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31780. };
  31781. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31782. if (suffix === void 0) { suffix = ""; }
  31783. UniformBuffer._tempBuffer[0] = x;
  31784. UniformBuffer._tempBuffer[1] = y;
  31785. UniformBuffer._tempBuffer[2] = z;
  31786. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31787. };
  31788. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31789. if (suffix === void 0) { suffix = ""; }
  31790. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31791. };
  31792. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31793. if (suffix === void 0) { suffix = ""; }
  31794. UniformBuffer._tempBuffer[0] = x;
  31795. UniformBuffer._tempBuffer[1] = y;
  31796. UniformBuffer._tempBuffer[2] = z;
  31797. UniformBuffer._tempBuffer[3] = w;
  31798. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31799. };
  31800. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31801. this._currentEffect.setMatrix(name, mat);
  31802. };
  31803. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31804. this.updateUniform(name, mat.toArray(), 16);
  31805. };
  31806. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31807. this._currentEffect.setVector3(name, vector);
  31808. };
  31809. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31810. vector.toArray(UniformBuffer._tempBuffer);
  31811. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31812. };
  31813. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31814. this._currentEffect.setVector4(name, vector);
  31815. };
  31816. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31817. vector.toArray(UniformBuffer._tempBuffer);
  31818. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31819. };
  31820. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31821. if (suffix === void 0) { suffix = ""; }
  31822. this._currentEffect.setColor3(name + suffix, color);
  31823. };
  31824. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31825. if (suffix === void 0) { suffix = ""; }
  31826. color.toArray(UniformBuffer._tempBuffer);
  31827. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31828. };
  31829. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31830. if (suffix === void 0) { suffix = ""; }
  31831. this._currentEffect.setColor4(name + suffix, color, alpha);
  31832. };
  31833. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31834. if (suffix === void 0) { suffix = ""; }
  31835. color.toArray(UniformBuffer._tempBuffer);
  31836. UniformBuffer._tempBuffer[3] = alpha;
  31837. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31838. };
  31839. /**
  31840. * Sets a sampler uniform on the effect.
  31841. * @param {string} name Name of the sampler.
  31842. * @param {Texture} texture
  31843. */
  31844. UniformBuffer.prototype.setTexture = function (name, texture) {
  31845. this._currentEffect.setTexture(name, texture);
  31846. };
  31847. /**
  31848. * Directly updates the value of the uniform in the cache AND on the GPU.
  31849. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31850. * @param {number[]|Float32Array} data Flattened data
  31851. */
  31852. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31853. this.updateUniform(uniformName, data, data.length);
  31854. this.update();
  31855. };
  31856. /**
  31857. * Binds this uniform buffer to an effect.
  31858. * @param {Effect} effect
  31859. * @param {string} name Name of the uniform block in the shader.
  31860. */
  31861. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31862. this._currentEffect = effect;
  31863. if (this._noUBO || !this._buffer) {
  31864. return;
  31865. }
  31866. effect.bindUniformBuffer(this._buffer, name);
  31867. };
  31868. /**
  31869. * Disposes the uniform buffer.
  31870. */
  31871. UniformBuffer.prototype.dispose = function () {
  31872. if (this._noUBO) {
  31873. return;
  31874. }
  31875. var index = this._engine._uniformBuffers.indexOf(this);
  31876. if (index !== -1) {
  31877. this._engine._uniformBuffers.splice(index, 1);
  31878. }
  31879. if (!this._buffer) {
  31880. return;
  31881. }
  31882. if (this._engine._releaseBuffer(this._buffer)) {
  31883. this._buffer = null;
  31884. }
  31885. };
  31886. // Pool for avoiding memory leaks
  31887. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31888. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31889. return UniformBuffer;
  31890. }());
  31891. BABYLON.UniformBuffer = UniformBuffer;
  31892. })(BABYLON || (BABYLON = {}));
  31893. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31894. var BABYLON;
  31895. (function (BABYLON) {
  31896. var VertexData = /** @class */ (function () {
  31897. function VertexData() {
  31898. }
  31899. VertexData.prototype.set = function (data, kind) {
  31900. switch (kind) {
  31901. case BABYLON.VertexBuffer.PositionKind:
  31902. this.positions = data;
  31903. break;
  31904. case BABYLON.VertexBuffer.NormalKind:
  31905. this.normals = data;
  31906. break;
  31907. case BABYLON.VertexBuffer.TangentKind:
  31908. this.tangents = data;
  31909. break;
  31910. case BABYLON.VertexBuffer.UVKind:
  31911. this.uvs = data;
  31912. break;
  31913. case BABYLON.VertexBuffer.UV2Kind:
  31914. this.uvs2 = data;
  31915. break;
  31916. case BABYLON.VertexBuffer.UV3Kind:
  31917. this.uvs3 = data;
  31918. break;
  31919. case BABYLON.VertexBuffer.UV4Kind:
  31920. this.uvs4 = data;
  31921. break;
  31922. case BABYLON.VertexBuffer.UV5Kind:
  31923. this.uvs5 = data;
  31924. break;
  31925. case BABYLON.VertexBuffer.UV6Kind:
  31926. this.uvs6 = data;
  31927. break;
  31928. case BABYLON.VertexBuffer.ColorKind:
  31929. this.colors = data;
  31930. break;
  31931. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31932. this.matricesIndices = data;
  31933. break;
  31934. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31935. this.matricesWeights = data;
  31936. break;
  31937. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31938. this.matricesIndicesExtra = data;
  31939. break;
  31940. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31941. this.matricesWeightsExtra = data;
  31942. break;
  31943. }
  31944. };
  31945. /**
  31946. * Associates the vertexData to the passed Mesh.
  31947. * Sets it as updatable or not (default `false`).
  31948. * Returns the VertexData.
  31949. */
  31950. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31951. this._applyTo(mesh, updatable);
  31952. return this;
  31953. };
  31954. /**
  31955. * Associates the vertexData to the passed Geometry.
  31956. * Sets it as updatable or not (default `false`).
  31957. * Returns the VertexData.
  31958. */
  31959. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31960. this._applyTo(geometry, updatable);
  31961. return this;
  31962. };
  31963. /**
  31964. * Updates the associated mesh.
  31965. * Returns the VertexData.
  31966. */
  31967. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31968. this._update(mesh);
  31969. return this;
  31970. };
  31971. /**
  31972. * Updates the associated geometry.
  31973. * Returns the VertexData.
  31974. */
  31975. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31976. this._update(geometry);
  31977. return this;
  31978. };
  31979. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31980. if (updatable === void 0) { updatable = false; }
  31981. if (this.positions) {
  31982. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31983. }
  31984. if (this.normals) {
  31985. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31986. }
  31987. if (this.tangents) {
  31988. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31989. }
  31990. if (this.uvs) {
  31991. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31992. }
  31993. if (this.uvs2) {
  31994. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31995. }
  31996. if (this.uvs3) {
  31997. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31998. }
  31999. if (this.uvs4) {
  32000. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32001. }
  32002. if (this.uvs5) {
  32003. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32004. }
  32005. if (this.uvs6) {
  32006. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32007. }
  32008. if (this.colors) {
  32009. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32010. }
  32011. if (this.matricesIndices) {
  32012. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32013. }
  32014. if (this.matricesWeights) {
  32015. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32016. }
  32017. if (this.matricesIndicesExtra) {
  32018. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32019. }
  32020. if (this.matricesWeightsExtra) {
  32021. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32022. }
  32023. if (this.indices) {
  32024. meshOrGeometry.setIndices(this.indices, null, updatable);
  32025. }
  32026. return this;
  32027. };
  32028. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32029. if (this.positions) {
  32030. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32031. }
  32032. if (this.normals) {
  32033. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32034. }
  32035. if (this.tangents) {
  32036. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32037. }
  32038. if (this.uvs) {
  32039. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32040. }
  32041. if (this.uvs2) {
  32042. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32043. }
  32044. if (this.uvs3) {
  32045. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32046. }
  32047. if (this.uvs4) {
  32048. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32049. }
  32050. if (this.uvs5) {
  32051. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32052. }
  32053. if (this.uvs6) {
  32054. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32055. }
  32056. if (this.colors) {
  32057. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32058. }
  32059. if (this.matricesIndices) {
  32060. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32061. }
  32062. if (this.matricesWeights) {
  32063. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32064. }
  32065. if (this.matricesIndicesExtra) {
  32066. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32067. }
  32068. if (this.matricesWeightsExtra) {
  32069. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32070. }
  32071. if (this.indices) {
  32072. meshOrGeometry.setIndices(this.indices, null);
  32073. }
  32074. return this;
  32075. };
  32076. /**
  32077. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32078. * Returns the VertexData.
  32079. */
  32080. VertexData.prototype.transform = function (matrix) {
  32081. var transformed = BABYLON.Vector3.Zero();
  32082. var index;
  32083. if (this.positions) {
  32084. var position = BABYLON.Vector3.Zero();
  32085. for (index = 0; index < this.positions.length; index += 3) {
  32086. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32087. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32088. this.positions[index] = transformed.x;
  32089. this.positions[index + 1] = transformed.y;
  32090. this.positions[index + 2] = transformed.z;
  32091. }
  32092. }
  32093. if (this.normals) {
  32094. var normal = BABYLON.Vector3.Zero();
  32095. for (index = 0; index < this.normals.length; index += 3) {
  32096. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32097. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32098. this.normals[index] = transformed.x;
  32099. this.normals[index + 1] = transformed.y;
  32100. this.normals[index + 2] = transformed.z;
  32101. }
  32102. }
  32103. if (this.tangents) {
  32104. var tangent = BABYLON.Vector4.Zero();
  32105. var tangentTransformed = BABYLON.Vector4.Zero();
  32106. for (index = 0; index < this.tangents.length; index += 4) {
  32107. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32108. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32109. this.tangents[index] = tangentTransformed.x;
  32110. this.tangents[index + 1] = tangentTransformed.y;
  32111. this.tangents[index + 2] = tangentTransformed.z;
  32112. this.tangents[index + 3] = tangentTransformed.w;
  32113. }
  32114. }
  32115. return this;
  32116. };
  32117. /**
  32118. * Merges the passed VertexData into the current one.
  32119. * Returns the modified VertexData.
  32120. */
  32121. VertexData.prototype.merge = function (other) {
  32122. this._validate();
  32123. other._validate();
  32124. if (!this.normals !== !other.normals ||
  32125. !this.tangents !== !other.tangents ||
  32126. !this.uvs !== !other.uvs ||
  32127. !this.uvs2 !== !other.uvs2 ||
  32128. !this.uvs3 !== !other.uvs3 ||
  32129. !this.uvs4 !== !other.uvs4 ||
  32130. !this.uvs5 !== !other.uvs5 ||
  32131. !this.uvs6 !== !other.uvs6 ||
  32132. !this.colors !== !other.colors ||
  32133. !this.matricesIndices !== !other.matricesIndices ||
  32134. !this.matricesWeights !== !other.matricesWeights ||
  32135. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32136. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32137. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32138. }
  32139. if (other.indices) {
  32140. if (!this.indices) {
  32141. this.indices = [];
  32142. }
  32143. var offset = this.positions ? this.positions.length / 3 : 0;
  32144. for (var index = 0; index < other.indices.length; index++) {
  32145. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32146. this.indices.push(other.indices[index] + offset);
  32147. }
  32148. }
  32149. this.positions = this._mergeElement(this.positions, other.positions);
  32150. this.normals = this._mergeElement(this.normals, other.normals);
  32151. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32152. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32153. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32154. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32155. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32156. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32157. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32158. this.colors = this._mergeElement(this.colors, other.colors);
  32159. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32160. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32161. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32162. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32163. return this;
  32164. };
  32165. VertexData.prototype._mergeElement = function (source, other) {
  32166. if (!source) {
  32167. return other;
  32168. }
  32169. if (!other) {
  32170. return source;
  32171. }
  32172. var len = other.length + source.length;
  32173. var isSrcTypedArray = source instanceof Float32Array;
  32174. var isOthTypedArray = other instanceof Float32Array;
  32175. // use non-loop method when the source is Float32Array
  32176. if (isSrcTypedArray) {
  32177. var ret32 = new Float32Array(len);
  32178. ret32.set(source);
  32179. ret32.set(other, source.length);
  32180. return ret32;
  32181. // source is number[], when other is also use concat
  32182. }
  32183. else if (!isOthTypedArray) {
  32184. return source.concat(other);
  32185. // source is a number[], but other is a Float32Array, loop required
  32186. }
  32187. else {
  32188. var ret = source.slice(0); // copy source to a separate array
  32189. for (var i = 0, len = other.length; i < len; i++) {
  32190. ret.push(other[i]);
  32191. }
  32192. return ret;
  32193. }
  32194. };
  32195. VertexData.prototype._validate = function () {
  32196. if (!this.positions) {
  32197. throw new Error("Positions are required");
  32198. }
  32199. var getElementCount = function (kind, values) {
  32200. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32201. if ((values.length % stride) !== 0) {
  32202. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32203. }
  32204. return values.length / stride;
  32205. };
  32206. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32207. var validateElementCount = function (kind, values) {
  32208. var elementCount = getElementCount(kind, values);
  32209. if (elementCount !== positionsElementCount) {
  32210. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32211. }
  32212. };
  32213. if (this.normals)
  32214. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32215. if (this.tangents)
  32216. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32217. if (this.uvs)
  32218. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32219. if (this.uvs2)
  32220. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32221. if (this.uvs3)
  32222. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32223. if (this.uvs4)
  32224. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32225. if (this.uvs5)
  32226. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32227. if (this.uvs6)
  32228. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32229. if (this.colors)
  32230. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32231. if (this.matricesIndices)
  32232. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32233. if (this.matricesWeights)
  32234. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32235. if (this.matricesIndicesExtra)
  32236. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32237. if (this.matricesWeightsExtra)
  32238. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32239. };
  32240. /**
  32241. * Serializes the VertexData.
  32242. * Returns a serialized object.
  32243. */
  32244. VertexData.prototype.serialize = function () {
  32245. var serializationObject = this.serialize();
  32246. if (this.positions) {
  32247. serializationObject.positions = this.positions;
  32248. }
  32249. if (this.normals) {
  32250. serializationObject.normals = this.normals;
  32251. }
  32252. if (this.tangents) {
  32253. serializationObject.tangents = this.tangents;
  32254. }
  32255. if (this.uvs) {
  32256. serializationObject.uvs = this.uvs;
  32257. }
  32258. if (this.uvs2) {
  32259. serializationObject.uvs2 = this.uvs2;
  32260. }
  32261. if (this.uvs3) {
  32262. serializationObject.uvs3 = this.uvs3;
  32263. }
  32264. if (this.uvs4) {
  32265. serializationObject.uvs4 = this.uvs4;
  32266. }
  32267. if (this.uvs5) {
  32268. serializationObject.uvs5 = this.uvs5;
  32269. }
  32270. if (this.uvs6) {
  32271. serializationObject.uvs6 = this.uvs6;
  32272. }
  32273. if (this.colors) {
  32274. serializationObject.colors = this.colors;
  32275. }
  32276. if (this.matricesIndices) {
  32277. serializationObject.matricesIndices = this.matricesIndices;
  32278. serializationObject.matricesIndices._isExpanded = true;
  32279. }
  32280. if (this.matricesWeights) {
  32281. serializationObject.matricesWeights = this.matricesWeights;
  32282. }
  32283. if (this.matricesIndicesExtra) {
  32284. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32285. serializationObject.matricesIndicesExtra._isExpanded = true;
  32286. }
  32287. if (this.matricesWeightsExtra) {
  32288. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32289. }
  32290. serializationObject.indices = this.indices;
  32291. return serializationObject;
  32292. };
  32293. // Statics
  32294. /**
  32295. * Returns the object VertexData associated to the passed mesh.
  32296. */
  32297. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32298. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32299. };
  32300. /**
  32301. * Returns the object VertexData associated to the passed geometry.
  32302. */
  32303. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32304. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32305. };
  32306. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32307. var result = new VertexData();
  32308. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32309. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32310. }
  32311. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32312. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32313. }
  32314. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32315. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32316. }
  32317. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32318. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32319. }
  32320. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32321. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32322. }
  32323. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32324. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32325. }
  32326. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32327. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32328. }
  32329. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32330. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32331. }
  32332. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32333. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32334. }
  32335. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32336. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32337. }
  32338. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32339. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32340. }
  32341. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32342. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32343. }
  32344. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32345. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32346. }
  32347. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32348. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32349. }
  32350. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32351. return result;
  32352. };
  32353. /**
  32354. * Creates the vertexData of the Ribbon.
  32355. */
  32356. VertexData.CreateRibbon = function (options) {
  32357. var pathArray = options.pathArray;
  32358. var closeArray = options.closeArray || false;
  32359. var closePath = options.closePath || false;
  32360. var invertUV = options.invertUV || false;
  32361. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32362. var offset = options.offset || defaultOffset;
  32363. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32364. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32365. var customUV = options.uvs;
  32366. var customColors = options.colors;
  32367. var positions = [];
  32368. var indices = [];
  32369. var normals = [];
  32370. var uvs = [];
  32371. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32372. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32373. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32374. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32375. var minlg; // minimal length among all paths from pathArray
  32376. var lg = []; // array of path lengths : nb of vertex per path
  32377. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32378. var p; // path iterator
  32379. var i; // point iterator
  32380. var j; // point iterator
  32381. // if single path in pathArray
  32382. if (pathArray.length < 2) {
  32383. var ar1 = [];
  32384. var ar2 = [];
  32385. for (i = 0; i < pathArray[0].length - offset; i++) {
  32386. ar1.push(pathArray[0][i]);
  32387. ar2.push(pathArray[0][i + offset]);
  32388. }
  32389. pathArray = [ar1, ar2];
  32390. }
  32391. // positions and horizontal distances (u)
  32392. var idc = 0;
  32393. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32394. var path;
  32395. var l;
  32396. minlg = pathArray[0].length;
  32397. var vectlg;
  32398. var dist;
  32399. for (p = 0; p < pathArray.length; p++) {
  32400. uTotalDistance[p] = 0;
  32401. us[p] = [0];
  32402. path = pathArray[p];
  32403. l = path.length;
  32404. minlg = (minlg < l) ? minlg : l;
  32405. j = 0;
  32406. while (j < l) {
  32407. positions.push(path[j].x, path[j].y, path[j].z);
  32408. if (j > 0) {
  32409. vectlg = path[j].subtract(path[j - 1]).length();
  32410. dist = vectlg + uTotalDistance[p];
  32411. us[p].push(dist);
  32412. uTotalDistance[p] = dist;
  32413. }
  32414. j++;
  32415. }
  32416. if (closePath) {
  32417. j--;
  32418. positions.push(path[0].x, path[0].y, path[0].z);
  32419. vectlg = path[j].subtract(path[0]).length();
  32420. dist = vectlg + uTotalDistance[p];
  32421. us[p].push(dist);
  32422. uTotalDistance[p] = dist;
  32423. }
  32424. lg[p] = l + closePathCorr;
  32425. idx[p] = idc;
  32426. idc += (l + closePathCorr);
  32427. }
  32428. // vertical distances (v)
  32429. var path1;
  32430. var path2;
  32431. var vertex1 = null;
  32432. var vertex2 = null;
  32433. for (i = 0; i < minlg + closePathCorr; i++) {
  32434. vTotalDistance[i] = 0;
  32435. vs[i] = [0];
  32436. for (p = 0; p < pathArray.length - 1; p++) {
  32437. path1 = pathArray[p];
  32438. path2 = pathArray[p + 1];
  32439. if (i === minlg) {
  32440. vertex1 = path1[0];
  32441. vertex2 = path2[0];
  32442. }
  32443. else {
  32444. vertex1 = path1[i];
  32445. vertex2 = path2[i];
  32446. }
  32447. vectlg = vertex2.subtract(vertex1).length();
  32448. dist = vectlg + vTotalDistance[i];
  32449. vs[i].push(dist);
  32450. vTotalDistance[i] = dist;
  32451. }
  32452. if (closeArray && vertex2 && vertex1) {
  32453. path1 = pathArray[p];
  32454. path2 = pathArray[0];
  32455. if (i === minlg) {
  32456. vertex2 = path2[0];
  32457. }
  32458. vectlg = vertex2.subtract(vertex1).length();
  32459. dist = vectlg + vTotalDistance[i];
  32460. vTotalDistance[i] = dist;
  32461. }
  32462. }
  32463. // uvs
  32464. var u;
  32465. var v;
  32466. if (customUV) {
  32467. for (p = 0; p < customUV.length; p++) {
  32468. uvs.push(customUV[p].x, customUV[p].y);
  32469. }
  32470. }
  32471. else {
  32472. for (p = 0; p < pathArray.length; p++) {
  32473. for (i = 0; i < minlg + closePathCorr; i++) {
  32474. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32475. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32476. if (invertUV) {
  32477. uvs.push(v, u);
  32478. }
  32479. else {
  32480. uvs.push(u, v);
  32481. }
  32482. }
  32483. }
  32484. }
  32485. // indices
  32486. p = 0; // path index
  32487. var pi = 0; // positions array index
  32488. var l1 = lg[p] - 1; // path1 length
  32489. var l2 = lg[p + 1] - 1; // path2 length
  32490. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32491. var shft = idx[1] - idx[0]; // shift
  32492. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32493. while (pi <= min && p < path1nb) {
  32494. // 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
  32495. indices.push(pi, pi + shft, pi + 1);
  32496. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32497. pi += 1;
  32498. if (pi === min) {
  32499. p++;
  32500. if (p === lg.length - 1) {
  32501. shft = idx[0] - idx[p];
  32502. l1 = lg[p] - 1;
  32503. l2 = lg[0] - 1;
  32504. }
  32505. else {
  32506. shft = idx[p + 1] - idx[p];
  32507. l1 = lg[p] - 1;
  32508. l2 = lg[p + 1] - 1;
  32509. }
  32510. pi = idx[p];
  32511. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32512. }
  32513. }
  32514. // normals
  32515. VertexData.ComputeNormals(positions, indices, normals);
  32516. if (closePath) {
  32517. var indexFirst = 0;
  32518. var indexLast = 0;
  32519. for (p = 0; p < pathArray.length; p++) {
  32520. indexFirst = idx[p] * 3;
  32521. if (p + 1 < pathArray.length) {
  32522. indexLast = (idx[p + 1] - 1) * 3;
  32523. }
  32524. else {
  32525. indexLast = normals.length - 3;
  32526. }
  32527. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32528. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32529. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32530. normals[indexLast] = normals[indexFirst];
  32531. normals[indexLast + 1] = normals[indexFirst + 1];
  32532. normals[indexLast + 2] = normals[indexFirst + 2];
  32533. }
  32534. }
  32535. // sides
  32536. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32537. // Colors
  32538. var colors = null;
  32539. if (customColors) {
  32540. colors = new Float32Array(customColors.length * 4);
  32541. for (var c = 0; c < customColors.length; c++) {
  32542. colors[c * 4] = customColors[c].r;
  32543. colors[c * 4 + 1] = customColors[c].g;
  32544. colors[c * 4 + 2] = customColors[c].b;
  32545. colors[c * 4 + 3] = customColors[c].a;
  32546. }
  32547. }
  32548. // Result
  32549. var vertexData = new VertexData();
  32550. var positions32 = new Float32Array(positions);
  32551. var normals32 = new Float32Array(normals);
  32552. var uvs32 = new Float32Array(uvs);
  32553. vertexData.indices = indices;
  32554. vertexData.positions = positions32;
  32555. vertexData.normals = normals32;
  32556. vertexData.uvs = uvs32;
  32557. if (colors) {
  32558. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32559. }
  32560. if (closePath) {
  32561. vertexData._idx = idx;
  32562. }
  32563. return vertexData;
  32564. };
  32565. /**
  32566. * Creates the VertexData of the Box.
  32567. */
  32568. VertexData.CreateBox = function (options) {
  32569. var normalsSource = [
  32570. new BABYLON.Vector3(0, 0, 1),
  32571. new BABYLON.Vector3(0, 0, -1),
  32572. new BABYLON.Vector3(1, 0, 0),
  32573. new BABYLON.Vector3(-1, 0, 0),
  32574. new BABYLON.Vector3(0, 1, 0),
  32575. new BABYLON.Vector3(0, -1, 0)
  32576. ];
  32577. var indices = [];
  32578. var positions = [];
  32579. var normals = [];
  32580. var uvs = [];
  32581. var width = options.width || options.size || 1;
  32582. var height = options.height || options.size || 1;
  32583. var depth = options.depth || options.size || 1;
  32584. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32585. var faceUV = options.faceUV || new Array(6);
  32586. var faceColors = options.faceColors;
  32587. var colors = [];
  32588. // default face colors and UV if undefined
  32589. for (var f = 0; f < 6; f++) {
  32590. if (faceUV[f] === undefined) {
  32591. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32592. }
  32593. if (faceColors && faceColors[f] === undefined) {
  32594. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32595. }
  32596. }
  32597. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32598. // Create each face in turn.
  32599. for (var index = 0; index < normalsSource.length; index++) {
  32600. var normal = normalsSource[index];
  32601. // Get two vectors perpendicular to the face normal and to each other.
  32602. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32603. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32604. // Six indices (two triangles) per face.
  32605. var verticesLength = positions.length / 3;
  32606. indices.push(verticesLength);
  32607. indices.push(verticesLength + 1);
  32608. indices.push(verticesLength + 2);
  32609. indices.push(verticesLength);
  32610. indices.push(verticesLength + 2);
  32611. indices.push(verticesLength + 3);
  32612. // Four vertices per face.
  32613. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32614. positions.push(vertex.x, vertex.y, vertex.z);
  32615. normals.push(normal.x, normal.y, normal.z);
  32616. uvs.push(faceUV[index].z, faceUV[index].w);
  32617. if (faceColors) {
  32618. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32619. }
  32620. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32621. positions.push(vertex.x, vertex.y, vertex.z);
  32622. normals.push(normal.x, normal.y, normal.z);
  32623. uvs.push(faceUV[index].x, faceUV[index].w);
  32624. if (faceColors) {
  32625. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32626. }
  32627. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32628. positions.push(vertex.x, vertex.y, vertex.z);
  32629. normals.push(normal.x, normal.y, normal.z);
  32630. uvs.push(faceUV[index].x, faceUV[index].y);
  32631. if (faceColors) {
  32632. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32633. }
  32634. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32635. positions.push(vertex.x, vertex.y, vertex.z);
  32636. normals.push(normal.x, normal.y, normal.z);
  32637. uvs.push(faceUV[index].z, faceUV[index].y);
  32638. if (faceColors) {
  32639. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32640. }
  32641. }
  32642. // sides
  32643. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32644. // Result
  32645. var vertexData = new VertexData();
  32646. vertexData.indices = indices;
  32647. vertexData.positions = positions;
  32648. vertexData.normals = normals;
  32649. vertexData.uvs = uvs;
  32650. if (faceColors) {
  32651. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32652. vertexData.colors = totalColors;
  32653. }
  32654. return vertexData;
  32655. };
  32656. /**
  32657. * Creates the VertexData of the Sphere.
  32658. */
  32659. VertexData.CreateSphere = function (options) {
  32660. var segments = options.segments || 32;
  32661. var diameterX = options.diameterX || options.diameter || 1;
  32662. var diameterY = options.diameterY || options.diameter || 1;
  32663. var diameterZ = options.diameterZ || options.diameter || 1;
  32664. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32665. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32666. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32667. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32668. var totalZRotationSteps = 2 + segments;
  32669. var totalYRotationSteps = 2 * totalZRotationSteps;
  32670. var indices = [];
  32671. var positions = [];
  32672. var normals = [];
  32673. var uvs = [];
  32674. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32675. var normalizedZ = zRotationStep / totalZRotationSteps;
  32676. var angleZ = normalizedZ * Math.PI * slice;
  32677. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32678. var normalizedY = yRotationStep / totalYRotationSteps;
  32679. var angleY = normalizedY * Math.PI * 2 * arc;
  32680. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32681. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32682. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32683. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32684. var vertex = complete.multiply(radius);
  32685. var normal = complete.divide(radius).normalize();
  32686. positions.push(vertex.x, vertex.y, vertex.z);
  32687. normals.push(normal.x, normal.y, normal.z);
  32688. uvs.push(normalizedY, normalizedZ);
  32689. }
  32690. if (zRotationStep > 0) {
  32691. var verticesCount = positions.length / 3;
  32692. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32693. indices.push((firstIndex));
  32694. indices.push((firstIndex + 1));
  32695. indices.push(firstIndex + totalYRotationSteps + 1);
  32696. indices.push((firstIndex + totalYRotationSteps + 1));
  32697. indices.push((firstIndex + 1));
  32698. indices.push((firstIndex + totalYRotationSteps + 2));
  32699. }
  32700. }
  32701. }
  32702. // Sides
  32703. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32704. // Result
  32705. var vertexData = new VertexData();
  32706. vertexData.indices = indices;
  32707. vertexData.positions = positions;
  32708. vertexData.normals = normals;
  32709. vertexData.uvs = uvs;
  32710. return vertexData;
  32711. };
  32712. /**
  32713. * Creates the VertexData of the Cylinder or Cone.
  32714. */
  32715. VertexData.CreateCylinder = function (options) {
  32716. var height = options.height || 2;
  32717. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32718. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32719. var tessellation = options.tessellation || 24;
  32720. var subdivisions = options.subdivisions || 1;
  32721. var hasRings = options.hasRings ? true : false;
  32722. var enclose = options.enclose ? true : false;
  32723. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32724. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32725. var faceUV = options.faceUV || new Array(3);
  32726. var faceColors = options.faceColors;
  32727. // default face colors and UV if undefined
  32728. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32729. var ringNb = (hasRings) ? subdivisions : 1;
  32730. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32731. var f;
  32732. for (f = 0; f < surfaceNb; f++) {
  32733. if (faceColors && faceColors[f] === undefined) {
  32734. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32735. }
  32736. }
  32737. for (f = 0; f < surfaceNb; f++) {
  32738. if (faceUV && faceUV[f] === undefined) {
  32739. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32740. }
  32741. }
  32742. var indices = new Array();
  32743. var positions = new Array();
  32744. var normals = new Array();
  32745. var uvs = new Array();
  32746. var colors = new Array();
  32747. var angle_step = Math.PI * 2 * arc / tessellation;
  32748. var angle;
  32749. var h;
  32750. var radius;
  32751. var tan = (diameterBottom - diameterTop) / 2 / height;
  32752. var ringVertex = BABYLON.Vector3.Zero();
  32753. var ringNormal = BABYLON.Vector3.Zero();
  32754. var ringFirstVertex = BABYLON.Vector3.Zero();
  32755. var ringFirstNormal = BABYLON.Vector3.Zero();
  32756. var quadNormal = BABYLON.Vector3.Zero();
  32757. var Y = BABYLON.Axis.Y;
  32758. // positions, normals, uvs
  32759. var i;
  32760. var j;
  32761. var r;
  32762. var ringIdx = 1;
  32763. var s = 1; // surface index
  32764. var cs = 0;
  32765. var v = 0;
  32766. for (i = 0; i <= subdivisions; i++) {
  32767. h = i / subdivisions;
  32768. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32769. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32770. for (r = 0; r < ringIdx; r++) {
  32771. if (hasRings) {
  32772. s += r;
  32773. }
  32774. if (enclose) {
  32775. s += 2 * r;
  32776. }
  32777. for (j = 0; j <= tessellation; j++) {
  32778. angle = j * angle_step;
  32779. // position
  32780. ringVertex.x = Math.cos(-angle) * radius;
  32781. ringVertex.y = -height / 2 + h * height;
  32782. ringVertex.z = Math.sin(-angle) * radius;
  32783. // normal
  32784. if (diameterTop === 0 && i === subdivisions) {
  32785. // if no top cap, reuse former normals
  32786. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32787. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32788. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32789. }
  32790. else {
  32791. ringNormal.x = ringVertex.x;
  32792. ringNormal.z = ringVertex.z;
  32793. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32794. ringNormal.normalize();
  32795. }
  32796. // keep first ring vertex values for enclose
  32797. if (j === 0) {
  32798. ringFirstVertex.copyFrom(ringVertex);
  32799. ringFirstNormal.copyFrom(ringNormal);
  32800. }
  32801. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32802. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32803. if (hasRings) {
  32804. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32805. }
  32806. else {
  32807. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32808. }
  32809. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32810. if (faceColors) {
  32811. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32812. }
  32813. }
  32814. // if enclose, add four vertices and their dedicated normals
  32815. if (arc !== 1 && enclose) {
  32816. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32817. positions.push(0, ringVertex.y, 0);
  32818. positions.push(0, ringVertex.y, 0);
  32819. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32820. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32821. quadNormal.normalize();
  32822. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32823. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32824. quadNormal.normalize();
  32825. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32826. if (hasRings) {
  32827. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32828. }
  32829. else {
  32830. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32831. }
  32832. uvs.push(faceUV[s + 1].x, v);
  32833. uvs.push(faceUV[s + 1].z, v);
  32834. if (hasRings) {
  32835. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32836. }
  32837. else {
  32838. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32839. }
  32840. uvs.push(faceUV[s + 2].x, v);
  32841. uvs.push(faceUV[s + 2].z, v);
  32842. if (faceColors) {
  32843. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32844. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32845. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32846. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32847. }
  32848. }
  32849. if (cs !== s) {
  32850. cs = s;
  32851. }
  32852. }
  32853. }
  32854. // indices
  32855. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32856. var s;
  32857. i = 0;
  32858. for (s = 0; s < subdivisions; s++) {
  32859. var i0 = 0;
  32860. var i1 = 0;
  32861. var i2 = 0;
  32862. var i3 = 0;
  32863. for (j = 0; j < tessellation; j++) {
  32864. i0 = i * (e + 1) + j;
  32865. i1 = (i + 1) * (e + 1) + j;
  32866. i2 = i * (e + 1) + (j + 1);
  32867. i3 = (i + 1) * (e + 1) + (j + 1);
  32868. indices.push(i0, i1, i2);
  32869. indices.push(i3, i2, i1);
  32870. }
  32871. if (arc !== 1 && enclose) {
  32872. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32873. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32874. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32875. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32876. }
  32877. i = (hasRings) ? (i + 2) : (i + 1);
  32878. }
  32879. // Caps
  32880. var createCylinderCap = function (isTop) {
  32881. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32882. if (radius === 0) {
  32883. return;
  32884. }
  32885. // Cap positions, normals & uvs
  32886. var angle;
  32887. var circleVector;
  32888. var i;
  32889. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32890. var c = null;
  32891. if (faceColors) {
  32892. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32893. }
  32894. // cap center
  32895. var vbase = positions.length / 3;
  32896. var offset = isTop ? height / 2 : -height / 2;
  32897. var center = new BABYLON.Vector3(0, offset, 0);
  32898. positions.push(center.x, center.y, center.z);
  32899. normals.push(0, isTop ? 1 : -1, 0);
  32900. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32901. if (c) {
  32902. colors.push(c.r, c.g, c.b, c.a);
  32903. }
  32904. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32905. for (i = 0; i <= tessellation; i++) {
  32906. angle = Math.PI * 2 * i * arc / tessellation;
  32907. var cos = Math.cos(-angle);
  32908. var sin = Math.sin(-angle);
  32909. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32910. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32911. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32912. normals.push(0, isTop ? 1 : -1, 0);
  32913. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32914. if (c) {
  32915. colors.push(c.r, c.g, c.b, c.a);
  32916. }
  32917. }
  32918. // Cap indices
  32919. for (i = 0; i < tessellation; i++) {
  32920. if (!isTop) {
  32921. indices.push(vbase);
  32922. indices.push(vbase + (i + 1));
  32923. indices.push(vbase + (i + 2));
  32924. }
  32925. else {
  32926. indices.push(vbase);
  32927. indices.push(vbase + (i + 2));
  32928. indices.push(vbase + (i + 1));
  32929. }
  32930. }
  32931. };
  32932. // add caps to geometry
  32933. createCylinderCap(false);
  32934. createCylinderCap(true);
  32935. // Sides
  32936. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32937. var vertexData = new VertexData();
  32938. vertexData.indices = indices;
  32939. vertexData.positions = positions;
  32940. vertexData.normals = normals;
  32941. vertexData.uvs = uvs;
  32942. if (faceColors) {
  32943. vertexData.colors = colors;
  32944. }
  32945. return vertexData;
  32946. };
  32947. /**
  32948. * Creates the VertexData of the Torus.
  32949. */
  32950. VertexData.CreateTorus = function (options) {
  32951. var indices = [];
  32952. var positions = [];
  32953. var normals = [];
  32954. var uvs = [];
  32955. var diameter = options.diameter || 1;
  32956. var thickness = options.thickness || 0.5;
  32957. var tessellation = options.tessellation || 16;
  32958. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32959. var stride = tessellation + 1;
  32960. for (var i = 0; i <= tessellation; i++) {
  32961. var u = i / tessellation;
  32962. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32963. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32964. for (var j = 0; j <= tessellation; j++) {
  32965. var v = 1 - j / tessellation;
  32966. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32967. var dx = Math.cos(innerAngle);
  32968. var dy = Math.sin(innerAngle);
  32969. // Create a vertex.
  32970. var normal = new BABYLON.Vector3(dx, dy, 0);
  32971. var position = normal.scale(thickness / 2);
  32972. var textureCoordinate = new BABYLON.Vector2(u, v);
  32973. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32974. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32975. positions.push(position.x, position.y, position.z);
  32976. normals.push(normal.x, normal.y, normal.z);
  32977. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32978. // And create indices for two triangles.
  32979. var nextI = (i + 1) % stride;
  32980. var nextJ = (j + 1) % stride;
  32981. indices.push(i * stride + j);
  32982. indices.push(i * stride + nextJ);
  32983. indices.push(nextI * stride + j);
  32984. indices.push(i * stride + nextJ);
  32985. indices.push(nextI * stride + nextJ);
  32986. indices.push(nextI * stride + j);
  32987. }
  32988. }
  32989. // Sides
  32990. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32991. // Result
  32992. var vertexData = new VertexData();
  32993. vertexData.indices = indices;
  32994. vertexData.positions = positions;
  32995. vertexData.normals = normals;
  32996. vertexData.uvs = uvs;
  32997. return vertexData;
  32998. };
  32999. /**
  33000. * Creates the VertexData of the LineSystem.
  33001. */
  33002. VertexData.CreateLineSystem = function (options) {
  33003. var indices = [];
  33004. var positions = [];
  33005. var lines = options.lines;
  33006. var colors = options.colors;
  33007. var vertexColors = [];
  33008. var idx = 0;
  33009. for (var l = 0; l < lines.length; l++) {
  33010. var points = lines[l];
  33011. for (var index = 0; index < points.length; index++) {
  33012. positions.push(points[index].x, points[index].y, points[index].z);
  33013. if (colors) {
  33014. var color = colors[l];
  33015. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33016. }
  33017. if (index > 0) {
  33018. indices.push(idx - 1);
  33019. indices.push(idx);
  33020. }
  33021. idx++;
  33022. }
  33023. }
  33024. var vertexData = new VertexData();
  33025. vertexData.indices = indices;
  33026. vertexData.positions = positions;
  33027. if (colors) {
  33028. vertexData.colors = vertexColors;
  33029. }
  33030. return vertexData;
  33031. };
  33032. /**
  33033. * Create the VertexData of the DashedLines.
  33034. */
  33035. VertexData.CreateDashedLines = function (options) {
  33036. var dashSize = options.dashSize || 3;
  33037. var gapSize = options.gapSize || 1;
  33038. var dashNb = options.dashNb || 200;
  33039. var points = options.points;
  33040. var positions = new Array();
  33041. var indices = new Array();
  33042. var curvect = BABYLON.Vector3.Zero();
  33043. var lg = 0;
  33044. var nb = 0;
  33045. var shft = 0;
  33046. var dashshft = 0;
  33047. var curshft = 0;
  33048. var idx = 0;
  33049. var i = 0;
  33050. for (i = 0; i < points.length - 1; i++) {
  33051. points[i + 1].subtractToRef(points[i], curvect);
  33052. lg += curvect.length();
  33053. }
  33054. shft = lg / dashNb;
  33055. dashshft = dashSize * shft / (dashSize + gapSize);
  33056. for (i = 0; i < points.length - 1; i++) {
  33057. points[i + 1].subtractToRef(points[i], curvect);
  33058. nb = Math.floor(curvect.length() / shft);
  33059. curvect.normalize();
  33060. for (var j = 0; j < nb; j++) {
  33061. curshft = shft * j;
  33062. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33063. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33064. indices.push(idx, idx + 1);
  33065. idx += 2;
  33066. }
  33067. }
  33068. // Result
  33069. var vertexData = new VertexData();
  33070. vertexData.positions = positions;
  33071. vertexData.indices = indices;
  33072. return vertexData;
  33073. };
  33074. /**
  33075. * Creates the VertexData of the Ground.
  33076. */
  33077. VertexData.CreateGround = function (options) {
  33078. var indices = [];
  33079. var positions = [];
  33080. var normals = [];
  33081. var uvs = [];
  33082. var row, col;
  33083. var width = options.width || 1;
  33084. var height = options.height || 1;
  33085. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33086. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33087. for (row = 0; row <= subdivisionsY; row++) {
  33088. for (col = 0; col <= subdivisionsX; col++) {
  33089. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33090. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33091. positions.push(position.x, position.y, position.z);
  33092. normals.push(normal.x, normal.y, normal.z);
  33093. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33094. }
  33095. }
  33096. for (row = 0; row < subdivisionsY; row++) {
  33097. for (col = 0; col < subdivisionsX; col++) {
  33098. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33099. indices.push(col + 1 + row * (subdivisionsX + 1));
  33100. indices.push(col + row * (subdivisionsX + 1));
  33101. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33102. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33103. indices.push(col + row * (subdivisionsX + 1));
  33104. }
  33105. }
  33106. // Result
  33107. var vertexData = new VertexData();
  33108. vertexData.indices = indices;
  33109. vertexData.positions = positions;
  33110. vertexData.normals = normals;
  33111. vertexData.uvs = uvs;
  33112. return vertexData;
  33113. };
  33114. /**
  33115. * Creates the VertexData of the TiledGround.
  33116. */
  33117. VertexData.CreateTiledGround = function (options) {
  33118. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33119. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33120. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33121. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33122. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33123. var precision = options.precision || { w: 1, h: 1 };
  33124. var indices = new Array();
  33125. var positions = new Array();
  33126. var normals = new Array();
  33127. var uvs = new Array();
  33128. var row, col, tileRow, tileCol;
  33129. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33130. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33131. precision.w = (precision.w < 1) ? 1 : precision.w;
  33132. precision.h = (precision.h < 1) ? 1 : precision.h;
  33133. var tileSize = {
  33134. 'w': (xmax - xmin) / subdivisions.w,
  33135. 'h': (zmax - zmin) / subdivisions.h
  33136. };
  33137. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33138. // Indices
  33139. var base = positions.length / 3;
  33140. var rowLength = precision.w + 1;
  33141. for (row = 0; row < precision.h; row++) {
  33142. for (col = 0; col < precision.w; col++) {
  33143. var square = [
  33144. base + col + row * rowLength,
  33145. base + (col + 1) + row * rowLength,
  33146. base + (col + 1) + (row + 1) * rowLength,
  33147. base + col + (row + 1) * rowLength
  33148. ];
  33149. indices.push(square[1]);
  33150. indices.push(square[2]);
  33151. indices.push(square[3]);
  33152. indices.push(square[0]);
  33153. indices.push(square[1]);
  33154. indices.push(square[3]);
  33155. }
  33156. }
  33157. // Position, normals and uvs
  33158. var position = BABYLON.Vector3.Zero();
  33159. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33160. for (row = 0; row <= precision.h; row++) {
  33161. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33162. for (col = 0; col <= precision.w; col++) {
  33163. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33164. position.y = 0;
  33165. positions.push(position.x, position.y, position.z);
  33166. normals.push(normal.x, normal.y, normal.z);
  33167. uvs.push(col / precision.w, row / precision.h);
  33168. }
  33169. }
  33170. }
  33171. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33172. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33173. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33174. }
  33175. }
  33176. // Result
  33177. var vertexData = new VertexData();
  33178. vertexData.indices = indices;
  33179. vertexData.positions = positions;
  33180. vertexData.normals = normals;
  33181. vertexData.uvs = uvs;
  33182. return vertexData;
  33183. };
  33184. /**
  33185. * Creates the VertexData of the Ground designed from a heightmap.
  33186. */
  33187. VertexData.CreateGroundFromHeightMap = function (options) {
  33188. var indices = [];
  33189. var positions = [];
  33190. var normals = [];
  33191. var uvs = [];
  33192. var row, col;
  33193. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33194. // Vertices
  33195. for (row = 0; row <= options.subdivisions; row++) {
  33196. for (col = 0; col <= options.subdivisions; col++) {
  33197. 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));
  33198. // Compute height
  33199. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33200. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33201. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33202. var r = options.buffer[pos] / 255.0;
  33203. var g = options.buffer[pos + 1] / 255.0;
  33204. var b = options.buffer[pos + 2] / 255.0;
  33205. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33206. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33207. // Add vertex
  33208. positions.push(position.x, position.y, position.z);
  33209. normals.push(0, 0, 0);
  33210. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33211. }
  33212. }
  33213. // Indices
  33214. for (row = 0; row < options.subdivisions; row++) {
  33215. for (col = 0; col < options.subdivisions; col++) {
  33216. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33217. indices.push(col + 1 + row * (options.subdivisions + 1));
  33218. indices.push(col + row * (options.subdivisions + 1));
  33219. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33220. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33221. indices.push(col + row * (options.subdivisions + 1));
  33222. }
  33223. }
  33224. // Normals
  33225. VertexData.ComputeNormals(positions, indices, normals);
  33226. // Result
  33227. var vertexData = new VertexData();
  33228. vertexData.indices = indices;
  33229. vertexData.positions = positions;
  33230. vertexData.normals = normals;
  33231. vertexData.uvs = uvs;
  33232. return vertexData;
  33233. };
  33234. /**
  33235. * Creates the VertexData of the Plane.
  33236. */
  33237. VertexData.CreatePlane = function (options) {
  33238. var indices = [];
  33239. var positions = [];
  33240. var normals = [];
  33241. var uvs = [];
  33242. var width = options.width || options.size || 1;
  33243. var height = options.height || options.size || 1;
  33244. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33245. // Vertices
  33246. var halfWidth = width / 2.0;
  33247. var halfHeight = height / 2.0;
  33248. positions.push(-halfWidth, -halfHeight, 0);
  33249. normals.push(0, 0, -1.0);
  33250. uvs.push(0.0, 0.0);
  33251. positions.push(halfWidth, -halfHeight, 0);
  33252. normals.push(0, 0, -1.0);
  33253. uvs.push(1.0, 0.0);
  33254. positions.push(halfWidth, halfHeight, 0);
  33255. normals.push(0, 0, -1.0);
  33256. uvs.push(1.0, 1.0);
  33257. positions.push(-halfWidth, halfHeight, 0);
  33258. normals.push(0, 0, -1.0);
  33259. uvs.push(0.0, 1.0);
  33260. // Indices
  33261. indices.push(0);
  33262. indices.push(1);
  33263. indices.push(2);
  33264. indices.push(0);
  33265. indices.push(2);
  33266. indices.push(3);
  33267. // Sides
  33268. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33269. // Result
  33270. var vertexData = new VertexData();
  33271. vertexData.indices = indices;
  33272. vertexData.positions = positions;
  33273. vertexData.normals = normals;
  33274. vertexData.uvs = uvs;
  33275. return vertexData;
  33276. };
  33277. /**
  33278. * Creates the VertexData of the Disc or regular Polygon.
  33279. */
  33280. VertexData.CreateDisc = function (options) {
  33281. var positions = new Array();
  33282. var indices = new Array();
  33283. var normals = new Array();
  33284. var uvs = new Array();
  33285. var radius = options.radius || 0.5;
  33286. var tessellation = options.tessellation || 64;
  33287. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33288. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33289. // positions and uvs
  33290. positions.push(0, 0, 0); // disc center first
  33291. uvs.push(0.5, 0.5);
  33292. var theta = Math.PI * 2 * arc;
  33293. var step = theta / tessellation;
  33294. for (var a = 0; a < theta; a += step) {
  33295. var x = Math.cos(a);
  33296. var y = Math.sin(a);
  33297. var u = (x + 1) / 2;
  33298. var v = (1 - y) / 2;
  33299. positions.push(radius * x, radius * y, 0);
  33300. uvs.push(u, v);
  33301. }
  33302. if (arc === 1) {
  33303. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33304. uvs.push(uvs[2], uvs[3]);
  33305. }
  33306. //indices
  33307. var vertexNb = positions.length / 3;
  33308. for (var i = 1; i < vertexNb - 1; i++) {
  33309. indices.push(i + 1, 0, i);
  33310. }
  33311. // result
  33312. VertexData.ComputeNormals(positions, indices, normals);
  33313. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33314. var vertexData = new VertexData();
  33315. vertexData.indices = indices;
  33316. vertexData.positions = positions;
  33317. vertexData.normals = normals;
  33318. vertexData.uvs = uvs;
  33319. return vertexData;
  33320. };
  33321. /**
  33322. * Re-creates the VertexData of the Polygon for sideOrientation.
  33323. */
  33324. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33325. var faceUV = fUV || new Array(3);
  33326. var faceColors = fColors;
  33327. var colors = [];
  33328. // default face colors and UV if undefined
  33329. for (var f = 0; f < 3; f++) {
  33330. if (faceUV[f] === undefined) {
  33331. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33332. }
  33333. if (faceColors && faceColors[f] === undefined) {
  33334. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33335. }
  33336. }
  33337. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33338. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33339. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33340. var indices = polygon.getIndices();
  33341. // set face colours and textures
  33342. var idx = 0;
  33343. var face = 0;
  33344. for (var index = 0; index < normals.length; index += 3) {
  33345. //Edge Face no. 1
  33346. if (Math.abs(normals[index + 1]) < 0.001) {
  33347. face = 1;
  33348. }
  33349. //Top Face no. 0
  33350. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33351. face = 0;
  33352. }
  33353. //Bottom Face no. 2
  33354. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33355. face = 2;
  33356. }
  33357. idx = index / 3;
  33358. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33359. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33360. if (faceColors) {
  33361. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33362. }
  33363. }
  33364. // sides
  33365. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33366. // Result
  33367. var vertexData = new VertexData();
  33368. vertexData.indices = indices;
  33369. vertexData.positions = positions;
  33370. vertexData.normals = normals;
  33371. vertexData.uvs = uvs;
  33372. if (faceColors) {
  33373. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33374. vertexData.colors = totalColors;
  33375. }
  33376. return vertexData;
  33377. };
  33378. /**
  33379. * Creates the VertexData of the IcoSphere.
  33380. */
  33381. VertexData.CreateIcoSphere = function (options) {
  33382. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33383. var radius = options.radius || 1;
  33384. var flat = (options.flat === undefined) ? true : options.flat;
  33385. var subdivisions = options.subdivisions || 4;
  33386. var radiusX = options.radiusX || radius;
  33387. var radiusY = options.radiusY || radius;
  33388. var radiusZ = options.radiusZ || radius;
  33389. var t = (1 + Math.sqrt(5)) / 2;
  33390. // 12 vertex x,y,z
  33391. var ico_vertices = [
  33392. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33393. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33394. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33395. ];
  33396. // index of 3 vertex makes a face of icopshere
  33397. var ico_indices = [
  33398. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33399. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33400. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33401. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33402. ];
  33403. // vertex for uv have aliased position, not for UV
  33404. var vertices_unalias_id = [
  33405. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33406. // vertex alias
  33407. 0,
  33408. 2,
  33409. 3,
  33410. 3,
  33411. 3,
  33412. 4,
  33413. 7,
  33414. 8,
  33415. 9,
  33416. 9,
  33417. 10,
  33418. 11 // 23: B + 12
  33419. ];
  33420. // uv as integer step (not pixels !)
  33421. var ico_vertexuv = [
  33422. 5, 1, 3, 1, 6, 4, 0, 0,
  33423. 5, 3, 4, 2, 2, 2, 4, 0,
  33424. 2, 0, 1, 1, 6, 0, 6, 2,
  33425. // vertex alias (for same vertex on different faces)
  33426. 0, 4,
  33427. 3, 3,
  33428. 4, 4,
  33429. 3, 1,
  33430. 4, 2,
  33431. 4, 4,
  33432. 0, 2,
  33433. 1, 1,
  33434. 2, 2,
  33435. 3, 3,
  33436. 1, 3,
  33437. 2, 4 // 23: B + 12
  33438. ];
  33439. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33440. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33441. // First island of uv mapping
  33442. // v = 4h 3+ 2
  33443. // v = 3h 9+ 4
  33444. // v = 2h 9+ 5 B
  33445. // v = 1h 9 1 0
  33446. // v = 0h 3 8 7 A
  33447. // u = 0 1 2 3 4 5 6 *a
  33448. // Second island of uv mapping
  33449. // v = 4h 0+ B+ 4+
  33450. // v = 3h A+ 2+
  33451. // v = 2h 7+ 6 3+
  33452. // v = 1h 8+ 3+
  33453. // v = 0h
  33454. // u = 0 1 2 3 4 5 6 *a
  33455. // Face layout on texture UV mapping
  33456. // ============
  33457. // \ 4 /\ 16 / ======
  33458. // \ / \ / /\ 11 /
  33459. // \/ 7 \/ / \ /
  33460. // ======= / 10 \/
  33461. // /\ 17 /\ =======
  33462. // / \ / \ \ 15 /\
  33463. // / 8 \/ 12 \ \ / \
  33464. // ============ \/ 6 \
  33465. // \ 18 /\ ============
  33466. // \ / \ \ 5 /\ 0 /
  33467. // \/ 13 \ \ / \ /
  33468. // ======= \/ 1 \/
  33469. // =============
  33470. // /\ 19 /\ 2 /\
  33471. // / \ / \ / \
  33472. // / 14 \/ 9 \/ 3 \
  33473. // ===================
  33474. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33475. var ustep = 138 / 1024;
  33476. var vstep = 239 / 1024;
  33477. var uoffset = 60 / 1024;
  33478. var voffset = 26 / 1024;
  33479. // Second island should have margin, not to touch the first island
  33480. // avoid any borderline artefact in pixel rounding
  33481. var island_u_offset = -40 / 1024;
  33482. var island_v_offset = +20 / 1024;
  33483. // face is either island 0 or 1 :
  33484. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33485. var island = [
  33486. 0, 0, 0, 0, 1,
  33487. 0, 0, 1, 1, 0,
  33488. 0, 0, 1, 1, 0,
  33489. 0, 1, 1, 1, 0 // 15 - 19
  33490. ];
  33491. var indices = new Array();
  33492. var positions = new Array();
  33493. var normals = new Array();
  33494. var uvs = new Array();
  33495. var current_indice = 0;
  33496. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33497. var face_vertex_pos = new Array(3);
  33498. var face_vertex_uv = new Array(3);
  33499. var v012;
  33500. for (v012 = 0; v012 < 3; v012++) {
  33501. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33502. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33503. }
  33504. // create all with normals
  33505. for (var face = 0; face < 20; face++) {
  33506. // 3 vertex per face
  33507. for (v012 = 0; v012 < 3; v012++) {
  33508. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33509. var v_id = ico_indices[3 * face + v012];
  33510. // vertex have 3D position (x,y,z)
  33511. 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]);
  33512. // Normalize to get normal, then scale to radius
  33513. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33514. // uv Coordinates from vertex ID
  33515. 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);
  33516. }
  33517. // Subdivide the face (interpolate pos, norm, uv)
  33518. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33519. // - norm is linear interpolation of vertex corner normal
  33520. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33521. // - uv is linear interpolation
  33522. //
  33523. // Topology is as below for sub-divide by 2
  33524. // vertex shown as v0,v1,v2
  33525. // interp index is i1 to progress in range [v0,v1[
  33526. // interp index is i2 to progress in range [v0,v2[
  33527. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33528. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33529. //
  33530. //
  33531. // i2 v2
  33532. // ^ ^
  33533. // / / \
  33534. // / / \
  33535. // / / \
  33536. // / / (0,1) \
  33537. // / #---------\
  33538. // / / \ (0,0)'/ \
  33539. // / / \ / \
  33540. // / / \ / \
  33541. // / / (0,0) \ / (1,0) \
  33542. // / #---------#---------\
  33543. // v0 v1
  33544. //
  33545. // --------------------> i1
  33546. //
  33547. // interp of (i1,i2):
  33548. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33549. // along i1 : lerp(x0,x1, i1/(S-i2))
  33550. //
  33551. // centroid of triangle is needed to get help normal computation
  33552. // (c1,c2) are used for centroid location
  33553. var interp_vertex = function (i1, i2, c1, c2) {
  33554. // vertex is interpolated from
  33555. // - face_vertex_pos[0..2]
  33556. // - face_vertex_uv[0..2]
  33557. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33558. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33559. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33560. pos_interp.normalize();
  33561. var vertex_normal;
  33562. if (flat) {
  33563. // in flat mode, recalculate normal as face centroid normal
  33564. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33565. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33566. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33567. }
  33568. else {
  33569. // in smooth mode, recalculate normal from each single vertex position
  33570. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33571. }
  33572. // Vertex normal need correction due to X,Y,Z radius scaling
  33573. vertex_normal.x /= radiusX;
  33574. vertex_normal.y /= radiusY;
  33575. vertex_normal.z /= radiusZ;
  33576. vertex_normal.normalize();
  33577. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33578. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33579. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33580. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33581. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33582. uvs.push(uv_interp.x, uv_interp.y);
  33583. // push each vertex has member of a face
  33584. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33585. indices.push(current_indice);
  33586. current_indice++;
  33587. };
  33588. for (var i2 = 0; i2 < subdivisions; i2++) {
  33589. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33590. // face : (i1,i2) for /\ :
  33591. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33592. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33593. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33594. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33595. if (i1 + i2 + 1 < subdivisions) {
  33596. // face : (i1,i2)' for \/ :
  33597. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33598. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33599. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33600. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33601. }
  33602. }
  33603. }
  33604. }
  33605. // Sides
  33606. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33607. // Result
  33608. var vertexData = new VertexData();
  33609. vertexData.indices = indices;
  33610. vertexData.positions = positions;
  33611. vertexData.normals = normals;
  33612. vertexData.uvs = uvs;
  33613. return vertexData;
  33614. };
  33615. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33616. /**
  33617. * Creates the VertexData of the Polyhedron.
  33618. */
  33619. VertexData.CreatePolyhedron = function (options) {
  33620. // provided polyhedron types :
  33621. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33622. // 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)
  33623. var polyhedra = [];
  33624. 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]] };
  33625. 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]] };
  33626. polyhedra[2] = {
  33627. 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]],
  33628. 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]]
  33629. };
  33630. polyhedra[3] = {
  33631. 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]],
  33632. 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]]
  33633. };
  33634. polyhedra[4] = {
  33635. 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]],
  33636. 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]]
  33637. };
  33638. 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]] };
  33639. 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]] };
  33640. 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]] };
  33641. 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]] };
  33642. 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]] };
  33643. 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]] };
  33644. 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]] };
  33645. 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]] };
  33646. 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]] };
  33647. polyhedra[14] = {
  33648. 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]],
  33649. 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]]
  33650. };
  33651. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33652. var size = options.size;
  33653. var sizeX = options.sizeX || size || 1;
  33654. var sizeY = options.sizeY || size || 1;
  33655. var sizeZ = options.sizeZ || size || 1;
  33656. var data = options.custom || polyhedra[type];
  33657. var nbfaces = data.face.length;
  33658. var faceUV = options.faceUV || new Array(nbfaces);
  33659. var faceColors = options.faceColors;
  33660. var flat = (options.flat === undefined) ? true : options.flat;
  33661. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33662. var positions = new Array();
  33663. var indices = new Array();
  33664. var normals = new Array();
  33665. var uvs = new Array();
  33666. var colors = new Array();
  33667. var index = 0;
  33668. var faceIdx = 0; // face cursor in the array "indexes"
  33669. var indexes = new Array();
  33670. var i = 0;
  33671. var f = 0;
  33672. var u, v, ang, x, y, tmp;
  33673. // default face colors and UV if undefined
  33674. if (flat) {
  33675. for (f = 0; f < nbfaces; f++) {
  33676. if (faceColors && faceColors[f] === undefined) {
  33677. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33678. }
  33679. if (faceUV && faceUV[f] === undefined) {
  33680. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33681. }
  33682. }
  33683. }
  33684. if (!flat) {
  33685. for (i = 0; i < data.vertex.length; i++) {
  33686. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33687. uvs.push(0, 0);
  33688. }
  33689. for (f = 0; f < nbfaces; f++) {
  33690. for (i = 0; i < data.face[f].length - 2; i++) {
  33691. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33692. }
  33693. }
  33694. }
  33695. else {
  33696. for (f = 0; f < nbfaces; f++) {
  33697. var fl = data.face[f].length; // number of vertices of the current face
  33698. ang = 2 * Math.PI / fl;
  33699. x = 0.5 * Math.tan(ang / 2);
  33700. y = 0.5;
  33701. // positions, uvs, colors
  33702. for (i = 0; i < fl; i++) {
  33703. // positions
  33704. 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);
  33705. indexes.push(index);
  33706. index++;
  33707. // uvs
  33708. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33709. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33710. uvs.push(u, v);
  33711. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33712. y = x * Math.sin(ang) + y * Math.cos(ang);
  33713. x = tmp;
  33714. // colors
  33715. if (faceColors) {
  33716. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33717. }
  33718. }
  33719. // indices from indexes
  33720. for (i = 0; i < fl - 2; i++) {
  33721. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33722. }
  33723. faceIdx += fl;
  33724. }
  33725. }
  33726. VertexData.ComputeNormals(positions, indices, normals);
  33727. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33728. var vertexData = new VertexData();
  33729. vertexData.positions = positions;
  33730. vertexData.indices = indices;
  33731. vertexData.normals = normals;
  33732. vertexData.uvs = uvs;
  33733. if (faceColors && flat) {
  33734. vertexData.colors = colors;
  33735. }
  33736. return vertexData;
  33737. };
  33738. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33739. /**
  33740. * Creates the VertexData of the Torus Knot.
  33741. */
  33742. VertexData.CreateTorusKnot = function (options) {
  33743. var indices = new Array();
  33744. var positions = new Array();
  33745. var normals = new Array();
  33746. var uvs = new Array();
  33747. var radius = options.radius || 2;
  33748. var tube = options.tube || 0.5;
  33749. var radialSegments = options.radialSegments || 32;
  33750. var tubularSegments = options.tubularSegments || 32;
  33751. var p = options.p || 2;
  33752. var q = options.q || 3;
  33753. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33754. // Helper
  33755. var getPos = function (angle) {
  33756. var cu = Math.cos(angle);
  33757. var su = Math.sin(angle);
  33758. var quOverP = q / p * angle;
  33759. var cs = Math.cos(quOverP);
  33760. var tx = radius * (2 + cs) * 0.5 * cu;
  33761. var ty = radius * (2 + cs) * su * 0.5;
  33762. var tz = radius * Math.sin(quOverP) * 0.5;
  33763. return new BABYLON.Vector3(tx, ty, tz);
  33764. };
  33765. // Vertices
  33766. var i;
  33767. var j;
  33768. for (i = 0; i <= radialSegments; i++) {
  33769. var modI = i % radialSegments;
  33770. var u = modI / radialSegments * 2 * p * Math.PI;
  33771. var p1 = getPos(u);
  33772. var p2 = getPos(u + 0.01);
  33773. var tang = p2.subtract(p1);
  33774. var n = p2.add(p1);
  33775. var bitan = BABYLON.Vector3.Cross(tang, n);
  33776. n = BABYLON.Vector3.Cross(bitan, tang);
  33777. bitan.normalize();
  33778. n.normalize();
  33779. for (j = 0; j < tubularSegments; j++) {
  33780. var modJ = j % tubularSegments;
  33781. var v = modJ / tubularSegments * 2 * Math.PI;
  33782. var cx = -tube * Math.cos(v);
  33783. var cy = tube * Math.sin(v);
  33784. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33785. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33786. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33787. uvs.push(i / radialSegments);
  33788. uvs.push(j / tubularSegments);
  33789. }
  33790. }
  33791. for (i = 0; i < radialSegments; i++) {
  33792. for (j = 0; j < tubularSegments; j++) {
  33793. var jNext = (j + 1) % tubularSegments;
  33794. var a = i * tubularSegments + j;
  33795. var b = (i + 1) * tubularSegments + j;
  33796. var c = (i + 1) * tubularSegments + jNext;
  33797. var d = i * tubularSegments + jNext;
  33798. indices.push(d);
  33799. indices.push(b);
  33800. indices.push(a);
  33801. indices.push(d);
  33802. indices.push(c);
  33803. indices.push(b);
  33804. }
  33805. }
  33806. // Normals
  33807. VertexData.ComputeNormals(positions, indices, normals);
  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. // Tools
  33819. /**
  33820. * @param {any} - positions (number[] or Float32Array)
  33821. * @param {any} - indices (number[] or Uint16Array)
  33822. * @param {any} - normals (number[] or Float32Array)
  33823. * options (optional) :
  33824. * facetPositions : optional array of facet positions (vector3)
  33825. * facetNormals : optional array of facet normals (vector3)
  33826. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33827. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33828. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33829. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33830. * bInfo : optional bounding info, required for facetPartitioning computation
  33831. * useRightHandedSystem: optional boolean to for right handed system computation
  33832. * depthSort : optional boolean to enable the facet depth sort computation
  33833. * distanceTo : optional Vector3 to compute the facet depth from this location
  33834. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33835. */
  33836. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33837. // temporary scalar variables
  33838. var index = 0; // facet index
  33839. var p1p2x = 0.0; // p1p2 vector x coordinate
  33840. var p1p2y = 0.0; // p1p2 vector y coordinate
  33841. var p1p2z = 0.0; // p1p2 vector z coordinate
  33842. var p3p2x = 0.0; // p3p2 vector x coordinate
  33843. var p3p2y = 0.0; // p3p2 vector y coordinate
  33844. var p3p2z = 0.0; // p3p2 vector z coordinate
  33845. var faceNormalx = 0.0; // facet normal x coordinate
  33846. var faceNormaly = 0.0; // facet normal y coordinate
  33847. var faceNormalz = 0.0; // facet normal z coordinate
  33848. var length = 0.0; // facet normal length before normalization
  33849. var v1x = 0; // vector1 x index in the positions array
  33850. var v1y = 0; // vector1 y index in the positions array
  33851. var v1z = 0; // vector1 z index in the positions array
  33852. var v2x = 0; // vector2 x index in the positions array
  33853. var v2y = 0; // vector2 y index in the positions array
  33854. var v2z = 0; // vector2 z index in the positions array
  33855. var v3x = 0; // vector3 x index in the positions array
  33856. var v3y = 0; // vector3 y index in the positions array
  33857. var v3z = 0; // vector3 z index in the positions array
  33858. var computeFacetNormals = false;
  33859. var computeFacetPositions = false;
  33860. var computeFacetPartitioning = false;
  33861. var computeDepthSort = false;
  33862. var faceNormalSign = 1;
  33863. var ratio = 0;
  33864. var distanceTo = null;
  33865. if (options) {
  33866. computeFacetNormals = (options.facetNormals) ? true : false;
  33867. computeFacetPositions = (options.facetPositions) ? true : false;
  33868. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33869. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33870. ratio = options.ratio || 0;
  33871. computeDepthSort = (options.depthSort) ? true : false;
  33872. distanceTo = (options.distanceTo);
  33873. if (computeDepthSort) {
  33874. if (distanceTo === undefined) {
  33875. distanceTo = BABYLON.Vector3.Zero();
  33876. }
  33877. var depthSortedFacets = options.depthSortedFacets;
  33878. }
  33879. }
  33880. // facetPartitioning reinit if needed
  33881. var xSubRatio = 0;
  33882. var ySubRatio = 0;
  33883. var zSubRatio = 0;
  33884. var subSq = 0;
  33885. if (computeFacetPartitioning && options && options.bbSize) {
  33886. var ox = 0; // X partitioning index for facet position
  33887. var oy = 0; // Y partinioning index for facet position
  33888. var oz = 0; // Z partinioning index for facet position
  33889. var b1x = 0; // X partitioning index for facet v1 vertex
  33890. var b1y = 0; // Y partitioning index for facet v1 vertex
  33891. var b1z = 0; // z partitioning index for facet v1 vertex
  33892. var b2x = 0; // X partitioning index for facet v2 vertex
  33893. var b2y = 0; // Y partitioning index for facet v2 vertex
  33894. var b2z = 0; // Z partitioning index for facet v2 vertex
  33895. var b3x = 0; // X partitioning index for facet v3 vertex
  33896. var b3y = 0; // Y partitioning index for facet v3 vertex
  33897. var b3z = 0; // Z partitioning index for facet v3 vertex
  33898. var block_idx_o = 0; // facet barycenter block index
  33899. var block_idx_v1 = 0; // v1 vertex block index
  33900. var block_idx_v2 = 0; // v2 vertex block index
  33901. var block_idx_v3 = 0; // v3 vertex block index
  33902. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33903. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33904. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33905. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33906. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33907. subSq = options.subDiv.max * options.subDiv.max;
  33908. options.facetPartitioning.length = 0;
  33909. }
  33910. // reset the normals
  33911. for (index = 0; index < positions.length; index++) {
  33912. normals[index] = 0.0;
  33913. }
  33914. // Loop : 1 indice triplet = 1 facet
  33915. var nbFaces = (indices.length / 3) | 0;
  33916. for (index = 0; index < nbFaces; index++) {
  33917. // get the indexes of the coordinates of each vertex of the facet
  33918. v1x = indices[index * 3] * 3;
  33919. v1y = v1x + 1;
  33920. v1z = v1x + 2;
  33921. v2x = indices[index * 3 + 1] * 3;
  33922. v2y = v2x + 1;
  33923. v2z = v2x + 2;
  33924. v3x = indices[index * 3 + 2] * 3;
  33925. v3y = v3x + 1;
  33926. v3z = v3x + 2;
  33927. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33928. p1p2y = positions[v1y] - positions[v2y];
  33929. p1p2z = positions[v1z] - positions[v2z];
  33930. p3p2x = positions[v3x] - positions[v2x];
  33931. p3p2y = positions[v3y] - positions[v2y];
  33932. p3p2z = positions[v3z] - positions[v2z];
  33933. // compute the face normal with the cross product
  33934. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33935. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33936. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33937. // normalize this normal and store it in the array facetData
  33938. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33939. length = (length === 0) ? 1.0 : length;
  33940. faceNormalx /= length;
  33941. faceNormaly /= length;
  33942. faceNormalz /= length;
  33943. if (computeFacetNormals && options) {
  33944. options.facetNormals[index].x = faceNormalx;
  33945. options.facetNormals[index].y = faceNormaly;
  33946. options.facetNormals[index].z = faceNormalz;
  33947. }
  33948. if (computeFacetPositions && options) {
  33949. // compute and the facet barycenter coordinates in the array facetPositions
  33950. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33951. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33952. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33953. }
  33954. if (computeFacetPartitioning && options) {
  33955. // store the facet indexes in arrays in the main facetPartitioning array :
  33956. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33957. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33958. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33959. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33960. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33961. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33962. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33963. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33964. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33965. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33966. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33967. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33968. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33969. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33970. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33971. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33972. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33973. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33974. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33975. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33976. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33977. // push each facet index in each block containing the vertex
  33978. options.facetPartitioning[block_idx_v1].push(index);
  33979. if (block_idx_v2 != block_idx_v1) {
  33980. options.facetPartitioning[block_idx_v2].push(index);
  33981. }
  33982. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33983. options.facetPartitioning[block_idx_v3].push(index);
  33984. }
  33985. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33986. options.facetPartitioning[block_idx_o].push(index);
  33987. }
  33988. }
  33989. if (computeDepthSort && options && options.facetPositions) {
  33990. var dsf = depthSortedFacets[index];
  33991. dsf.ind = index * 3;
  33992. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  33993. }
  33994. // compute the normals anyway
  33995. normals[v1x] += faceNormalx; // accumulate all the normals per face
  33996. normals[v1y] += faceNormaly;
  33997. normals[v1z] += faceNormalz;
  33998. normals[v2x] += faceNormalx;
  33999. normals[v2y] += faceNormaly;
  34000. normals[v2z] += faceNormalz;
  34001. normals[v3x] += faceNormalx;
  34002. normals[v3y] += faceNormaly;
  34003. normals[v3z] += faceNormalz;
  34004. }
  34005. // last normalization of each normal
  34006. for (index = 0; index < normals.length / 3; index++) {
  34007. faceNormalx = normals[index * 3];
  34008. faceNormaly = normals[index * 3 + 1];
  34009. faceNormalz = normals[index * 3 + 2];
  34010. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34011. length = (length === 0) ? 1.0 : length;
  34012. faceNormalx /= length;
  34013. faceNormaly /= length;
  34014. faceNormalz /= length;
  34015. normals[index * 3] = faceNormalx;
  34016. normals[index * 3 + 1] = faceNormaly;
  34017. normals[index * 3 + 2] = faceNormalz;
  34018. }
  34019. };
  34020. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34021. var li = indices.length;
  34022. var ln = normals.length;
  34023. var i;
  34024. var n;
  34025. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34026. switch (sideOrientation) {
  34027. case BABYLON.Mesh.FRONTSIDE:
  34028. // nothing changed
  34029. break;
  34030. case BABYLON.Mesh.BACKSIDE:
  34031. var tmp;
  34032. // indices
  34033. for (i = 0; i < li; i += 3) {
  34034. tmp = indices[i];
  34035. indices[i] = indices[i + 2];
  34036. indices[i + 2] = tmp;
  34037. }
  34038. // normals
  34039. for (n = 0; n < ln; n++) {
  34040. normals[n] = -normals[n];
  34041. }
  34042. break;
  34043. case BABYLON.Mesh.DOUBLESIDE:
  34044. // positions
  34045. var lp = positions.length;
  34046. var l = lp / 3;
  34047. for (var p = 0; p < lp; p++) {
  34048. positions[lp + p] = positions[p];
  34049. }
  34050. // indices
  34051. for (i = 0; i < li; i += 3) {
  34052. indices[i + li] = indices[i + 2] + l;
  34053. indices[i + 1 + li] = indices[i + 1] + l;
  34054. indices[i + 2 + li] = indices[i] + l;
  34055. }
  34056. // normals
  34057. for (n = 0; n < ln; n++) {
  34058. normals[ln + n] = -normals[n];
  34059. }
  34060. // uvs
  34061. var lu = uvs.length;
  34062. var u = 0;
  34063. for (u = 0; u < lu; u++) {
  34064. uvs[u + lu] = uvs[u];
  34065. }
  34066. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34067. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34068. u = 0;
  34069. for (i = 0; i < lu / 2; i++) {
  34070. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34071. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34072. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34073. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34074. u += 2;
  34075. }
  34076. break;
  34077. }
  34078. };
  34079. /**
  34080. * Creates a new VertexData from the imported parameters.
  34081. */
  34082. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34083. var vertexData = new VertexData();
  34084. // positions
  34085. var positions = parsedVertexData.positions;
  34086. if (positions) {
  34087. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34088. }
  34089. // normals
  34090. var normals = parsedVertexData.normals;
  34091. if (normals) {
  34092. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34093. }
  34094. // tangents
  34095. var tangents = parsedVertexData.tangents;
  34096. if (tangents) {
  34097. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34098. }
  34099. // uvs
  34100. var uvs = parsedVertexData.uvs;
  34101. if (uvs) {
  34102. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34103. }
  34104. // uv2s
  34105. var uv2s = parsedVertexData.uv2s;
  34106. if (uv2s) {
  34107. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34108. }
  34109. // uv3s
  34110. var uv3s = parsedVertexData.uv3s;
  34111. if (uv3s) {
  34112. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34113. }
  34114. // uv4s
  34115. var uv4s = parsedVertexData.uv4s;
  34116. if (uv4s) {
  34117. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34118. }
  34119. // uv5s
  34120. var uv5s = parsedVertexData.uv5s;
  34121. if (uv5s) {
  34122. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34123. }
  34124. // uv6s
  34125. var uv6s = parsedVertexData.uv6s;
  34126. if (uv6s) {
  34127. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34128. }
  34129. // colors
  34130. var colors = parsedVertexData.colors;
  34131. if (colors) {
  34132. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34133. }
  34134. // matricesIndices
  34135. var matricesIndices = parsedVertexData.matricesIndices;
  34136. if (matricesIndices) {
  34137. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34138. }
  34139. // matricesWeights
  34140. var matricesWeights = parsedVertexData.matricesWeights;
  34141. if (matricesWeights) {
  34142. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34143. }
  34144. // indices
  34145. var indices = parsedVertexData.indices;
  34146. if (indices) {
  34147. vertexData.indices = indices;
  34148. }
  34149. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34150. };
  34151. return VertexData;
  34152. }());
  34153. BABYLON.VertexData = VertexData;
  34154. })(BABYLON || (BABYLON = {}));
  34155. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34156. var BABYLON;
  34157. (function (BABYLON) {
  34158. /**
  34159. * Class used to store geometry data (vertex buffers + index buffer)
  34160. */
  34161. var Geometry = /** @class */ (function () {
  34162. /**
  34163. * Creates a new geometry
  34164. * @param id defines the unique ID
  34165. * @param scene defines the hosting scene
  34166. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34167. * @param updatable defines if geometry must be updatable (false by default)
  34168. * @param mesh defines the mesh that will be associated with the geometry
  34169. */
  34170. function Geometry(id, scene, vertexData, updatable, mesh) {
  34171. if (updatable === void 0) { updatable = false; }
  34172. if (mesh === void 0) { mesh = null; }
  34173. /**
  34174. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34175. */
  34176. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34177. this._totalVertices = 0;
  34178. this._isDisposed = false;
  34179. this._indexBufferIsUpdatable = false;
  34180. this.id = id;
  34181. this._engine = scene.getEngine();
  34182. this._meshes = [];
  34183. this._scene = scene;
  34184. //Init vertex buffer cache
  34185. this._vertexBuffers = {};
  34186. this._indices = [];
  34187. this._updatable = updatable;
  34188. // vertexData
  34189. if (vertexData) {
  34190. this.setAllVerticesData(vertexData, updatable);
  34191. }
  34192. else {
  34193. this._totalVertices = 0;
  34194. this._indices = [];
  34195. }
  34196. if (this._engine.getCaps().vertexArrayObject) {
  34197. this._vertexArrayObjects = {};
  34198. }
  34199. // applyToMesh
  34200. if (mesh) {
  34201. if (mesh.getClassName() === "LinesMesh") {
  34202. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34203. this.updateExtend();
  34204. }
  34205. this.applyToMesh(mesh);
  34206. mesh.computeWorldMatrix(true);
  34207. }
  34208. }
  34209. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34210. /**
  34211. * 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
  34212. */
  34213. get: function () {
  34214. return this._boundingBias;
  34215. },
  34216. /**
  34217. * 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
  34218. */
  34219. set: function (value) {
  34220. if (this._boundingBias && this._boundingBias.equals(value)) {
  34221. return;
  34222. }
  34223. this._boundingBias = value.clone();
  34224. this.updateBoundingInfo(true, null);
  34225. },
  34226. enumerable: true,
  34227. configurable: true
  34228. });
  34229. /**
  34230. * Static function used to attach a new empty geometry to a mesh
  34231. * @param mesh defines the mesh to attach the geometry to
  34232. * @returns the new {BABYLON.Geometry}
  34233. */
  34234. Geometry.CreateGeometryForMesh = function (mesh) {
  34235. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34236. geometry.applyToMesh(mesh);
  34237. return geometry;
  34238. };
  34239. Object.defineProperty(Geometry.prototype, "extend", {
  34240. /**
  34241. * Gets the current extend of the geometry
  34242. */
  34243. get: function () {
  34244. return this._extend;
  34245. },
  34246. enumerable: true,
  34247. configurable: true
  34248. });
  34249. /**
  34250. * Gets the hosting scene
  34251. * @returns the hosting {BABYLON.Scene}
  34252. */
  34253. Geometry.prototype.getScene = function () {
  34254. return this._scene;
  34255. };
  34256. /**
  34257. * Gets the hosting engine
  34258. * @returns the hosting {BABYLON.Engine}
  34259. */
  34260. Geometry.prototype.getEngine = function () {
  34261. return this._engine;
  34262. };
  34263. /**
  34264. * Defines if the geometry is ready to use
  34265. * @returns true if the geometry is ready to be used
  34266. */
  34267. Geometry.prototype.isReady = function () {
  34268. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34269. };
  34270. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34271. /**
  34272. * Gets a value indicating that the geometry should not be serialized
  34273. */
  34274. get: function () {
  34275. for (var index = 0; index < this._meshes.length; index++) {
  34276. if (!this._meshes[index].doNotSerialize) {
  34277. return false;
  34278. }
  34279. }
  34280. return true;
  34281. },
  34282. enumerable: true,
  34283. configurable: true
  34284. });
  34285. /** @ignore */
  34286. Geometry.prototype._rebuild = function () {
  34287. if (this._vertexArrayObjects) {
  34288. this._vertexArrayObjects = {};
  34289. }
  34290. // Index buffer
  34291. if (this._meshes.length !== 0 && this._indices) {
  34292. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34293. }
  34294. // Vertex buffers
  34295. for (var key in this._vertexBuffers) {
  34296. var vertexBuffer = this._vertexBuffers[key];
  34297. vertexBuffer._rebuild();
  34298. }
  34299. };
  34300. /**
  34301. * Affects all gemetry data in one call
  34302. * @param vertexData defines the geometry data
  34303. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34304. */
  34305. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34306. vertexData.applyToGeometry(this, updatable);
  34307. this.notifyUpdate();
  34308. };
  34309. /**
  34310. * Set specific vertex data
  34311. * @param kind defines the data kind (Position, normal, etc...)
  34312. * @param data defines the vertex data to use
  34313. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34314. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34315. */
  34316. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34317. if (updatable === void 0) { updatable = false; }
  34318. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34319. this.setVerticesBuffer(buffer);
  34320. };
  34321. /**
  34322. * Removes a specific vertex data
  34323. * @param kind defines the data kind (Position, normal, etc...)
  34324. */
  34325. Geometry.prototype.removeVerticesData = function (kind) {
  34326. if (this._vertexBuffers[kind]) {
  34327. this._vertexBuffers[kind].dispose();
  34328. delete this._vertexBuffers[kind];
  34329. }
  34330. };
  34331. /**
  34332. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34333. * @param buffer defines the vertex buffer to use
  34334. */
  34335. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34336. var kind = buffer.getKind();
  34337. if (this._vertexBuffers[kind]) {
  34338. this._vertexBuffers[kind].dispose();
  34339. }
  34340. this._vertexBuffers[kind] = buffer;
  34341. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34342. var data = buffer.getData();
  34343. var stride = buffer.getStrideSize();
  34344. this._totalVertices = data.length / stride;
  34345. this.updateExtend(data, stride);
  34346. this._resetPointsArrayCache();
  34347. var meshes = this._meshes;
  34348. var numOfMeshes = meshes.length;
  34349. for (var index = 0; index < numOfMeshes; index++) {
  34350. var mesh = meshes[index];
  34351. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34352. mesh._createGlobalSubMesh(false);
  34353. mesh.computeWorldMatrix(true);
  34354. }
  34355. }
  34356. this.notifyUpdate(kind);
  34357. if (this._vertexArrayObjects) {
  34358. this._disposeVertexArrayObjects();
  34359. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34360. }
  34361. };
  34362. /**
  34363. * Update a specific vertex buffer
  34364. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34365. * It will do nothing if the buffer is not updatable
  34366. * @param kind defines the data kind (Position, normal, etc...)
  34367. * @param data defines the data to use
  34368. * @param offset defines the offset in the target buffer where to store the data
  34369. */
  34370. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34371. var vertexBuffer = this.getVertexBuffer(kind);
  34372. if (!vertexBuffer) {
  34373. return;
  34374. }
  34375. vertexBuffer.updateDirectly(data, offset);
  34376. this.notifyUpdate(kind);
  34377. };
  34378. /**
  34379. * Update a specific vertex buffer
  34380. * This function will create a new buffer if the current one is not updatable
  34381. * @param kind defines the data kind (Position, normal, etc...)
  34382. * @param data defines the data to use
  34383. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34384. */
  34385. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34386. if (updateExtends === void 0) { updateExtends = false; }
  34387. var vertexBuffer = this.getVertexBuffer(kind);
  34388. if (!vertexBuffer) {
  34389. return;
  34390. }
  34391. vertexBuffer.update(data);
  34392. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34393. var stride = vertexBuffer.getStrideSize();
  34394. this._totalVertices = data.length / stride;
  34395. this.updateBoundingInfo(updateExtends, data);
  34396. }
  34397. this.notifyUpdate(kind);
  34398. };
  34399. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34400. if (updateExtends) {
  34401. this.updateExtend(data);
  34402. }
  34403. var meshes = this._meshes;
  34404. var numOfMeshes = meshes.length;
  34405. this._resetPointsArrayCache();
  34406. for (var index = 0; index < numOfMeshes; index++) {
  34407. var mesh = meshes[index];
  34408. if (updateExtends) {
  34409. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34410. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34411. var subMesh = mesh.subMeshes[subIndex];
  34412. subMesh.refreshBoundingInfo();
  34413. }
  34414. }
  34415. }
  34416. };
  34417. /** @ignore */
  34418. Geometry.prototype._bind = function (effect, indexToBind) {
  34419. if (!effect) {
  34420. return;
  34421. }
  34422. if (indexToBind === undefined) {
  34423. indexToBind = this._indexBuffer;
  34424. }
  34425. var vbs = this.getVertexBuffers();
  34426. if (!vbs) {
  34427. return;
  34428. }
  34429. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34430. this._engine.bindBuffers(vbs, indexToBind, effect);
  34431. return;
  34432. }
  34433. // Using VAO
  34434. if (!this._vertexArrayObjects[effect.key]) {
  34435. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34436. }
  34437. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34438. };
  34439. /**
  34440. * Gets total number of vertices
  34441. * @returns the total number of vertices
  34442. */
  34443. Geometry.prototype.getTotalVertices = function () {
  34444. if (!this.isReady()) {
  34445. return 0;
  34446. }
  34447. return this._totalVertices;
  34448. };
  34449. /**
  34450. * Gets a specific vertex data attached to this geometry
  34451. * @param kind defines the data kind (Position, normal, etc...)
  34452. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34453. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34454. * @returns a float array containing vertex data
  34455. */
  34456. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34457. var vertexBuffer = this.getVertexBuffer(kind);
  34458. if (!vertexBuffer) {
  34459. return null;
  34460. }
  34461. var orig = vertexBuffer.getData();
  34462. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34463. return orig;
  34464. }
  34465. else {
  34466. var len = orig.length;
  34467. var copy = [];
  34468. for (var i = 0; i < len; i++) {
  34469. copy.push(orig[i]);
  34470. }
  34471. return copy;
  34472. }
  34473. };
  34474. /**
  34475. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34476. * @param kind defines the data kind (Position, normal, etc...)
  34477. * @returns true if the vertex buffer with the specified kind is updatable
  34478. */
  34479. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34480. var vb = this._vertexBuffers[kind];
  34481. if (!vb) {
  34482. return false;
  34483. }
  34484. return vb.isUpdatable();
  34485. };
  34486. /**
  34487. * Gets a specific vertex buffer
  34488. * @param kind defines the data kind (Position, normal, etc...)
  34489. * @returns a {BABYLON.VertexBuffer}
  34490. */
  34491. Geometry.prototype.getVertexBuffer = function (kind) {
  34492. if (!this.isReady()) {
  34493. return null;
  34494. }
  34495. return this._vertexBuffers[kind];
  34496. };
  34497. /**
  34498. * Returns all vertex buffers
  34499. * @return an object holding all vertex buffers indexed by kind
  34500. */
  34501. Geometry.prototype.getVertexBuffers = function () {
  34502. if (!this.isReady()) {
  34503. return null;
  34504. }
  34505. return this._vertexBuffers;
  34506. };
  34507. /**
  34508. * Gets a boolean indicating if specific vertex buffer is present
  34509. * @param kind defines the data kind (Position, normal, etc...)
  34510. * @returns true if data is present
  34511. */
  34512. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34513. if (!this._vertexBuffers) {
  34514. if (this._delayInfo) {
  34515. return this._delayInfo.indexOf(kind) !== -1;
  34516. }
  34517. return false;
  34518. }
  34519. return this._vertexBuffers[kind] !== undefined;
  34520. };
  34521. /**
  34522. * Gets a list of all attached data kinds (Position, normal, etc...)
  34523. * @returns a list of string containing all kinds
  34524. */
  34525. Geometry.prototype.getVerticesDataKinds = function () {
  34526. var result = [];
  34527. var kind;
  34528. if (!this._vertexBuffers && this._delayInfo) {
  34529. for (kind in this._delayInfo) {
  34530. result.push(kind);
  34531. }
  34532. }
  34533. else {
  34534. for (kind in this._vertexBuffers) {
  34535. result.push(kind);
  34536. }
  34537. }
  34538. return result;
  34539. };
  34540. /**
  34541. * Update index buffer
  34542. * @param indices defines the indices to store in the index buffer
  34543. * @param offset defines the offset in the target buffer where to store the data
  34544. */
  34545. Geometry.prototype.updateIndices = function (indices, offset) {
  34546. if (!this._indexBuffer) {
  34547. return;
  34548. }
  34549. if (!this._indexBufferIsUpdatable) {
  34550. this.setIndices(indices, null, true);
  34551. }
  34552. else {
  34553. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34554. }
  34555. };
  34556. /**
  34557. * Creates a new index buffer
  34558. * @param indices defines the indices to store in the index buffer
  34559. * @param totalVertices defines the total number of vertices (could be null)
  34560. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34561. */
  34562. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34563. if (totalVertices === void 0) { totalVertices = null; }
  34564. if (updatable === void 0) { updatable = false; }
  34565. if (this._indexBuffer) {
  34566. this._engine._releaseBuffer(this._indexBuffer);
  34567. }
  34568. this._disposeVertexArrayObjects();
  34569. this._indices = indices;
  34570. this._indexBufferIsUpdatable = updatable;
  34571. if (this._meshes.length !== 0 && this._indices) {
  34572. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34573. }
  34574. if (totalVertices != undefined) {
  34575. this._totalVertices = totalVertices;
  34576. }
  34577. var meshes = this._meshes;
  34578. var numOfMeshes = meshes.length;
  34579. for (var index = 0; index < numOfMeshes; index++) {
  34580. meshes[index]._createGlobalSubMesh(true);
  34581. }
  34582. this.notifyUpdate();
  34583. };
  34584. /**
  34585. * Return the total number of indices
  34586. * @returns the total number of indices
  34587. */
  34588. Geometry.prototype.getTotalIndices = function () {
  34589. if (!this.isReady()) {
  34590. return 0;
  34591. }
  34592. return this._indices.length;
  34593. };
  34594. /**
  34595. * Gets the index buffer array
  34596. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34597. * @returns the index buffer array
  34598. */
  34599. Geometry.prototype.getIndices = function (copyWhenShared) {
  34600. if (!this.isReady()) {
  34601. return null;
  34602. }
  34603. var orig = this._indices;
  34604. if (!copyWhenShared || this._meshes.length === 1) {
  34605. return orig;
  34606. }
  34607. else {
  34608. var len = orig.length;
  34609. var copy = [];
  34610. for (var i = 0; i < len; i++) {
  34611. copy.push(orig[i]);
  34612. }
  34613. return copy;
  34614. }
  34615. };
  34616. /**
  34617. * Gets the index buffer
  34618. * @return the index buffer
  34619. */
  34620. Geometry.prototype.getIndexBuffer = function () {
  34621. if (!this.isReady()) {
  34622. return null;
  34623. }
  34624. return this._indexBuffer;
  34625. };
  34626. /** @ignore */
  34627. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34628. if (effect === void 0) { effect = null; }
  34629. if (!effect || !this._vertexArrayObjects) {
  34630. return;
  34631. }
  34632. if (this._vertexArrayObjects[effect.key]) {
  34633. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34634. delete this._vertexArrayObjects[effect.key];
  34635. }
  34636. };
  34637. /**
  34638. * Release the associated resources for a specific mesh
  34639. * @param mesh defines the source mesh
  34640. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34641. */
  34642. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34643. var meshes = this._meshes;
  34644. var index = meshes.indexOf(mesh);
  34645. if (index === -1) {
  34646. return;
  34647. }
  34648. meshes.splice(index, 1);
  34649. mesh._geometry = null;
  34650. if (meshes.length === 0 && shouldDispose) {
  34651. this.dispose();
  34652. }
  34653. };
  34654. /**
  34655. * Apply current geometry to a given mesh
  34656. * @param mesh defines the mesh to apply geometry to
  34657. */
  34658. Geometry.prototype.applyToMesh = function (mesh) {
  34659. if (mesh._geometry === this) {
  34660. return;
  34661. }
  34662. var previousGeometry = mesh._geometry;
  34663. if (previousGeometry) {
  34664. previousGeometry.releaseForMesh(mesh);
  34665. }
  34666. var meshes = this._meshes;
  34667. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34668. mesh._geometry = this;
  34669. this._scene.pushGeometry(this);
  34670. meshes.push(mesh);
  34671. if (this.isReady()) {
  34672. this._applyToMesh(mesh);
  34673. }
  34674. else {
  34675. mesh._boundingInfo = this._boundingInfo;
  34676. }
  34677. };
  34678. Geometry.prototype.updateExtend = function (data, stride) {
  34679. if (data === void 0) { data = null; }
  34680. if (!data) {
  34681. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34682. }
  34683. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34684. };
  34685. Geometry.prototype._applyToMesh = function (mesh) {
  34686. var numOfMeshes = this._meshes.length;
  34687. // vertexBuffers
  34688. for (var kind in this._vertexBuffers) {
  34689. if (numOfMeshes === 1) {
  34690. this._vertexBuffers[kind].create();
  34691. }
  34692. var buffer = this._vertexBuffers[kind].getBuffer();
  34693. if (buffer)
  34694. buffer.references = numOfMeshes;
  34695. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34696. if (!this._extend) {
  34697. this.updateExtend(this._vertexBuffers[kind].getData());
  34698. }
  34699. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34700. mesh._createGlobalSubMesh(false);
  34701. //bounding info was just created again, world matrix should be applied again.
  34702. mesh._updateBoundingInfo();
  34703. }
  34704. }
  34705. // indexBuffer
  34706. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34707. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34708. }
  34709. if (this._indexBuffer) {
  34710. this._indexBuffer.references = numOfMeshes;
  34711. }
  34712. };
  34713. Geometry.prototype.notifyUpdate = function (kind) {
  34714. if (this.onGeometryUpdated) {
  34715. this.onGeometryUpdated(this, kind);
  34716. }
  34717. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34718. var mesh = _a[_i];
  34719. mesh._markSubMeshesAsAttributesDirty();
  34720. }
  34721. };
  34722. /**
  34723. * Load the geometry if it was flagged as delay loaded
  34724. * @param scene defines the hosting scene
  34725. * @param onLoaded defines a callback called when the geometry is loaded
  34726. */
  34727. Geometry.prototype.load = function (scene, onLoaded) {
  34728. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34729. return;
  34730. }
  34731. if (this.isReady()) {
  34732. if (onLoaded) {
  34733. onLoaded();
  34734. }
  34735. return;
  34736. }
  34737. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34738. this._queueLoad(scene, onLoaded);
  34739. };
  34740. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34741. var _this = this;
  34742. if (!this.delayLoadingFile) {
  34743. return;
  34744. }
  34745. scene._addPendingData(this);
  34746. scene._loadFile(this.delayLoadingFile, function (data) {
  34747. if (!_this._delayLoadingFunction) {
  34748. return;
  34749. }
  34750. _this._delayLoadingFunction(JSON.parse(data), _this);
  34751. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34752. _this._delayInfo = [];
  34753. scene._removePendingData(_this);
  34754. var meshes = _this._meshes;
  34755. var numOfMeshes = meshes.length;
  34756. for (var index = 0; index < numOfMeshes; index++) {
  34757. _this._applyToMesh(meshes[index]);
  34758. }
  34759. if (onLoaded) {
  34760. onLoaded();
  34761. }
  34762. }, undefined, true);
  34763. };
  34764. /**
  34765. * Invert the geometry to move from a right handed system to a left handed one.
  34766. */
  34767. Geometry.prototype.toLeftHanded = function () {
  34768. // Flip faces
  34769. var tIndices = this.getIndices(false);
  34770. if (tIndices != null && tIndices.length > 0) {
  34771. for (var i = 0; i < tIndices.length; i += 3) {
  34772. var tTemp = tIndices[i + 0];
  34773. tIndices[i + 0] = tIndices[i + 2];
  34774. tIndices[i + 2] = tTemp;
  34775. }
  34776. this.setIndices(tIndices);
  34777. }
  34778. // Negate position.z
  34779. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34780. if (tPositions != null && tPositions.length > 0) {
  34781. for (var i = 0; i < tPositions.length; i += 3) {
  34782. tPositions[i + 2] = -tPositions[i + 2];
  34783. }
  34784. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34785. }
  34786. // Negate normal.z
  34787. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34788. if (tNormals != null && tNormals.length > 0) {
  34789. for (var i = 0; i < tNormals.length; i += 3) {
  34790. tNormals[i + 2] = -tNormals[i + 2];
  34791. }
  34792. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34793. }
  34794. };
  34795. // Cache
  34796. /** @ignore */
  34797. Geometry.prototype._resetPointsArrayCache = function () {
  34798. this._positions = null;
  34799. };
  34800. /** @ignore */
  34801. Geometry.prototype._generatePointsArray = function () {
  34802. if (this._positions)
  34803. return true;
  34804. this._positions = [];
  34805. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34806. if (!data) {
  34807. return false;
  34808. }
  34809. for (var index = 0; index < data.length; index += 3) {
  34810. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34811. }
  34812. return true;
  34813. };
  34814. /**
  34815. * Gets a value indicating if the geometry is disposed
  34816. * @returns true if the geometry was disposed
  34817. */
  34818. Geometry.prototype.isDisposed = function () {
  34819. return this._isDisposed;
  34820. };
  34821. Geometry.prototype._disposeVertexArrayObjects = function () {
  34822. if (this._vertexArrayObjects) {
  34823. for (var kind in this._vertexArrayObjects) {
  34824. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34825. }
  34826. this._vertexArrayObjects = {};
  34827. }
  34828. };
  34829. /**
  34830. * Free all associated resources
  34831. */
  34832. Geometry.prototype.dispose = function () {
  34833. var meshes = this._meshes;
  34834. var numOfMeshes = meshes.length;
  34835. var index;
  34836. for (index = 0; index < numOfMeshes; index++) {
  34837. this.releaseForMesh(meshes[index]);
  34838. }
  34839. this._meshes = [];
  34840. this._disposeVertexArrayObjects();
  34841. for (var kind in this._vertexBuffers) {
  34842. this._vertexBuffers[kind].dispose();
  34843. }
  34844. this._vertexBuffers = {};
  34845. this._totalVertices = 0;
  34846. if (this._indexBuffer) {
  34847. this._engine._releaseBuffer(this._indexBuffer);
  34848. }
  34849. this._indexBuffer = null;
  34850. this._indices = [];
  34851. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34852. this.delayLoadingFile = null;
  34853. this._delayLoadingFunction = null;
  34854. this._delayInfo = [];
  34855. this._boundingInfo = null;
  34856. this._scene.removeGeometry(this);
  34857. this._isDisposed = true;
  34858. };
  34859. /**
  34860. * Clone the current geometry into a new geometry
  34861. * @param id defines the unique ID of the new geometry
  34862. * @returns a new geometry object
  34863. */
  34864. Geometry.prototype.copy = function (id) {
  34865. var vertexData = new BABYLON.VertexData();
  34866. vertexData.indices = [];
  34867. var indices = this.getIndices();
  34868. if (indices) {
  34869. for (var index = 0; index < indices.length; index++) {
  34870. vertexData.indices.push(indices[index]);
  34871. }
  34872. }
  34873. var updatable = false;
  34874. var stopChecking = false;
  34875. var kind;
  34876. for (kind in this._vertexBuffers) {
  34877. // using slice() to make a copy of the array and not just reference it
  34878. var data = this.getVerticesData(kind);
  34879. if (data instanceof Float32Array) {
  34880. vertexData.set(new Float32Array(data), kind);
  34881. }
  34882. else {
  34883. vertexData.set(data.slice(0), kind);
  34884. }
  34885. if (!stopChecking) {
  34886. var vb = this.getVertexBuffer(kind);
  34887. if (vb) {
  34888. updatable = vb.isUpdatable();
  34889. stopChecking = !updatable;
  34890. }
  34891. }
  34892. }
  34893. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34894. geometry.delayLoadState = this.delayLoadState;
  34895. geometry.delayLoadingFile = this.delayLoadingFile;
  34896. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34897. for (kind in this._delayInfo) {
  34898. geometry._delayInfo = geometry._delayInfo || [];
  34899. geometry._delayInfo.push(kind);
  34900. }
  34901. // Bounding info
  34902. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34903. return geometry;
  34904. };
  34905. /**
  34906. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34907. * @return a JSON representation of the current geometry data (without the vertices data)
  34908. */
  34909. Geometry.prototype.serialize = function () {
  34910. var serializationObject = {};
  34911. serializationObject.id = this.id;
  34912. serializationObject.updatable = this._updatable;
  34913. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34914. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34915. }
  34916. return serializationObject;
  34917. };
  34918. Geometry.prototype.toNumberArray = function (origin) {
  34919. if (Array.isArray(origin)) {
  34920. return origin;
  34921. }
  34922. else {
  34923. return Array.prototype.slice.call(origin);
  34924. }
  34925. };
  34926. /**
  34927. * Serialize all vertices data into a JSON oject
  34928. * @returns a JSON representation of the current geometry data
  34929. */
  34930. Geometry.prototype.serializeVerticeData = function () {
  34931. var serializationObject = this.serialize();
  34932. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34933. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34934. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34935. serializationObject.positions._updatable = true;
  34936. }
  34937. }
  34938. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34939. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34940. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34941. serializationObject.normals._updatable = true;
  34942. }
  34943. }
  34944. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34945. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34946. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34947. serializationObject.tangets._updatable = true;
  34948. }
  34949. }
  34950. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34951. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34952. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34953. serializationObject.uvs._updatable = true;
  34954. }
  34955. }
  34956. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34957. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34958. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34959. serializationObject.uv2s._updatable = true;
  34960. }
  34961. }
  34962. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34963. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34964. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34965. serializationObject.uv3s._updatable = true;
  34966. }
  34967. }
  34968. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34969. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34970. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34971. serializationObject.uv4s._updatable = true;
  34972. }
  34973. }
  34974. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34975. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34976. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34977. serializationObject.uv5s._updatable = true;
  34978. }
  34979. }
  34980. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34981. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34982. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34983. serializationObject.uv6s._updatable = true;
  34984. }
  34985. }
  34986. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34987. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34988. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34989. serializationObject.colors._updatable = true;
  34990. }
  34991. }
  34992. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34993. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  34994. serializationObject.matricesIndices._isExpanded = true;
  34995. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34996. serializationObject.matricesIndices._updatable = true;
  34997. }
  34998. }
  34999. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35000. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35001. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35002. serializationObject.matricesWeights._updatable = true;
  35003. }
  35004. }
  35005. serializationObject.indices = this.toNumberArray(this.getIndices());
  35006. return serializationObject;
  35007. };
  35008. // Statics
  35009. /**
  35010. * Extracts a clone of a mesh geometry
  35011. * @param mesh defines the source mesh
  35012. * @param id defines the unique ID of the new geometry object
  35013. * @returns the new geometry object
  35014. */
  35015. Geometry.ExtractFromMesh = function (mesh, id) {
  35016. var geometry = mesh._geometry;
  35017. if (!geometry) {
  35018. return null;
  35019. }
  35020. return geometry.copy(id);
  35021. };
  35022. /**
  35023. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35024. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35025. * Be aware Math.random() could cause collisions, but:
  35026. * "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"
  35027. * @returns a string containing a new GUID
  35028. */
  35029. Geometry.RandomId = function () {
  35030. return BABYLON.Tools.RandomId();
  35031. };
  35032. /** @ignore */
  35033. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35034. var scene = mesh.getScene();
  35035. // Geometry
  35036. var geometryId = parsedGeometry.geometryId;
  35037. if (geometryId) {
  35038. var geometry = scene.getGeometryByID(geometryId);
  35039. if (geometry) {
  35040. geometry.applyToMesh(mesh);
  35041. }
  35042. }
  35043. else if (parsedGeometry instanceof ArrayBuffer) {
  35044. var binaryInfo = mesh._binaryInfo;
  35045. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35046. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35047. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35048. }
  35049. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35050. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35051. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35052. }
  35053. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35054. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35055. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35056. }
  35057. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35058. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35059. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35060. }
  35061. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35062. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35063. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35064. }
  35065. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35066. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35067. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35068. }
  35069. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35070. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35071. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35072. }
  35073. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35074. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35075. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35076. }
  35077. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35078. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35079. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35080. }
  35081. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35082. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35083. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35084. }
  35085. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35086. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35087. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35088. }
  35089. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35090. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35091. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35092. }
  35093. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35094. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35095. mesh.setIndices(indicesData, null);
  35096. }
  35097. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35098. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35099. mesh.subMeshes = [];
  35100. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35101. var materialIndex = subMeshesData[(i * 5) + 0];
  35102. var verticesStart = subMeshesData[(i * 5) + 1];
  35103. var verticesCount = subMeshesData[(i * 5) + 2];
  35104. var indexStart = subMeshesData[(i * 5) + 3];
  35105. var indexCount = subMeshesData[(i * 5) + 4];
  35106. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35107. }
  35108. }
  35109. }
  35110. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35111. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35112. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35113. if (parsedGeometry.tangents) {
  35114. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35115. }
  35116. if (parsedGeometry.uvs) {
  35117. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35118. }
  35119. if (parsedGeometry.uvs2) {
  35120. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35121. }
  35122. if (parsedGeometry.uvs3) {
  35123. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35124. }
  35125. if (parsedGeometry.uvs4) {
  35126. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35127. }
  35128. if (parsedGeometry.uvs5) {
  35129. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35130. }
  35131. if (parsedGeometry.uvs6) {
  35132. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35133. }
  35134. if (parsedGeometry.colors) {
  35135. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35136. }
  35137. if (parsedGeometry.matricesIndices) {
  35138. if (!parsedGeometry.matricesIndices._isExpanded) {
  35139. var floatIndices = [];
  35140. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35141. var matricesIndex = parsedGeometry.matricesIndices[i];
  35142. floatIndices.push(matricesIndex & 0x000000FF);
  35143. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35144. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35145. floatIndices.push(matricesIndex >> 24);
  35146. }
  35147. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35148. }
  35149. else {
  35150. delete parsedGeometry.matricesIndices._isExpanded;
  35151. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35152. }
  35153. }
  35154. if (parsedGeometry.matricesIndicesExtra) {
  35155. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35156. var floatIndices = [];
  35157. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35158. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35159. floatIndices.push(matricesIndex & 0x000000FF);
  35160. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35161. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35162. floatIndices.push(matricesIndex >> 24);
  35163. }
  35164. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35165. }
  35166. else {
  35167. delete parsedGeometry.matricesIndices._isExpanded;
  35168. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35169. }
  35170. }
  35171. if (parsedGeometry.matricesWeights) {
  35172. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35174. }
  35175. if (parsedGeometry.matricesWeightsExtra) {
  35176. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35177. }
  35178. mesh.setIndices(parsedGeometry.indices, null);
  35179. }
  35180. // SubMeshes
  35181. if (parsedGeometry.subMeshes) {
  35182. mesh.subMeshes = [];
  35183. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35184. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35185. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35186. }
  35187. }
  35188. // Flat shading
  35189. if (mesh._shouldGenerateFlatShading) {
  35190. mesh.convertToFlatShadedMesh();
  35191. delete mesh._shouldGenerateFlatShading;
  35192. }
  35193. // Update
  35194. mesh.computeWorldMatrix(true);
  35195. // Octree
  35196. var sceneOctree = scene.selectionOctree;
  35197. if (sceneOctree !== undefined && sceneOctree !== null) {
  35198. sceneOctree.addMesh(mesh);
  35199. }
  35200. };
  35201. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35202. var epsilon = 1e-3;
  35203. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35204. return;
  35205. }
  35206. var noInfluenceBoneIndex = 0.0;
  35207. if (parsedGeometry.skeletonId > -1) {
  35208. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35209. if (!skeleton) {
  35210. return;
  35211. }
  35212. noInfluenceBoneIndex = skeleton.bones.length;
  35213. }
  35214. else {
  35215. return;
  35216. }
  35217. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35218. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35219. var matricesWeights = parsedGeometry.matricesWeights;
  35220. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35221. var influencers = parsedGeometry.numBoneInfluencer;
  35222. var size = matricesWeights.length;
  35223. for (var i = 0; i < size; i += 4) {
  35224. var weight = 0.0;
  35225. var firstZeroWeight = -1;
  35226. for (var j = 0; j < 4; j++) {
  35227. var w = matricesWeights[i + j];
  35228. weight += w;
  35229. if (w < epsilon && firstZeroWeight < 0) {
  35230. firstZeroWeight = j;
  35231. }
  35232. }
  35233. if (matricesWeightsExtra) {
  35234. for (var j = 0; j < 4; j++) {
  35235. var w = matricesWeightsExtra[i + j];
  35236. weight += w;
  35237. if (w < epsilon && firstZeroWeight < 0) {
  35238. firstZeroWeight = j + 4;
  35239. }
  35240. }
  35241. }
  35242. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35243. firstZeroWeight = influencers - 1;
  35244. }
  35245. if (weight > epsilon) {
  35246. var mweight = 1.0 / weight;
  35247. for (var j = 0; j < 4; j++) {
  35248. matricesWeights[i + j] *= mweight;
  35249. }
  35250. if (matricesWeightsExtra) {
  35251. for (var j = 0; j < 4; j++) {
  35252. matricesWeightsExtra[i + j] *= mweight;
  35253. }
  35254. }
  35255. }
  35256. else {
  35257. if (firstZeroWeight >= 4) {
  35258. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35259. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35260. }
  35261. else {
  35262. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35263. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35264. }
  35265. }
  35266. }
  35267. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35268. if (parsedGeometry.matricesWeightsExtra) {
  35269. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35270. }
  35271. };
  35272. /**
  35273. * Create a new geometry from persisted data (Using .babylon file format)
  35274. * @param parsedVertexData defines the persisted data
  35275. * @param scene defines the hosting scene
  35276. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35277. * @returns the new geometry object
  35278. */
  35279. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35280. if (scene.getGeometryByID(parsedVertexData.id)) {
  35281. return null; // null since geometry could be something else than a box...
  35282. }
  35283. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35284. if (BABYLON.Tags) {
  35285. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35286. }
  35287. if (parsedVertexData.delayLoadingFile) {
  35288. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35289. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35290. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35291. geometry._delayInfo = [];
  35292. if (parsedVertexData.hasUVs) {
  35293. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35294. }
  35295. if (parsedVertexData.hasUVs2) {
  35296. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35297. }
  35298. if (parsedVertexData.hasUVs3) {
  35299. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35300. }
  35301. if (parsedVertexData.hasUVs4) {
  35302. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35303. }
  35304. if (parsedVertexData.hasUVs5) {
  35305. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35306. }
  35307. if (parsedVertexData.hasUVs6) {
  35308. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35309. }
  35310. if (parsedVertexData.hasColors) {
  35311. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35312. }
  35313. if (parsedVertexData.hasMatricesIndices) {
  35314. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35315. }
  35316. if (parsedVertexData.hasMatricesWeights) {
  35317. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35318. }
  35319. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35320. }
  35321. else {
  35322. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35323. }
  35324. scene.pushGeometry(geometry, true);
  35325. return geometry;
  35326. };
  35327. return Geometry;
  35328. }());
  35329. BABYLON.Geometry = Geometry;
  35330. // Primitives
  35331. /// Abstract class
  35332. /**
  35333. * Abstract class used to provide common services for all typed geometries
  35334. */
  35335. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35336. __extends(_PrimitiveGeometry, _super);
  35337. /**
  35338. * Creates a new typed geometry
  35339. * @param id defines the unique ID of the geometry
  35340. * @param scene defines the hosting scene
  35341. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35342. * @param mesh defines the hosting mesh (can be null)
  35343. */
  35344. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35345. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35346. if (mesh === void 0) { mesh = null; }
  35347. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35348. _this._canBeRegenerated = _canBeRegenerated;
  35349. _this._beingRegenerated = true;
  35350. _this.regenerate();
  35351. _this._beingRegenerated = false;
  35352. return _this;
  35353. }
  35354. /**
  35355. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35356. * @returns true if the geometry can be regenerated
  35357. */
  35358. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35359. return this._canBeRegenerated;
  35360. };
  35361. /**
  35362. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35363. */
  35364. _PrimitiveGeometry.prototype.regenerate = function () {
  35365. if (!this._canBeRegenerated) {
  35366. return;
  35367. }
  35368. this._beingRegenerated = true;
  35369. this.setAllVerticesData(this._regenerateVertexData(), false);
  35370. this._beingRegenerated = false;
  35371. };
  35372. /**
  35373. * Clone the geometry
  35374. * @param id defines the unique ID of the new geometry
  35375. * @returns the new geometry
  35376. */
  35377. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35378. return _super.prototype.copy.call(this, id);
  35379. };
  35380. // overrides
  35381. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35382. if (!this._beingRegenerated) {
  35383. return;
  35384. }
  35385. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35386. };
  35387. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35388. if (!this._beingRegenerated) {
  35389. return;
  35390. }
  35391. _super.prototype.setVerticesData.call(this, kind, data, false);
  35392. };
  35393. // to override
  35394. /** @ignore */
  35395. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35396. throw new Error("Abstract method");
  35397. };
  35398. _PrimitiveGeometry.prototype.copy = function (id) {
  35399. throw new Error("Must be overriden in sub-classes.");
  35400. };
  35401. _PrimitiveGeometry.prototype.serialize = function () {
  35402. var serializationObject = _super.prototype.serialize.call(this);
  35403. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35404. return serializationObject;
  35405. };
  35406. return _PrimitiveGeometry;
  35407. }(Geometry));
  35408. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35409. /**
  35410. * Creates a ribbon geometry
  35411. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35412. */
  35413. var RibbonGeometry = /** @class */ (function (_super) {
  35414. __extends(RibbonGeometry, _super);
  35415. /**
  35416. * Creates a ribbon geometry
  35417. * @param id defines the unique ID of the geometry
  35418. * @param scene defines the hosting scene
  35419. * @param pathArray defines the array of paths to use
  35420. * @param closeArray defines if the last path and the first path must be joined
  35421. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35422. * @param offset defines the offset between points
  35423. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35424. * @param mesh defines the hosting mesh (can be null)
  35425. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35426. */
  35427. function RibbonGeometry(id, scene,
  35428. /**
  35429. * Defines the array of paths to use
  35430. */
  35431. pathArray,
  35432. /**
  35433. * Defines if the last and first points of each path in your pathArray must be joined
  35434. */
  35435. closeArray,
  35436. /**
  35437. * Defines if the last and first points of each path in your pathArray must be joined
  35438. */
  35439. closePath,
  35440. /**
  35441. * Defines the offset between points
  35442. */
  35443. offset, canBeRegenerated, mesh,
  35444. /**
  35445. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35446. */
  35447. side) {
  35448. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35449. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35450. _this.pathArray = pathArray;
  35451. _this.closeArray = closeArray;
  35452. _this.closePath = closePath;
  35453. _this.offset = offset;
  35454. _this.side = side;
  35455. return _this;
  35456. }
  35457. /** @ignore */
  35458. RibbonGeometry.prototype._regenerateVertexData = function () {
  35459. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35460. };
  35461. RibbonGeometry.prototype.copy = function (id) {
  35462. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35463. };
  35464. return RibbonGeometry;
  35465. }(_PrimitiveGeometry));
  35466. BABYLON.RibbonGeometry = RibbonGeometry;
  35467. /**
  35468. * Creates a box geometry
  35469. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35470. */
  35471. var BoxGeometry = /** @class */ (function (_super) {
  35472. __extends(BoxGeometry, _super);
  35473. /**
  35474. * Creates a box geometry
  35475. * @param id defines the unique ID of the geometry
  35476. * @param scene defines the hosting scene
  35477. * @param size defines the zise of the box (width, height and depth are the same)
  35478. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35479. * @param mesh defines the hosting mesh (can be null)
  35480. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35481. */
  35482. function BoxGeometry(id, scene,
  35483. /**
  35484. * Defines the zise of the box (width, height and depth are the same)
  35485. */
  35486. size, canBeRegenerated, mesh,
  35487. /**
  35488. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35489. */
  35490. side) {
  35491. if (mesh === void 0) { mesh = null; }
  35492. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35493. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35494. _this.size = size;
  35495. _this.side = side;
  35496. return _this;
  35497. }
  35498. BoxGeometry.prototype._regenerateVertexData = function () {
  35499. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35500. };
  35501. BoxGeometry.prototype.copy = function (id) {
  35502. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35503. };
  35504. BoxGeometry.prototype.serialize = function () {
  35505. var serializationObject = _super.prototype.serialize.call(this);
  35506. serializationObject.size = this.size;
  35507. return serializationObject;
  35508. };
  35509. BoxGeometry.Parse = function (parsedBox, scene) {
  35510. if (scene.getGeometryByID(parsedBox.id)) {
  35511. return null; // null since geometry could be something else than a box...
  35512. }
  35513. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35514. if (BABYLON.Tags) {
  35515. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35516. }
  35517. scene.pushGeometry(box, true);
  35518. return box;
  35519. };
  35520. return BoxGeometry;
  35521. }(_PrimitiveGeometry));
  35522. BABYLON.BoxGeometry = BoxGeometry;
  35523. /**
  35524. * Creates a sphere geometry
  35525. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35526. */
  35527. var SphereGeometry = /** @class */ (function (_super) {
  35528. __extends(SphereGeometry, _super);
  35529. /**
  35530. * Create a new sphere geometry
  35531. * @param id defines the unique ID of the geometry
  35532. * @param scene defines the hosting scene
  35533. * @param segments defines the number of segments to use to create the sphere
  35534. * @param diameter defines the diameter of the sphere
  35535. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35536. * @param mesh defines the hosting mesh (can be null)
  35537. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35538. */
  35539. function SphereGeometry(id, scene,
  35540. /**
  35541. * Defines the number of segments to use to create the sphere
  35542. */
  35543. segments,
  35544. /**
  35545. * Defines the diameter of the sphere
  35546. */
  35547. diameter, canBeRegenerated, mesh,
  35548. /**
  35549. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35550. */
  35551. side) {
  35552. if (mesh === void 0) { mesh = null; }
  35553. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35554. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35555. _this.segments = segments;
  35556. _this.diameter = diameter;
  35557. _this.side = side;
  35558. return _this;
  35559. }
  35560. SphereGeometry.prototype._regenerateVertexData = function () {
  35561. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35562. };
  35563. SphereGeometry.prototype.copy = function (id) {
  35564. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35565. };
  35566. SphereGeometry.prototype.serialize = function () {
  35567. var serializationObject = _super.prototype.serialize.call(this);
  35568. serializationObject.segments = this.segments;
  35569. serializationObject.diameter = this.diameter;
  35570. return serializationObject;
  35571. };
  35572. SphereGeometry.Parse = function (parsedSphere, scene) {
  35573. if (scene.getGeometryByID(parsedSphere.id)) {
  35574. return null; // null since geometry could be something else than a sphere...
  35575. }
  35576. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35577. if (BABYLON.Tags) {
  35578. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35579. }
  35580. scene.pushGeometry(sphere, true);
  35581. return sphere;
  35582. };
  35583. return SphereGeometry;
  35584. }(_PrimitiveGeometry));
  35585. BABYLON.SphereGeometry = SphereGeometry;
  35586. /**
  35587. * Creates a disc geometry
  35588. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35589. */
  35590. var DiscGeometry = /** @class */ (function (_super) {
  35591. __extends(DiscGeometry, _super);
  35592. /**
  35593. * Creates a new disc geometry
  35594. * @param id defines the unique ID of the geometry
  35595. * @param scene defines the hosting scene
  35596. * @param radius defines the radius of the disc
  35597. * @param tessellation defines the tesselation factor to apply to the disc
  35598. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35599. * @param mesh defines the hosting mesh (can be null)
  35600. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35601. */
  35602. function DiscGeometry(id, scene,
  35603. /**
  35604. * Defines the radius of the disc
  35605. */
  35606. radius,
  35607. /**
  35608. * Defines the tesselation factor to apply to the disc
  35609. */
  35610. tessellation, canBeRegenerated, mesh,
  35611. /**
  35612. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35613. */
  35614. side) {
  35615. if (mesh === void 0) { mesh = null; }
  35616. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35617. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35618. _this.radius = radius;
  35619. _this.tessellation = tessellation;
  35620. _this.side = side;
  35621. return _this;
  35622. }
  35623. DiscGeometry.prototype._regenerateVertexData = function () {
  35624. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35625. };
  35626. DiscGeometry.prototype.copy = function (id) {
  35627. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35628. };
  35629. return DiscGeometry;
  35630. }(_PrimitiveGeometry));
  35631. BABYLON.DiscGeometry = DiscGeometry;
  35632. /**
  35633. * Creates a new cylinder geometry
  35634. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35635. */
  35636. var CylinderGeometry = /** @class */ (function (_super) {
  35637. __extends(CylinderGeometry, _super);
  35638. /**
  35639. * Creates a new cylinder geometry
  35640. * @param id defines the unique ID of the geometry
  35641. * @param scene defines the hosting scene
  35642. * @param height defines the height of the cylinder
  35643. * @param diameterTop defines the diameter of the cylinder's top cap
  35644. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35645. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35646. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35647. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35648. * @param mesh defines the hosting mesh (can be null)
  35649. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35650. */
  35651. function CylinderGeometry(id, scene,
  35652. /**
  35653. * Defines the height of the cylinder
  35654. */
  35655. height,
  35656. /**
  35657. * Defines the diameter of the cylinder's top cap
  35658. */
  35659. diameterTop,
  35660. /**
  35661. * Defines the diameter of the cylinder's bottom cap
  35662. */
  35663. diameterBottom,
  35664. /**
  35665. * Defines the tessellation factor to apply to the cylinder
  35666. */
  35667. tessellation,
  35668. /**
  35669. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35670. */
  35671. subdivisions, canBeRegenerated, mesh,
  35672. /**
  35673. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35674. */
  35675. side) {
  35676. if (subdivisions === void 0) { subdivisions = 1; }
  35677. if (mesh === void 0) { mesh = null; }
  35678. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35679. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35680. _this.height = height;
  35681. _this.diameterTop = diameterTop;
  35682. _this.diameterBottom = diameterBottom;
  35683. _this.tessellation = tessellation;
  35684. _this.subdivisions = subdivisions;
  35685. _this.side = side;
  35686. return _this;
  35687. }
  35688. CylinderGeometry.prototype._regenerateVertexData = function () {
  35689. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35690. };
  35691. CylinderGeometry.prototype.copy = function (id) {
  35692. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35693. };
  35694. CylinderGeometry.prototype.serialize = function () {
  35695. var serializationObject = _super.prototype.serialize.call(this);
  35696. serializationObject.height = this.height;
  35697. serializationObject.diameterTop = this.diameterTop;
  35698. serializationObject.diameterBottom = this.diameterBottom;
  35699. serializationObject.tessellation = this.tessellation;
  35700. return serializationObject;
  35701. };
  35702. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35703. if (scene.getGeometryByID(parsedCylinder.id)) {
  35704. return null; // null since geometry could be something else than a cylinder...
  35705. }
  35706. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35707. if (BABYLON.Tags) {
  35708. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35709. }
  35710. scene.pushGeometry(cylinder, true);
  35711. return cylinder;
  35712. };
  35713. return CylinderGeometry;
  35714. }(_PrimitiveGeometry));
  35715. BABYLON.CylinderGeometry = CylinderGeometry;
  35716. /**
  35717. * Creates a new torus geometry
  35718. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35719. */
  35720. var TorusGeometry = /** @class */ (function (_super) {
  35721. __extends(TorusGeometry, _super);
  35722. /**
  35723. * Creates a new torus geometry
  35724. * @param id defines the unique ID of the geometry
  35725. * @param scene defines the hosting scene
  35726. * @param diameter defines the diameter of the torus
  35727. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35728. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35729. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35730. * @param mesh defines the hosting mesh (can be null)
  35731. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35732. */
  35733. function TorusGeometry(id, scene,
  35734. /**
  35735. * Defines the diameter of the torus
  35736. */
  35737. diameter,
  35738. /**
  35739. * Defines the thickness of the torus (ie. internal diameter)
  35740. */
  35741. thickness,
  35742. /**
  35743. * Defines the tesselation factor to apply to the torus
  35744. */
  35745. tessellation, canBeRegenerated, mesh,
  35746. /**
  35747. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35748. */
  35749. side) {
  35750. if (mesh === void 0) { mesh = null; }
  35751. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35752. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35753. _this.diameter = diameter;
  35754. _this.thickness = thickness;
  35755. _this.tessellation = tessellation;
  35756. _this.side = side;
  35757. return _this;
  35758. }
  35759. TorusGeometry.prototype._regenerateVertexData = function () {
  35760. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35761. };
  35762. TorusGeometry.prototype.copy = function (id) {
  35763. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35764. };
  35765. TorusGeometry.prototype.serialize = function () {
  35766. var serializationObject = _super.prototype.serialize.call(this);
  35767. serializationObject.diameter = this.diameter;
  35768. serializationObject.thickness = this.thickness;
  35769. serializationObject.tessellation = this.tessellation;
  35770. return serializationObject;
  35771. };
  35772. TorusGeometry.Parse = function (parsedTorus, scene) {
  35773. if (scene.getGeometryByID(parsedTorus.id)) {
  35774. return null; // null since geometry could be something else than a torus...
  35775. }
  35776. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35777. if (BABYLON.Tags) {
  35778. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35779. }
  35780. scene.pushGeometry(torus, true);
  35781. return torus;
  35782. };
  35783. return TorusGeometry;
  35784. }(_PrimitiveGeometry));
  35785. BABYLON.TorusGeometry = TorusGeometry;
  35786. /**
  35787. * Creates a new ground geometry
  35788. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35789. */
  35790. var GroundGeometry = /** @class */ (function (_super) {
  35791. __extends(GroundGeometry, _super);
  35792. /**
  35793. * Creates a new ground geometry
  35794. * @param id defines the unique ID of the geometry
  35795. * @param scene defines the hosting scene
  35796. * @param width defines the width of the ground
  35797. * @param height defines the height of the ground
  35798. * @param subdivisions defines the subdivisions to apply to the ground
  35799. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35800. * @param mesh defines the hosting mesh (can be null)
  35801. */
  35802. function GroundGeometry(id, scene,
  35803. /**
  35804. * Defines the width of the ground
  35805. */
  35806. width,
  35807. /**
  35808. * Defines the height of the ground
  35809. */
  35810. height,
  35811. /**
  35812. * Defines the subdivisions to apply to the ground
  35813. */
  35814. subdivisions, canBeRegenerated, mesh) {
  35815. if (mesh === void 0) { mesh = null; }
  35816. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35817. _this.width = width;
  35818. _this.height = height;
  35819. _this.subdivisions = subdivisions;
  35820. return _this;
  35821. }
  35822. GroundGeometry.prototype._regenerateVertexData = function () {
  35823. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35824. };
  35825. GroundGeometry.prototype.copy = function (id) {
  35826. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35827. };
  35828. GroundGeometry.prototype.serialize = function () {
  35829. var serializationObject = _super.prototype.serialize.call(this);
  35830. serializationObject.width = this.width;
  35831. serializationObject.height = this.height;
  35832. serializationObject.subdivisions = this.subdivisions;
  35833. return serializationObject;
  35834. };
  35835. GroundGeometry.Parse = function (parsedGround, scene) {
  35836. if (scene.getGeometryByID(parsedGround.id)) {
  35837. return null; // null since geometry could be something else than a ground...
  35838. }
  35839. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35840. if (BABYLON.Tags) {
  35841. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35842. }
  35843. scene.pushGeometry(ground, true);
  35844. return ground;
  35845. };
  35846. return GroundGeometry;
  35847. }(_PrimitiveGeometry));
  35848. BABYLON.GroundGeometry = GroundGeometry;
  35849. /**
  35850. * Creates a tiled ground geometry
  35851. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35852. */
  35853. var TiledGroundGeometry = /** @class */ (function (_super) {
  35854. __extends(TiledGroundGeometry, _super);
  35855. /**
  35856. * Creates a tiled ground geometry
  35857. * @param id defines the unique ID of the geometry
  35858. * @param scene defines the hosting scene
  35859. * @param xmin defines the minimum value on X axis
  35860. * @param zmin defines the minimum value on Z axis
  35861. * @param xmax defines the maximum value on X axis
  35862. * @param zmax defines the maximum value on Z axis
  35863. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35864. * @param precision defines the precision to use when computing the tiles
  35865. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35866. * @param mesh defines the hosting mesh (can be null)
  35867. */
  35868. function TiledGroundGeometry(id, scene,
  35869. /**
  35870. * Defines the minimum value on X axis
  35871. */
  35872. xmin,
  35873. /**
  35874. * Defines the minimum value on Z axis
  35875. */
  35876. zmin,
  35877. /**
  35878. * Defines the maximum value on X axis
  35879. */
  35880. xmax,
  35881. /**
  35882. * Defines the maximum value on Z axis
  35883. */
  35884. zmax,
  35885. /**
  35886. * Defines the subdivisions to apply to the ground
  35887. */
  35888. subdivisions,
  35889. /**
  35890. * Defines the precision to use when computing the tiles
  35891. */
  35892. precision, canBeRegenerated, mesh) {
  35893. if (mesh === void 0) { mesh = null; }
  35894. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35895. _this.xmin = xmin;
  35896. _this.zmin = zmin;
  35897. _this.xmax = xmax;
  35898. _this.zmax = zmax;
  35899. _this.subdivisions = subdivisions;
  35900. _this.precision = precision;
  35901. return _this;
  35902. }
  35903. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35904. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35905. };
  35906. TiledGroundGeometry.prototype.copy = function (id) {
  35907. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35908. };
  35909. return TiledGroundGeometry;
  35910. }(_PrimitiveGeometry));
  35911. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35912. /**
  35913. * Creates a plane geometry
  35914. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35915. */
  35916. var PlaneGeometry = /** @class */ (function (_super) {
  35917. __extends(PlaneGeometry, _super);
  35918. /**
  35919. * Creates a plane geometry
  35920. * @param id defines the unique ID of the geometry
  35921. * @param scene defines the hosting scene
  35922. * @param size defines the size of the plane (width === height)
  35923. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35924. * @param mesh defines the hosting mesh (can be null)
  35925. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35926. */
  35927. function PlaneGeometry(id, scene,
  35928. /**
  35929. * Defines the size of the plane (width === height)
  35930. */
  35931. size, canBeRegenerated, mesh,
  35932. /**
  35933. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35934. */
  35935. side) {
  35936. if (mesh === void 0) { mesh = null; }
  35937. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35938. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35939. _this.size = size;
  35940. _this.side = side;
  35941. return _this;
  35942. }
  35943. PlaneGeometry.prototype._regenerateVertexData = function () {
  35944. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35945. };
  35946. PlaneGeometry.prototype.copy = function (id) {
  35947. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35948. };
  35949. PlaneGeometry.prototype.serialize = function () {
  35950. var serializationObject = _super.prototype.serialize.call(this);
  35951. serializationObject.size = this.size;
  35952. return serializationObject;
  35953. };
  35954. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35955. if (scene.getGeometryByID(parsedPlane.id)) {
  35956. return null; // null since geometry could be something else than a ground...
  35957. }
  35958. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35959. if (BABYLON.Tags) {
  35960. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35961. }
  35962. scene.pushGeometry(plane, true);
  35963. return plane;
  35964. };
  35965. return PlaneGeometry;
  35966. }(_PrimitiveGeometry));
  35967. BABYLON.PlaneGeometry = PlaneGeometry;
  35968. /**
  35969. * Creates a torus knot geometry
  35970. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35971. */
  35972. var TorusKnotGeometry = /** @class */ (function (_super) {
  35973. __extends(TorusKnotGeometry, _super);
  35974. /**
  35975. * Creates a torus knot geometry
  35976. * @param id defines the unique ID of the geometry
  35977. * @param scene defines the hosting scene
  35978. * @param radius defines the radius of the torus knot
  35979. * @param tube defines the thickness of the torus knot tube
  35980. * @param radialSegments defines the number of radial segments
  35981. * @param tubularSegments defines the number of tubular segments
  35982. * @param p defines the first number of windings
  35983. * @param q defines the second number of windings
  35984. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35985. * @param mesh defines the hosting mesh (can be null)
  35986. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35987. */
  35988. function TorusKnotGeometry(id, scene,
  35989. /**
  35990. * Defines the radius of the torus knot
  35991. */
  35992. radius,
  35993. /**
  35994. * Defines the thickness of the torus knot tube
  35995. */
  35996. tube,
  35997. /**
  35998. * Defines the number of radial segments
  35999. */
  36000. radialSegments,
  36001. /**
  36002. * Defines the number of tubular segments
  36003. */
  36004. tubularSegments,
  36005. /**
  36006. * Defines the first number of windings
  36007. */
  36008. p,
  36009. /**
  36010. * Defines the second number of windings
  36011. */
  36012. q, canBeRegenerated, mesh,
  36013. /**
  36014. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36015. */
  36016. side) {
  36017. if (mesh === void 0) { mesh = null; }
  36018. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36019. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36020. _this.radius = radius;
  36021. _this.tube = tube;
  36022. _this.radialSegments = radialSegments;
  36023. _this.tubularSegments = tubularSegments;
  36024. _this.p = p;
  36025. _this.q = q;
  36026. _this.side = side;
  36027. return _this;
  36028. }
  36029. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36030. 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 });
  36031. };
  36032. TorusKnotGeometry.prototype.copy = function (id) {
  36033. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36034. };
  36035. TorusKnotGeometry.prototype.serialize = function () {
  36036. var serializationObject = _super.prototype.serialize.call(this);
  36037. serializationObject.radius = this.radius;
  36038. serializationObject.tube = this.tube;
  36039. serializationObject.radialSegments = this.radialSegments;
  36040. serializationObject.tubularSegments = this.tubularSegments;
  36041. serializationObject.p = this.p;
  36042. serializationObject.q = this.q;
  36043. return serializationObject;
  36044. };
  36045. ;
  36046. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36047. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36048. return null; // null since geometry could be something else than a ground...
  36049. }
  36050. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36051. if (BABYLON.Tags) {
  36052. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36053. }
  36054. scene.pushGeometry(torusKnot, true);
  36055. return torusKnot;
  36056. };
  36057. return TorusKnotGeometry;
  36058. }(_PrimitiveGeometry));
  36059. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36060. //}
  36061. })(BABYLON || (BABYLON = {}));
  36062. //# sourceMappingURL=babylon.geometry.js.map
  36063. var BABYLON;
  36064. (function (BABYLON) {
  36065. /**
  36066. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36067. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36068. */
  36069. var PostProcessManager = /** @class */ (function () {
  36070. /**
  36071. * Creates a new instance of @see PostProcess
  36072. * @param scene The scene that the post process is associated with.
  36073. */
  36074. function PostProcessManager(scene) {
  36075. this._vertexBuffers = {};
  36076. this._scene = scene;
  36077. }
  36078. PostProcessManager.prototype._prepareBuffers = function () {
  36079. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36080. return;
  36081. }
  36082. // VBO
  36083. var vertices = [];
  36084. vertices.push(1, 1);
  36085. vertices.push(-1, 1);
  36086. vertices.push(-1, -1);
  36087. vertices.push(1, -1);
  36088. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36089. this._buildIndexBuffer();
  36090. };
  36091. PostProcessManager.prototype._buildIndexBuffer = function () {
  36092. // Indices
  36093. var indices = [];
  36094. indices.push(0);
  36095. indices.push(1);
  36096. indices.push(2);
  36097. indices.push(0);
  36098. indices.push(2);
  36099. indices.push(3);
  36100. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36101. };
  36102. /**
  36103. * Rebuilds the vertex buffers of the manager.
  36104. */
  36105. PostProcessManager.prototype._rebuild = function () {
  36106. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36107. if (!vb) {
  36108. return;
  36109. }
  36110. vb._rebuild();
  36111. this._buildIndexBuffer();
  36112. };
  36113. // Methods
  36114. /**
  36115. * Prepares a frame to be run through a post process.
  36116. * @param sourceTexture The input texture to the post procesess. (default: null)
  36117. * @param postProcesses An array of post processes to be run. (default: null)
  36118. * @returns True if the post processes were able to be run.
  36119. */
  36120. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36121. if (sourceTexture === void 0) { sourceTexture = null; }
  36122. if (postProcesses === void 0) { postProcesses = null; }
  36123. var camera = this._scene.activeCamera;
  36124. if (!camera) {
  36125. return false;
  36126. }
  36127. var postProcesses = postProcesses || camera._postProcesses;
  36128. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36129. return false;
  36130. }
  36131. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36132. return true;
  36133. };
  36134. /**
  36135. * Manually render a set of post processes to a texture.
  36136. * @param postProcesses An array of post processes to be run.
  36137. * @param targetTexture The target texture to render to.
  36138. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36139. */
  36140. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36141. if (targetTexture === void 0) { targetTexture = null; }
  36142. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36143. var engine = this._scene.getEngine();
  36144. for (var index = 0; index < postProcesses.length; index++) {
  36145. if (index < postProcesses.length - 1) {
  36146. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36147. }
  36148. else {
  36149. if (targetTexture) {
  36150. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36151. }
  36152. else {
  36153. engine.restoreDefaultFramebuffer();
  36154. }
  36155. }
  36156. var pp = postProcesses[index];
  36157. var effect = pp.apply();
  36158. if (effect) {
  36159. pp.onBeforeRenderObservable.notifyObservers(effect);
  36160. // VBOs
  36161. this._prepareBuffers();
  36162. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36163. // Draw order
  36164. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36165. pp.onAfterRenderObservable.notifyObservers(effect);
  36166. }
  36167. }
  36168. // Restore depth buffer
  36169. engine.setDepthBuffer(true);
  36170. engine.setDepthWrite(true);
  36171. };
  36172. /**
  36173. * Finalize the result of the output of the postprocesses.
  36174. * @param doNotPresent If true the result will not be displayed to the screen.
  36175. * @param targetTexture The target texture to render to.
  36176. * @param faceIndex The index of the face to bind the target texture to.
  36177. * @param postProcesses The array of post processes to render.
  36178. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36179. */
  36180. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36181. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36182. var camera = this._scene.activeCamera;
  36183. if (!camera) {
  36184. return;
  36185. }
  36186. postProcesses = postProcesses || camera._postProcesses;
  36187. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36188. return;
  36189. }
  36190. var engine = this._scene.getEngine();
  36191. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36192. if (index < len - 1) {
  36193. postProcesses[index + 1].activate(camera, targetTexture);
  36194. }
  36195. else {
  36196. if (targetTexture) {
  36197. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36198. }
  36199. else {
  36200. engine.restoreDefaultFramebuffer();
  36201. }
  36202. }
  36203. if (doNotPresent) {
  36204. break;
  36205. }
  36206. var pp = postProcesses[index];
  36207. var effect = pp.apply();
  36208. if (effect) {
  36209. pp.onBeforeRenderObservable.notifyObservers(effect);
  36210. // VBOs
  36211. this._prepareBuffers();
  36212. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36213. // Draw order
  36214. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36215. pp.onAfterRenderObservable.notifyObservers(effect);
  36216. }
  36217. }
  36218. // Restore states
  36219. engine.setDepthBuffer(true);
  36220. engine.setDepthWrite(true);
  36221. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36222. };
  36223. /**
  36224. * Disposes of the post process manager.
  36225. */
  36226. PostProcessManager.prototype.dispose = function () {
  36227. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36228. if (buffer) {
  36229. buffer.dispose();
  36230. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36231. }
  36232. if (this._indexBuffer) {
  36233. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36234. this._indexBuffer = null;
  36235. }
  36236. };
  36237. return PostProcessManager;
  36238. }());
  36239. BABYLON.PostProcessManager = PostProcessManager;
  36240. })(BABYLON || (BABYLON = {}));
  36241. //# sourceMappingURL=babylon.postProcessManager.js.map
  36242. var BABYLON;
  36243. (function (BABYLON) {
  36244. /**
  36245. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36246. */
  36247. var PerformanceMonitor = /** @class */ (function () {
  36248. /**
  36249. * constructor
  36250. * @param frameSampleSize The number of samples required to saturate the sliding window
  36251. */
  36252. function PerformanceMonitor(frameSampleSize) {
  36253. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36254. this._enabled = true;
  36255. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36256. }
  36257. /**
  36258. * Samples current frame
  36259. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36260. */
  36261. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36262. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36263. if (!this._enabled)
  36264. return;
  36265. if (this._lastFrameTimeMs != null) {
  36266. var dt = timeMs - this._lastFrameTimeMs;
  36267. this._rollingFrameTime.add(dt);
  36268. }
  36269. this._lastFrameTimeMs = timeMs;
  36270. };
  36271. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36272. /**
  36273. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36274. * @return Average frame time in milliseconds
  36275. */
  36276. get: function () {
  36277. return this._rollingFrameTime.average;
  36278. },
  36279. enumerable: true,
  36280. configurable: true
  36281. });
  36282. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36283. /**
  36284. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36285. * @return Frame time variance in milliseconds squared
  36286. */
  36287. get: function () {
  36288. return this._rollingFrameTime.variance;
  36289. },
  36290. enumerable: true,
  36291. configurable: true
  36292. });
  36293. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36294. /**
  36295. * Returns the frame time of the most recent frame
  36296. * @return Frame time in milliseconds
  36297. */
  36298. get: function () {
  36299. return this._rollingFrameTime.history(0);
  36300. },
  36301. enumerable: true,
  36302. configurable: true
  36303. });
  36304. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36305. /**
  36306. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36307. * @return Framerate in frames per second
  36308. */
  36309. get: function () {
  36310. return 1000.0 / this._rollingFrameTime.average;
  36311. },
  36312. enumerable: true,
  36313. configurable: true
  36314. });
  36315. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36316. /**
  36317. * Returns the average framerate in frames per second using the most recent frame time
  36318. * @return Framerate in frames per second
  36319. */
  36320. get: function () {
  36321. var history = this._rollingFrameTime.history(0);
  36322. if (history === 0) {
  36323. return 0;
  36324. }
  36325. return 1000.0 / history;
  36326. },
  36327. enumerable: true,
  36328. configurable: true
  36329. });
  36330. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36331. /**
  36332. * Returns true if enough samples have been taken to completely fill the sliding window
  36333. * @return true if saturated
  36334. */
  36335. get: function () {
  36336. return this._rollingFrameTime.isSaturated();
  36337. },
  36338. enumerable: true,
  36339. configurable: true
  36340. });
  36341. /**
  36342. * Enables contributions to the sliding window sample set
  36343. */
  36344. PerformanceMonitor.prototype.enable = function () {
  36345. this._enabled = true;
  36346. };
  36347. /**
  36348. * Disables contributions to the sliding window sample set
  36349. * Samples will not be interpolated over the disabled period
  36350. */
  36351. PerformanceMonitor.prototype.disable = function () {
  36352. this._enabled = false;
  36353. //clear last sample to avoid interpolating over the disabled period when next enabled
  36354. this._lastFrameTimeMs = null;
  36355. };
  36356. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36357. /**
  36358. * Returns true if sampling is enabled
  36359. * @return true if enabled
  36360. */
  36361. get: function () {
  36362. return this._enabled;
  36363. },
  36364. enumerable: true,
  36365. configurable: true
  36366. });
  36367. /**
  36368. * Resets performance monitor
  36369. */
  36370. PerformanceMonitor.prototype.reset = function () {
  36371. //clear last sample to avoid interpolating over the disabled period when next enabled
  36372. this._lastFrameTimeMs = null;
  36373. //wipe record
  36374. this._rollingFrameTime.reset();
  36375. };
  36376. return PerformanceMonitor;
  36377. }());
  36378. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36379. /**
  36380. * RollingAverage
  36381. *
  36382. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36383. */
  36384. var RollingAverage = /** @class */ (function () {
  36385. /**
  36386. * constructor
  36387. * @param length The number of samples required to saturate the sliding window
  36388. */
  36389. function RollingAverage(length) {
  36390. this._samples = new Array(length);
  36391. this.reset();
  36392. }
  36393. /**
  36394. * Adds a sample to the sample set
  36395. * @param v The sample value
  36396. */
  36397. RollingAverage.prototype.add = function (v) {
  36398. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36399. var delta;
  36400. //we need to check if we've already wrapped round
  36401. if (this.isSaturated()) {
  36402. //remove bottom of stack from mean
  36403. var bottomValue = this._samples[this._pos];
  36404. delta = bottomValue - this.average;
  36405. this.average -= delta / (this._sampleCount - 1);
  36406. this._m2 -= delta * (bottomValue - this.average);
  36407. }
  36408. else {
  36409. this._sampleCount++;
  36410. }
  36411. //add new value to mean
  36412. delta = v - this.average;
  36413. this.average += delta / (this._sampleCount);
  36414. this._m2 += delta * (v - this.average);
  36415. //set the new variance
  36416. this.variance = this._m2 / (this._sampleCount - 1);
  36417. this._samples[this._pos] = v;
  36418. this._pos++;
  36419. this._pos %= this._samples.length; //positive wrap around
  36420. };
  36421. /**
  36422. * Returns previously added values or null if outside of history or outside the sliding window domain
  36423. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36424. * @return Value previously recorded with add() or null if outside of range
  36425. */
  36426. RollingAverage.prototype.history = function (i) {
  36427. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36428. return 0;
  36429. }
  36430. var i0 = this._wrapPosition(this._pos - 1.0);
  36431. return this._samples[this._wrapPosition(i0 - i)];
  36432. };
  36433. /**
  36434. * Returns true if enough samples have been taken to completely fill the sliding window
  36435. * @return true if sample-set saturated
  36436. */
  36437. RollingAverage.prototype.isSaturated = function () {
  36438. return this._sampleCount >= this._samples.length;
  36439. };
  36440. /**
  36441. * Resets the rolling average (equivalent to 0 samples taken so far)
  36442. */
  36443. RollingAverage.prototype.reset = function () {
  36444. this.average = 0;
  36445. this.variance = 0;
  36446. this._sampleCount = 0;
  36447. this._pos = 0;
  36448. this._m2 = 0;
  36449. };
  36450. /**
  36451. * Wraps a value around the sample range boundaries
  36452. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36453. * @return Wrapped position in sample range
  36454. */
  36455. RollingAverage.prototype._wrapPosition = function (i) {
  36456. var max = this._samples.length;
  36457. return ((i % max) + max) % max;
  36458. };
  36459. return RollingAverage;
  36460. }());
  36461. BABYLON.RollingAverage = RollingAverage;
  36462. })(BABYLON || (BABYLON = {}));
  36463. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36464. var BABYLON;
  36465. (function (BABYLON) {
  36466. /**
  36467. * This groups together the common properties used for image processing either in direct forward pass
  36468. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36469. * or not.
  36470. */
  36471. var ImageProcessingConfiguration = /** @class */ (function () {
  36472. function ImageProcessingConfiguration() {
  36473. /**
  36474. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36475. */
  36476. this.colorCurves = new BABYLON.ColorCurves();
  36477. this._colorCurvesEnabled = false;
  36478. this._colorGradingEnabled = false;
  36479. this._colorGradingWithGreenDepth = true;
  36480. this._colorGradingBGR = true;
  36481. this._exposure = 1.0;
  36482. this._toneMappingEnabled = false;
  36483. this._contrast = 1.0;
  36484. /**
  36485. * Vignette stretch size.
  36486. */
  36487. this.vignetteStretch = 0;
  36488. /**
  36489. * Vignette centre X Offset.
  36490. */
  36491. this.vignetteCentreX = 0;
  36492. /**
  36493. * Vignette centre Y Offset.
  36494. */
  36495. this.vignetteCentreY = 0;
  36496. /**
  36497. * Vignette weight or intensity of the vignette effect.
  36498. */
  36499. this.vignetteWeight = 1.5;
  36500. /**
  36501. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36502. * if vignetteEnabled is set to true.
  36503. */
  36504. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36505. /**
  36506. * Camera field of view used by the Vignette effect.
  36507. */
  36508. this.vignetteCameraFov = 0.5;
  36509. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36510. this._vignetteEnabled = false;
  36511. this._applyByPostProcess = false;
  36512. this._isEnabled = true;
  36513. /**
  36514. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36515. * @type {BABYLON.Observable}
  36516. */
  36517. this.onUpdateParameters = new BABYLON.Observable();
  36518. }
  36519. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36520. /**
  36521. * Gets wether the color curves effect is enabled.
  36522. */
  36523. get: function () {
  36524. return this._colorCurvesEnabled;
  36525. },
  36526. /**
  36527. * Sets wether the color curves effect is enabled.
  36528. */
  36529. set: function (value) {
  36530. if (this._colorCurvesEnabled === value) {
  36531. return;
  36532. }
  36533. this._colorCurvesEnabled = value;
  36534. this._updateParameters();
  36535. },
  36536. enumerable: true,
  36537. configurable: true
  36538. });
  36539. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36540. /**
  36541. * Gets wether the color grading effect is enabled.
  36542. */
  36543. get: function () {
  36544. return this._colorGradingEnabled;
  36545. },
  36546. /**
  36547. * Sets wether the color grading effect is enabled.
  36548. */
  36549. set: function (value) {
  36550. if (this._colorGradingEnabled === value) {
  36551. return;
  36552. }
  36553. this._colorGradingEnabled = value;
  36554. this._updateParameters();
  36555. },
  36556. enumerable: true,
  36557. configurable: true
  36558. });
  36559. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36560. /**
  36561. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36562. */
  36563. get: function () {
  36564. return this._colorGradingWithGreenDepth;
  36565. },
  36566. /**
  36567. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36568. */
  36569. set: function (value) {
  36570. if (this._colorGradingWithGreenDepth === value) {
  36571. return;
  36572. }
  36573. this._colorGradingWithGreenDepth = value;
  36574. this._updateParameters();
  36575. },
  36576. enumerable: true,
  36577. configurable: true
  36578. });
  36579. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36580. /**
  36581. * Gets wether the color grading texture contains BGR values.
  36582. */
  36583. get: function () {
  36584. return this._colorGradingBGR;
  36585. },
  36586. /**
  36587. * Sets wether the color grading texture contains BGR values.
  36588. */
  36589. set: function (value) {
  36590. if (this._colorGradingBGR === value) {
  36591. return;
  36592. }
  36593. this._colorGradingBGR = value;
  36594. this._updateParameters();
  36595. },
  36596. enumerable: true,
  36597. configurable: true
  36598. });
  36599. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36600. /**
  36601. * Gets the Exposure used in the effect.
  36602. */
  36603. get: function () {
  36604. return this._exposure;
  36605. },
  36606. /**
  36607. * Sets the Exposure used in the effect.
  36608. */
  36609. set: function (value) {
  36610. if (this._exposure === value) {
  36611. return;
  36612. }
  36613. this._exposure = value;
  36614. this._updateParameters();
  36615. },
  36616. enumerable: true,
  36617. configurable: true
  36618. });
  36619. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36620. /**
  36621. * Gets wether the tone mapping effect is enabled.
  36622. */
  36623. get: function () {
  36624. return this._toneMappingEnabled;
  36625. },
  36626. /**
  36627. * Sets wether the tone mapping effect is enabled.
  36628. */
  36629. set: function (value) {
  36630. if (this._toneMappingEnabled === value) {
  36631. return;
  36632. }
  36633. this._toneMappingEnabled = value;
  36634. this._updateParameters();
  36635. },
  36636. enumerable: true,
  36637. configurable: true
  36638. });
  36639. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36640. /**
  36641. * Gets the contrast used in the effect.
  36642. */
  36643. get: function () {
  36644. return this._contrast;
  36645. },
  36646. /**
  36647. * Sets the contrast used in the effect.
  36648. */
  36649. set: function (value) {
  36650. if (this._contrast === value) {
  36651. return;
  36652. }
  36653. this._contrast = value;
  36654. this._updateParameters();
  36655. },
  36656. enumerable: true,
  36657. configurable: true
  36658. });
  36659. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36660. /**
  36661. * Gets the vignette blend mode allowing different kind of effect.
  36662. */
  36663. get: function () {
  36664. return this._vignetteBlendMode;
  36665. },
  36666. /**
  36667. * Sets the vignette blend mode allowing different kind of effect.
  36668. */
  36669. set: function (value) {
  36670. if (this._vignetteBlendMode === value) {
  36671. return;
  36672. }
  36673. this._vignetteBlendMode = value;
  36674. this._updateParameters();
  36675. },
  36676. enumerable: true,
  36677. configurable: true
  36678. });
  36679. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36680. /**
  36681. * Gets wether the vignette effect is enabled.
  36682. */
  36683. get: function () {
  36684. return this._vignetteEnabled;
  36685. },
  36686. /**
  36687. * Sets wether the vignette effect is enabled.
  36688. */
  36689. set: function (value) {
  36690. if (this._vignetteEnabled === value) {
  36691. return;
  36692. }
  36693. this._vignetteEnabled = value;
  36694. this._updateParameters();
  36695. },
  36696. enumerable: true,
  36697. configurable: true
  36698. });
  36699. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36700. /**
  36701. * Gets wether the image processing is applied through a post process or not.
  36702. */
  36703. get: function () {
  36704. return this._applyByPostProcess;
  36705. },
  36706. /**
  36707. * Sets wether the image processing is applied through a post process or not.
  36708. */
  36709. set: function (value) {
  36710. if (this._applyByPostProcess === value) {
  36711. return;
  36712. }
  36713. this._applyByPostProcess = value;
  36714. this._updateParameters();
  36715. },
  36716. enumerable: true,
  36717. configurable: true
  36718. });
  36719. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36720. /**
  36721. * Gets wether the image processing is enabled or not.
  36722. */
  36723. get: function () {
  36724. return this._isEnabled;
  36725. },
  36726. /**
  36727. * Sets wether the image processing is enabled or not.
  36728. */
  36729. set: function (value) {
  36730. if (this._isEnabled === value) {
  36731. return;
  36732. }
  36733. this._isEnabled = value;
  36734. this._updateParameters();
  36735. },
  36736. enumerable: true,
  36737. configurable: true
  36738. });
  36739. /**
  36740. * Method called each time the image processing information changes requires to recompile the effect.
  36741. */
  36742. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36743. this.onUpdateParameters.notifyObservers(this);
  36744. };
  36745. ImageProcessingConfiguration.prototype.getClassName = function () {
  36746. return "ImageProcessingConfiguration";
  36747. };
  36748. /**
  36749. * Prepare the list of uniforms associated with the Image Processing effects.
  36750. * @param uniformsList The list of uniforms used in the effect
  36751. * @param defines the list of defines currently in use
  36752. */
  36753. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36754. if (defines.EXPOSURE) {
  36755. uniforms.push("exposureLinear");
  36756. }
  36757. if (defines.CONTRAST) {
  36758. uniforms.push("contrast");
  36759. }
  36760. if (defines.COLORGRADING) {
  36761. uniforms.push("colorTransformSettings");
  36762. }
  36763. if (defines.VIGNETTE) {
  36764. uniforms.push("vInverseScreenSize");
  36765. uniforms.push("vignetteSettings1");
  36766. uniforms.push("vignetteSettings2");
  36767. }
  36768. if (defines.COLORCURVES) {
  36769. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36770. }
  36771. };
  36772. /**
  36773. * Prepare the list of samplers associated with the Image Processing effects.
  36774. * @param uniformsList The list of uniforms used in the effect
  36775. * @param defines the list of defines currently in use
  36776. */
  36777. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36778. if (defines.COLORGRADING) {
  36779. samplersList.push("txColorTransform");
  36780. }
  36781. };
  36782. /**
  36783. * Prepare the list of defines associated to the shader.
  36784. * @param defines the list of defines to complete
  36785. */
  36786. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36787. if (forPostProcess === void 0) { forPostProcess = false; }
  36788. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36789. defines.VIGNETTE = false;
  36790. defines.TONEMAPPING = false;
  36791. defines.CONTRAST = false;
  36792. defines.EXPOSURE = false;
  36793. defines.COLORCURVES = false;
  36794. defines.COLORGRADING = false;
  36795. defines.COLORGRADING3D = false;
  36796. defines.IMAGEPROCESSING = false;
  36797. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36798. return;
  36799. }
  36800. defines.VIGNETTE = this.vignetteEnabled;
  36801. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36802. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36803. defines.TONEMAPPING = this.toneMappingEnabled;
  36804. defines.CONTRAST = (this.contrast !== 1.0);
  36805. defines.EXPOSURE = (this.exposure !== 1.0);
  36806. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36807. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36808. if (defines.COLORGRADING) {
  36809. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36810. }
  36811. else {
  36812. defines.COLORGRADING3D = false;
  36813. }
  36814. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36815. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36816. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36817. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36818. };
  36819. /**
  36820. * Returns true if all the image processing information are ready.
  36821. */
  36822. ImageProcessingConfiguration.prototype.isReady = function () {
  36823. // Color Grading texure can not be none blocking.
  36824. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36825. };
  36826. /**
  36827. * Binds the image processing to the shader.
  36828. * @param effect The effect to bind to
  36829. */
  36830. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36831. if (aspectRatio === void 0) { aspectRatio = 1; }
  36832. // Color Curves
  36833. if (this._colorCurvesEnabled && this.colorCurves) {
  36834. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36835. }
  36836. // Vignette
  36837. if (this._vignetteEnabled) {
  36838. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36839. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36840. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36841. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36842. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36843. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36844. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36845. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36846. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36847. var vignettePower = -2.0 * this.vignetteWeight;
  36848. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36849. }
  36850. // Exposure
  36851. effect.setFloat("exposureLinear", this.exposure);
  36852. // Contrast
  36853. effect.setFloat("contrast", this.contrast);
  36854. // Color transform settings
  36855. if (this.colorGradingTexture) {
  36856. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36857. var textureSize = this.colorGradingTexture.getSize().height;
  36858. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36859. 0.5 / textureSize, // textureOffset
  36860. textureSize, // textureSize
  36861. this.colorGradingTexture.level // weight
  36862. );
  36863. }
  36864. };
  36865. /**
  36866. * Clones the current image processing instance.
  36867. * @return The cloned image processing
  36868. */
  36869. ImageProcessingConfiguration.prototype.clone = function () {
  36870. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36871. };
  36872. /**
  36873. * Serializes the current image processing instance to a json representation.
  36874. * @return a JSON representation
  36875. */
  36876. ImageProcessingConfiguration.prototype.serialize = function () {
  36877. return BABYLON.SerializationHelper.Serialize(this);
  36878. };
  36879. /**
  36880. * Parses the image processing from a json representation.
  36881. * @param source the JSON source to parse
  36882. * @return The parsed image processing
  36883. */
  36884. ImageProcessingConfiguration.Parse = function (source) {
  36885. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36886. };
  36887. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36888. /**
  36889. * Used to apply the vignette as a mix with the pixel color.
  36890. */
  36891. get: function () {
  36892. return this._VIGNETTEMODE_MULTIPLY;
  36893. },
  36894. enumerable: true,
  36895. configurable: true
  36896. });
  36897. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36898. /**
  36899. * Used to apply the vignette as a replacement of the pixel color.
  36900. */
  36901. get: function () {
  36902. return this._VIGNETTEMODE_OPAQUE;
  36903. },
  36904. enumerable: true,
  36905. configurable: true
  36906. });
  36907. // Static constants associated to the image processing.
  36908. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36909. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36910. __decorate([
  36911. BABYLON.serializeAsColorCurves()
  36912. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36913. __decorate([
  36914. BABYLON.serialize()
  36915. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36916. __decorate([
  36917. BABYLON.serializeAsTexture()
  36918. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36919. __decorate([
  36920. BABYLON.serialize()
  36921. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36922. __decorate([
  36923. BABYLON.serialize()
  36924. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36925. __decorate([
  36926. BABYLON.serialize()
  36927. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36928. __decorate([
  36929. BABYLON.serialize()
  36930. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36931. __decorate([
  36932. BABYLON.serialize()
  36933. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36934. __decorate([
  36935. BABYLON.serialize()
  36936. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36937. __decorate([
  36938. BABYLON.serialize()
  36939. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36940. __decorate([
  36941. BABYLON.serialize()
  36942. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36943. __decorate([
  36944. BABYLON.serialize()
  36945. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36946. __decorate([
  36947. BABYLON.serialize()
  36948. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36949. __decorate([
  36950. BABYLON.serializeAsColor4()
  36951. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36952. __decorate([
  36953. BABYLON.serialize()
  36954. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36955. __decorate([
  36956. BABYLON.serialize()
  36957. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36958. __decorate([
  36959. BABYLON.serialize()
  36960. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36961. __decorate([
  36962. BABYLON.serialize()
  36963. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36964. __decorate([
  36965. BABYLON.serialize()
  36966. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36967. return ImageProcessingConfiguration;
  36968. }());
  36969. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36970. })(BABYLON || (BABYLON = {}));
  36971. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36972. var BABYLON;
  36973. (function (BABYLON) {
  36974. /**
  36975. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36976. * It can help converting any input color in a desired output one. This can then be used to create effects
  36977. * from sepia, black and white to sixties or futuristic rendering...
  36978. *
  36979. * The only supported format is currently 3dl.
  36980. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36981. */
  36982. var ColorGradingTexture = /** @class */ (function (_super) {
  36983. __extends(ColorGradingTexture, _super);
  36984. /**
  36985. * Instantiates a ColorGradingTexture from the following parameters.
  36986. *
  36987. * @param url The location of the color gradind data (currently only supporting 3dl)
  36988. * @param scene The scene the texture will be used in
  36989. */
  36990. function ColorGradingTexture(url, scene) {
  36991. var _this = _super.call(this, scene) || this;
  36992. if (!url) {
  36993. return _this;
  36994. }
  36995. _this._engine = scene.getEngine();
  36996. _this._textureMatrix = BABYLON.Matrix.Identity();
  36997. _this.name = url;
  36998. _this.url = url;
  36999. _this.hasAlpha = false;
  37000. _this.isCube = false;
  37001. _this.is3D = _this._engine.webGLVersion > 1;
  37002. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37003. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37004. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37005. _this.anisotropicFilteringLevel = 1;
  37006. _this._texture = _this._getFromCache(url, true);
  37007. if (!_this._texture) {
  37008. if (!scene.useDelayedTextureLoading) {
  37009. _this.loadTexture();
  37010. }
  37011. else {
  37012. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37013. }
  37014. }
  37015. return _this;
  37016. }
  37017. /**
  37018. * Returns the texture matrix used in most of the material.
  37019. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37020. */
  37021. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37022. return this._textureMatrix;
  37023. };
  37024. /**
  37025. * Occurs when the file being loaded is a .3dl LUT file.
  37026. */
  37027. ColorGradingTexture.prototype.load3dlTexture = function () {
  37028. var engine = this._engine;
  37029. var texture;
  37030. if (engine.webGLVersion === 1) {
  37031. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37032. }
  37033. else {
  37034. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37035. }
  37036. this._texture = texture;
  37037. var callback = function (text) {
  37038. if (typeof text !== "string") {
  37039. return;
  37040. }
  37041. var data = null;
  37042. var tempData = null;
  37043. var line;
  37044. var lines = text.split('\n');
  37045. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37046. var maxColor = 0;
  37047. for (var i = 0; i < lines.length; i++) {
  37048. line = lines[i];
  37049. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37050. continue;
  37051. if (line.indexOf('#') === 0)
  37052. continue;
  37053. var words = line.split(" ");
  37054. if (size === 0) {
  37055. // Number of space + one
  37056. size = words.length;
  37057. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37058. tempData = new Float32Array(size * size * size * 4);
  37059. continue;
  37060. }
  37061. if (size != 0) {
  37062. var r = Math.max(parseInt(words[0]), 0);
  37063. var g = Math.max(parseInt(words[1]), 0);
  37064. var b = Math.max(parseInt(words[2]), 0);
  37065. maxColor = Math.max(r, maxColor);
  37066. maxColor = Math.max(g, maxColor);
  37067. maxColor = Math.max(b, maxColor);
  37068. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37069. if (tempData) {
  37070. tempData[pixelStorageIndex + 0] = r;
  37071. tempData[pixelStorageIndex + 1] = g;
  37072. tempData[pixelStorageIndex + 2] = b;
  37073. }
  37074. pixelIndexSlice++;
  37075. if (pixelIndexSlice % size == 0) {
  37076. pixelIndexH++;
  37077. pixelIndexSlice = 0;
  37078. if (pixelIndexH % size == 0) {
  37079. pixelIndexW++;
  37080. pixelIndexH = 0;
  37081. }
  37082. }
  37083. }
  37084. }
  37085. if (tempData && data) {
  37086. for (var i = 0; i < tempData.length; i++) {
  37087. if (i > 0 && (i + 1) % 4 === 0) {
  37088. data[i] = 255;
  37089. }
  37090. else {
  37091. var value = tempData[i];
  37092. data[i] = (value / maxColor * 255);
  37093. }
  37094. }
  37095. }
  37096. if (texture.is3D) {
  37097. texture.updateSize(size, size, size);
  37098. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37099. }
  37100. else {
  37101. texture.updateSize(size * size, size);
  37102. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37103. }
  37104. };
  37105. var scene = this.getScene();
  37106. if (scene) {
  37107. scene._loadFile(this.url, callback);
  37108. }
  37109. else {
  37110. this._engine._loadFile(this.url, callback);
  37111. }
  37112. return this._texture;
  37113. };
  37114. /**
  37115. * Starts the loading process of the texture.
  37116. */
  37117. ColorGradingTexture.prototype.loadTexture = function () {
  37118. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37119. this.load3dlTexture();
  37120. }
  37121. };
  37122. /**
  37123. * Clones the color gradind texture.
  37124. */
  37125. ColorGradingTexture.prototype.clone = function () {
  37126. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37127. // Base texture
  37128. newTexture.level = this.level;
  37129. return newTexture;
  37130. };
  37131. /**
  37132. * Called during delayed load for textures.
  37133. */
  37134. ColorGradingTexture.prototype.delayLoad = function () {
  37135. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37136. return;
  37137. }
  37138. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37139. this._texture = this._getFromCache(this.url, true);
  37140. if (!this._texture) {
  37141. this.loadTexture();
  37142. }
  37143. };
  37144. /**
  37145. * Parses a color grading texture serialized by Babylon.
  37146. * @param parsedTexture The texture information being parsedTexture
  37147. * @param scene The scene to load the texture in
  37148. * @param rootUrl The root url of the data assets to load
  37149. * @return A color gradind texture
  37150. */
  37151. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37152. var texture = null;
  37153. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37154. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37155. texture.name = parsedTexture.name;
  37156. texture.level = parsedTexture.level;
  37157. }
  37158. return texture;
  37159. };
  37160. /**
  37161. * Serializes the LUT texture to json format.
  37162. */
  37163. ColorGradingTexture.prototype.serialize = function () {
  37164. if (!this.name) {
  37165. return null;
  37166. }
  37167. var serializationObject = {};
  37168. serializationObject.name = this.name;
  37169. serializationObject.level = this.level;
  37170. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37171. return serializationObject;
  37172. };
  37173. /**
  37174. * Empty line regex stored for GC.
  37175. */
  37176. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37177. return ColorGradingTexture;
  37178. }(BABYLON.BaseTexture));
  37179. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37180. })(BABYLON || (BABYLON = {}));
  37181. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37182. var BABYLON;
  37183. (function (BABYLON) {
  37184. /**
  37185. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37186. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37187. * 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;
  37188. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37189. */
  37190. var ColorCurves = /** @class */ (function () {
  37191. function ColorCurves() {
  37192. this._dirty = true;
  37193. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37194. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37195. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37196. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37197. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37198. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37199. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37200. this._globalHue = 30;
  37201. this._globalDensity = 0;
  37202. this._globalSaturation = 0;
  37203. this._globalExposure = 0;
  37204. this._highlightsHue = 30;
  37205. this._highlightsDensity = 0;
  37206. this._highlightsSaturation = 0;
  37207. this._highlightsExposure = 0;
  37208. this._midtonesHue = 30;
  37209. this._midtonesDensity = 0;
  37210. this._midtonesSaturation = 0;
  37211. this._midtonesExposure = 0;
  37212. this._shadowsHue = 30;
  37213. this._shadowsDensity = 0;
  37214. this._shadowsSaturation = 0;
  37215. this._shadowsExposure = 0;
  37216. }
  37217. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37218. /**
  37219. * Gets the global Hue value.
  37220. * 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).
  37221. */
  37222. get: function () {
  37223. return this._globalHue;
  37224. },
  37225. /**
  37226. * Sets the global Hue value.
  37227. * 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).
  37228. */
  37229. set: function (value) {
  37230. this._globalHue = value;
  37231. this._dirty = true;
  37232. },
  37233. enumerable: true,
  37234. configurable: true
  37235. });
  37236. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37237. /**
  37238. * Gets the global Density value.
  37239. * 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.
  37240. * Values less than zero provide a filter of opposite hue.
  37241. */
  37242. get: function () {
  37243. return this._globalDensity;
  37244. },
  37245. /**
  37246. * Sets the global Density value.
  37247. * 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.
  37248. * Values less than zero provide a filter of opposite hue.
  37249. */
  37250. set: function (value) {
  37251. this._globalDensity = value;
  37252. this._dirty = true;
  37253. },
  37254. enumerable: true,
  37255. configurable: true
  37256. });
  37257. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37258. /**
  37259. * Gets the global Saturation value.
  37260. * 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.
  37261. */
  37262. get: function () {
  37263. return this._globalSaturation;
  37264. },
  37265. /**
  37266. * Sets the global Saturation value.
  37267. * 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.
  37268. */
  37269. set: function (value) {
  37270. this._globalSaturation = value;
  37271. this._dirty = true;
  37272. },
  37273. enumerable: true,
  37274. configurable: true
  37275. });
  37276. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37277. /**
  37278. * Gets the highlights Hue value.
  37279. * 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).
  37280. */
  37281. get: function () {
  37282. return this._highlightsHue;
  37283. },
  37284. /**
  37285. * Sets the highlights Hue value.
  37286. * 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).
  37287. */
  37288. set: function (value) {
  37289. this._highlightsHue = value;
  37290. this._dirty = true;
  37291. },
  37292. enumerable: true,
  37293. configurable: true
  37294. });
  37295. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37296. /**
  37297. * Gets the highlights Density value.
  37298. * 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.
  37299. * Values less than zero provide a filter of opposite hue.
  37300. */
  37301. get: function () {
  37302. return this._highlightsDensity;
  37303. },
  37304. /**
  37305. * Sets the highlights Density value.
  37306. * 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.
  37307. * Values less than zero provide a filter of opposite hue.
  37308. */
  37309. set: function (value) {
  37310. this._highlightsDensity = value;
  37311. this._dirty = true;
  37312. },
  37313. enumerable: true,
  37314. configurable: true
  37315. });
  37316. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37317. /**
  37318. * Gets the highlights Saturation value.
  37319. * 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.
  37320. */
  37321. get: function () {
  37322. return this._highlightsSaturation;
  37323. },
  37324. /**
  37325. * Sets the highlights Saturation value.
  37326. * 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.
  37327. */
  37328. set: function (value) {
  37329. this._highlightsSaturation = value;
  37330. this._dirty = true;
  37331. },
  37332. enumerable: true,
  37333. configurable: true
  37334. });
  37335. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37336. /**
  37337. * Gets the highlights Exposure value.
  37338. * 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.
  37339. */
  37340. get: function () {
  37341. return this._highlightsExposure;
  37342. },
  37343. /**
  37344. * Sets the highlights Exposure value.
  37345. * 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.
  37346. */
  37347. set: function (value) {
  37348. this._highlightsExposure = value;
  37349. this._dirty = true;
  37350. },
  37351. enumerable: true,
  37352. configurable: true
  37353. });
  37354. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37355. /**
  37356. * Gets the midtones Hue value.
  37357. * 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).
  37358. */
  37359. get: function () {
  37360. return this._midtonesHue;
  37361. },
  37362. /**
  37363. * Sets the midtones Hue value.
  37364. * 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).
  37365. */
  37366. set: function (value) {
  37367. this._midtonesHue = value;
  37368. this._dirty = true;
  37369. },
  37370. enumerable: true,
  37371. configurable: true
  37372. });
  37373. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37374. /**
  37375. * Gets the midtones Density value.
  37376. * 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.
  37377. * Values less than zero provide a filter of opposite hue.
  37378. */
  37379. get: function () {
  37380. return this._midtonesDensity;
  37381. },
  37382. /**
  37383. * Sets the midtones Density value.
  37384. * 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.
  37385. * Values less than zero provide a filter of opposite hue.
  37386. */
  37387. set: function (value) {
  37388. this._midtonesDensity = value;
  37389. this._dirty = true;
  37390. },
  37391. enumerable: true,
  37392. configurable: true
  37393. });
  37394. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37395. /**
  37396. * Gets the midtones Saturation value.
  37397. * 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.
  37398. */
  37399. get: function () {
  37400. return this._midtonesSaturation;
  37401. },
  37402. /**
  37403. * Sets the midtones Saturation value.
  37404. * 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.
  37405. */
  37406. set: function (value) {
  37407. this._midtonesSaturation = value;
  37408. this._dirty = true;
  37409. },
  37410. enumerable: true,
  37411. configurable: true
  37412. });
  37413. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37414. /**
  37415. * Gets the midtones Exposure value.
  37416. * 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.
  37417. */
  37418. get: function () {
  37419. return this._midtonesExposure;
  37420. },
  37421. /**
  37422. * Sets the midtones Exposure value.
  37423. * 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.
  37424. */
  37425. set: function (value) {
  37426. this._midtonesExposure = value;
  37427. this._dirty = true;
  37428. },
  37429. enumerable: true,
  37430. configurable: true
  37431. });
  37432. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37433. /**
  37434. * Gets the shadows Hue value.
  37435. * 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).
  37436. */
  37437. get: function () {
  37438. return this._shadowsHue;
  37439. },
  37440. /**
  37441. * Sets the shadows Hue value.
  37442. * 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).
  37443. */
  37444. set: function (value) {
  37445. this._shadowsHue = value;
  37446. this._dirty = true;
  37447. },
  37448. enumerable: true,
  37449. configurable: true
  37450. });
  37451. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37452. /**
  37453. * Gets the shadows Density value.
  37454. * 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.
  37455. * Values less than zero provide a filter of opposite hue.
  37456. */
  37457. get: function () {
  37458. return this._shadowsDensity;
  37459. },
  37460. /**
  37461. * Sets the shadows Density value.
  37462. * 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.
  37463. * Values less than zero provide a filter of opposite hue.
  37464. */
  37465. set: function (value) {
  37466. this._shadowsDensity = value;
  37467. this._dirty = true;
  37468. },
  37469. enumerable: true,
  37470. configurable: true
  37471. });
  37472. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37473. /**
  37474. * Gets the shadows Saturation value.
  37475. * 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.
  37476. */
  37477. get: function () {
  37478. return this._shadowsSaturation;
  37479. },
  37480. /**
  37481. * Sets the shadows Saturation value.
  37482. * 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.
  37483. */
  37484. set: function (value) {
  37485. this._shadowsSaturation = value;
  37486. this._dirty = true;
  37487. },
  37488. enumerable: true,
  37489. configurable: true
  37490. });
  37491. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37492. /**
  37493. * Gets the shadows Exposure value.
  37494. * 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.
  37495. */
  37496. get: function () {
  37497. return this._shadowsExposure;
  37498. },
  37499. /**
  37500. * Sets the shadows Exposure value.
  37501. * 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.
  37502. */
  37503. set: function (value) {
  37504. this._shadowsExposure = value;
  37505. this._dirty = true;
  37506. },
  37507. enumerable: true,
  37508. configurable: true
  37509. });
  37510. ColorCurves.prototype.getClassName = function () {
  37511. return "ColorCurves";
  37512. };
  37513. /**
  37514. * Binds the color curves to the shader.
  37515. * @param colorCurves The color curve to bind
  37516. * @param effect The effect to bind to
  37517. */
  37518. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37519. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37520. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37521. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37522. if (colorCurves._dirty) {
  37523. colorCurves._dirty = false;
  37524. // Fill in global info.
  37525. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37526. // Compute highlights info.
  37527. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37528. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37529. // Compute midtones info.
  37530. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37531. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37532. // Compute shadows info.
  37533. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37534. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37535. // Compute deltas (neutral is midtones).
  37536. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37537. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37538. }
  37539. if (effect) {
  37540. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37541. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37542. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37543. }
  37544. };
  37545. /**
  37546. * Prepare the list of uniforms associated with the ColorCurves effects.
  37547. * @param uniformsList The list of uniforms used in the effect
  37548. */
  37549. ColorCurves.PrepareUniforms = function (uniformsList) {
  37550. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37551. };
  37552. /**
  37553. * Returns color grading data based on a hue, density, saturation and exposure value.
  37554. * @param filterHue The hue of the color filter.
  37555. * @param filterDensity The density of the color filter.
  37556. * @param saturation The saturation.
  37557. * @param exposure The exposure.
  37558. * @param result The result data container.
  37559. */
  37560. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37561. if (hue == null) {
  37562. return;
  37563. }
  37564. hue = ColorCurves.clamp(hue, 0, 360);
  37565. density = ColorCurves.clamp(density, -100, 100);
  37566. saturation = ColorCurves.clamp(saturation, -100, 100);
  37567. exposure = ColorCurves.clamp(exposure, -100, 100);
  37568. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37569. // so that the maximum filter density is only 50% control. This provides fine control
  37570. // for small values and reasonable range.
  37571. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37572. density *= 0.5;
  37573. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37574. if (density < 0) {
  37575. density *= -1;
  37576. hue = (hue + 180) % 360;
  37577. }
  37578. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37579. result.scaleToRef(2, result);
  37580. result.a = 1 + 0.01 * saturation;
  37581. };
  37582. /**
  37583. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37584. * @param value The input slider value in range [-100,100].
  37585. * @returns Adjusted value.
  37586. */
  37587. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37588. value /= 100;
  37589. var x = Math.abs(value);
  37590. x = Math.pow(x, 2);
  37591. if (value < 0) {
  37592. x *= -1;
  37593. }
  37594. x *= 100;
  37595. return x;
  37596. };
  37597. /**
  37598. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37599. * @param hue The hue (H) input.
  37600. * @param saturation The saturation (S) input.
  37601. * @param brightness The brightness (B) input.
  37602. * @result An RGBA color represented as Vector4.
  37603. */
  37604. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37605. var h = ColorCurves.clamp(hue, 0, 360);
  37606. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37607. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37608. if (s === 0) {
  37609. result.r = v;
  37610. result.g = v;
  37611. result.b = v;
  37612. }
  37613. else {
  37614. // sector 0 to 5
  37615. h /= 60;
  37616. var i = Math.floor(h);
  37617. // fractional part of h
  37618. var f = h - i;
  37619. var p = v * (1 - s);
  37620. var q = v * (1 - s * f);
  37621. var t = v * (1 - s * (1 - f));
  37622. switch (i) {
  37623. case 0:
  37624. result.r = v;
  37625. result.g = t;
  37626. result.b = p;
  37627. break;
  37628. case 1:
  37629. result.r = q;
  37630. result.g = v;
  37631. result.b = p;
  37632. break;
  37633. case 2:
  37634. result.r = p;
  37635. result.g = v;
  37636. result.b = t;
  37637. break;
  37638. case 3:
  37639. result.r = p;
  37640. result.g = q;
  37641. result.b = v;
  37642. break;
  37643. case 4:
  37644. result.r = t;
  37645. result.g = p;
  37646. result.b = v;
  37647. break;
  37648. default:// case 5:
  37649. result.r = v;
  37650. result.g = p;
  37651. result.b = q;
  37652. break;
  37653. }
  37654. }
  37655. result.a = 1;
  37656. };
  37657. /**
  37658. * Returns a value clamped between min and max
  37659. * @param value The value to clamp
  37660. * @param min The minimum of value
  37661. * @param max The maximum of value
  37662. * @returns The clamped value.
  37663. */
  37664. ColorCurves.clamp = function (value, min, max) {
  37665. return Math.min(Math.max(value, min), max);
  37666. };
  37667. /**
  37668. * Clones the current color curve instance.
  37669. * @return The cloned curves
  37670. */
  37671. ColorCurves.prototype.clone = function () {
  37672. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37673. };
  37674. /**
  37675. * Serializes the current color curve instance to a json representation.
  37676. * @return a JSON representation
  37677. */
  37678. ColorCurves.prototype.serialize = function () {
  37679. return BABYLON.SerializationHelper.Serialize(this);
  37680. };
  37681. /**
  37682. * Parses the color curve from a json representation.
  37683. * @param source the JSON source to parse
  37684. * @return The parsed curves
  37685. */
  37686. ColorCurves.Parse = function (source) {
  37687. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37688. };
  37689. __decorate([
  37690. BABYLON.serialize()
  37691. ], ColorCurves.prototype, "_globalHue", void 0);
  37692. __decorate([
  37693. BABYLON.serialize()
  37694. ], ColorCurves.prototype, "_globalDensity", void 0);
  37695. __decorate([
  37696. BABYLON.serialize()
  37697. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37698. __decorate([
  37699. BABYLON.serialize()
  37700. ], ColorCurves.prototype, "_globalExposure", void 0);
  37701. __decorate([
  37702. BABYLON.serialize()
  37703. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37704. __decorate([
  37705. BABYLON.serialize()
  37706. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37707. __decorate([
  37708. BABYLON.serialize()
  37709. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37710. __decorate([
  37711. BABYLON.serialize()
  37712. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37713. __decorate([
  37714. BABYLON.serialize()
  37715. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37716. __decorate([
  37717. BABYLON.serialize()
  37718. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37719. __decorate([
  37720. BABYLON.serialize()
  37721. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37722. __decorate([
  37723. BABYLON.serialize()
  37724. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37725. return ColorCurves;
  37726. }());
  37727. BABYLON.ColorCurves = ColorCurves;
  37728. })(BABYLON || (BABYLON = {}));
  37729. //# sourceMappingURL=babylon.colorCurves.js.map
  37730. //# sourceMappingURL=babylon.behavior.js.map
  37731. var BABYLON;
  37732. (function (BABYLON) {
  37733. /**
  37734. * "Static Class" containing the most commonly used helper while dealing with material for
  37735. * rendering purpose.
  37736. *
  37737. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37738. *
  37739. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37740. */
  37741. var MaterialHelper = /** @class */ (function () {
  37742. function MaterialHelper() {
  37743. }
  37744. /**
  37745. * Bind the current view position to an effect.
  37746. * @param effect The effect to be bound
  37747. * @param scene The scene the eyes position is used from
  37748. */
  37749. MaterialHelper.BindEyePosition = function (effect, scene) {
  37750. if (scene._forcedViewPosition) {
  37751. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37752. return;
  37753. }
  37754. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37755. };
  37756. /**
  37757. * Helps preparing the defines values about the UVs in used in the effect.
  37758. * UVs are shared as much as we can accross chanels in the shaders.
  37759. * @param texture The texture we are preparing the UVs for
  37760. * @param defines The defines to update
  37761. * @param key The chanel key "diffuse", "specular"... used in the shader
  37762. */
  37763. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37764. defines._needUVs = true;
  37765. defines[key] = true;
  37766. if (texture.getTextureMatrix().isIdentity(true)) {
  37767. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37768. if (texture.coordinatesIndex === 0) {
  37769. defines["MAINUV1"] = true;
  37770. }
  37771. else {
  37772. defines["MAINUV2"] = true;
  37773. }
  37774. }
  37775. else {
  37776. defines[key + "DIRECTUV"] = 0;
  37777. }
  37778. };
  37779. /**
  37780. * Binds a texture matrix value to its corrsponding uniform
  37781. * @param texture The texture to bind the matrix for
  37782. * @param uniformBuffer The uniform buffer receivin the data
  37783. * @param key The chanel key "diffuse", "specular"... used in the shader
  37784. */
  37785. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37786. var matrix = texture.getTextureMatrix();
  37787. if (!matrix.isIdentity(true)) {
  37788. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37789. }
  37790. };
  37791. /**
  37792. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37793. * @param mesh defines the current mesh
  37794. * @param scene defines the current scene
  37795. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37796. * @param pointsCloud defines if point cloud rendering has to be turned on
  37797. * @param fogEnabled defines if fog has to be turned on
  37798. * @param alphaTest defines if alpha testing has to be turned on
  37799. * @param defines defines the current list of defines
  37800. */
  37801. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37802. if (defines._areMiscDirty) {
  37803. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37804. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37805. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37806. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37807. defines["ALPHATEST"] = alphaTest;
  37808. }
  37809. };
  37810. /**
  37811. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37812. * @param scene defines the current scene
  37813. * @param engine defines the current engine
  37814. * @param defines specifies the list of active defines
  37815. * @param useInstances defines if instances have to be turned on
  37816. * @param useClipPlane defines if clip plane have to be turned on
  37817. */
  37818. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37819. if (useClipPlane === void 0) { useClipPlane = null; }
  37820. var changed = false;
  37821. if (useClipPlane == null) {
  37822. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37823. }
  37824. if (defines["CLIPPLANE"] !== useClipPlane) {
  37825. defines["CLIPPLANE"] = useClipPlane;
  37826. changed = true;
  37827. }
  37828. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37829. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37830. changed = true;
  37831. }
  37832. if (defines["INSTANCES"] !== useInstances) {
  37833. defines["INSTANCES"] = useInstances;
  37834. changed = true;
  37835. }
  37836. if (changed) {
  37837. defines.markAsUnprocessed();
  37838. }
  37839. };
  37840. /**
  37841. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37842. * @param mesh The mesh containing the geometry data we will draw
  37843. * @param defines The defines to update
  37844. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37845. * @param useBones Precise whether bones should be used or not (override mesh info)
  37846. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37847. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37848. * @returns false if defines are considered not dirty and have not been checked
  37849. */
  37850. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37851. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37852. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37853. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37854. return false;
  37855. }
  37856. defines._normals = defines._needNormals;
  37857. defines._uvs = defines._needUVs;
  37858. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37859. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37860. defines["TANGENT"] = true;
  37861. }
  37862. if (defines._needUVs) {
  37863. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37864. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37865. }
  37866. else {
  37867. defines["UV1"] = false;
  37868. defines["UV2"] = false;
  37869. }
  37870. if (useVertexColor) {
  37871. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37872. defines["VERTEXCOLOR"] = hasVertexColors;
  37873. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37874. }
  37875. if (useBones) {
  37876. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37877. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37878. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37879. }
  37880. else {
  37881. defines["NUM_BONE_INFLUENCERS"] = 0;
  37882. defines["BonesPerMesh"] = 0;
  37883. }
  37884. }
  37885. if (useMorphTargets) {
  37886. var manager = mesh.morphTargetManager;
  37887. if (manager) {
  37888. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37889. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37890. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37891. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37892. }
  37893. else {
  37894. defines["MORPHTARGETS_TANGENT"] = false;
  37895. defines["MORPHTARGETS_NORMAL"] = false;
  37896. defines["MORPHTARGETS"] = false;
  37897. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37898. }
  37899. }
  37900. return true;
  37901. };
  37902. /**
  37903. * Prepares the defines related to the light information passed in parameter
  37904. * @param scene The scene we are intending to draw
  37905. * @param mesh The mesh the effect is compiling for
  37906. * @param defines The defines to update
  37907. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37908. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37909. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37910. * @returns true if normals will be required for the rest of the effect
  37911. */
  37912. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37913. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37914. if (disableLighting === void 0) { disableLighting = false; }
  37915. if (!defines._areLightsDirty) {
  37916. return defines._needNormals;
  37917. }
  37918. var lightIndex = 0;
  37919. var needNormals = false;
  37920. var needRebuild = false;
  37921. var lightmapMode = false;
  37922. var shadowEnabled = false;
  37923. var specularEnabled = false;
  37924. if (scene.lightsEnabled && !disableLighting) {
  37925. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37926. var light = _a[_i];
  37927. needNormals = true;
  37928. if (defines["LIGHT" + lightIndex] === undefined) {
  37929. needRebuild = true;
  37930. }
  37931. defines["LIGHT" + lightIndex] = true;
  37932. defines["SPOTLIGHT" + lightIndex] = false;
  37933. defines["HEMILIGHT" + lightIndex] = false;
  37934. defines["POINTLIGHT" + lightIndex] = false;
  37935. defines["DIRLIGHT" + lightIndex] = false;
  37936. var type;
  37937. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37938. type = "SPOTLIGHT" + lightIndex;
  37939. var spotLight = light;
  37940. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37941. }
  37942. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37943. type = "HEMILIGHT" + lightIndex;
  37944. }
  37945. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37946. type = "POINTLIGHT" + lightIndex;
  37947. }
  37948. else {
  37949. type = "DIRLIGHT" + lightIndex;
  37950. }
  37951. defines[type] = true;
  37952. // Specular
  37953. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37954. specularEnabled = true;
  37955. }
  37956. // Shadows
  37957. defines["SHADOW" + lightIndex] = false;
  37958. defines["SHADOWPCF" + lightIndex] = false;
  37959. defines["SHADOWESM" + lightIndex] = false;
  37960. defines["SHADOWCUBE" + lightIndex] = false;
  37961. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37962. var shadowGenerator = light.getShadowGenerator();
  37963. if (shadowGenerator) {
  37964. shadowEnabled = true;
  37965. shadowGenerator.prepareDefines(defines, lightIndex);
  37966. }
  37967. }
  37968. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37969. lightmapMode = true;
  37970. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37971. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37972. }
  37973. else {
  37974. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37975. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37976. }
  37977. lightIndex++;
  37978. if (lightIndex === maxSimultaneousLights)
  37979. break;
  37980. }
  37981. }
  37982. defines["SPECULARTERM"] = specularEnabled;
  37983. defines["SHADOWS"] = shadowEnabled;
  37984. // Resetting all other lights if any
  37985. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37986. if (defines["LIGHT" + index] !== undefined) {
  37987. defines["LIGHT" + index] = false;
  37988. defines["HEMILIGHT" + lightIndex] = false;
  37989. defines["POINTLIGHT" + lightIndex] = false;
  37990. defines["DIRLIGHT" + lightIndex] = false;
  37991. defines["SPOTLIGHT" + lightIndex] = false;
  37992. defines["SHADOW" + lightIndex] = false;
  37993. }
  37994. }
  37995. var caps = scene.getEngine().getCaps();
  37996. if (defines["SHADOWFLOAT"] === undefined) {
  37997. needRebuild = true;
  37998. }
  37999. defines["SHADOWFLOAT"] = shadowEnabled &&
  38000. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38001. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38002. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38003. if (needRebuild) {
  38004. defines.rebuild();
  38005. }
  38006. return needNormals;
  38007. };
  38008. /**
  38009. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38010. * that won t be acctive due to defines being turned off.
  38011. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38012. * @param samplersList The samplers list
  38013. * @param defines The defines helping in the list generation
  38014. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38015. */
  38016. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38017. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38018. var uniformsList;
  38019. var uniformBuffersList = null;
  38020. if (uniformsListOrOptions.uniformsNames) {
  38021. var options = uniformsListOrOptions;
  38022. uniformsList = options.uniformsNames;
  38023. uniformBuffersList = options.uniformBuffersNames;
  38024. samplersList = options.samplers;
  38025. defines = options.defines;
  38026. maxSimultaneousLights = options.maxSimultaneousLights;
  38027. }
  38028. else {
  38029. uniformsList = uniformsListOrOptions;
  38030. if (!samplersList) {
  38031. samplersList = [];
  38032. }
  38033. }
  38034. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38035. if (!defines["LIGHT" + lightIndex]) {
  38036. break;
  38037. }
  38038. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38039. if (uniformBuffersList) {
  38040. uniformBuffersList.push("Light" + lightIndex);
  38041. }
  38042. samplersList.push("shadowSampler" + lightIndex);
  38043. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38044. samplersList.push("projectionLightSampler" + lightIndex);
  38045. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38046. }
  38047. }
  38048. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38049. uniformsList.push("morphTargetInfluences");
  38050. }
  38051. };
  38052. /**
  38053. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38054. * @param defines The defines to update while falling back
  38055. * @param fallbacks The authorized effect fallbacks
  38056. * @param maxSimultaneousLights The maximum number of lights allowed
  38057. * @param rank the current rank of the Effect
  38058. * @returns The newly affected rank
  38059. */
  38060. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38061. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38062. if (rank === void 0) { rank = 0; }
  38063. var lightFallbackRank = 0;
  38064. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38065. if (!defines["LIGHT" + lightIndex]) {
  38066. break;
  38067. }
  38068. if (lightIndex > 0) {
  38069. lightFallbackRank = rank + lightIndex;
  38070. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38071. }
  38072. if (!defines["SHADOWS"]) {
  38073. if (defines["SHADOW" + lightIndex]) {
  38074. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38075. }
  38076. if (defines["SHADOWPCF" + lightIndex]) {
  38077. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38078. }
  38079. if (defines["SHADOWESM" + lightIndex]) {
  38080. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38081. }
  38082. }
  38083. }
  38084. return lightFallbackRank++;
  38085. };
  38086. /**
  38087. * Prepares the list of attributes required for morph targets according to the effect defines.
  38088. * @param attribs The current list of supported attribs
  38089. * @param mesh The mesh to prepare the morph targets attributes for
  38090. * @param defines The current Defines of the effect
  38091. */
  38092. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38093. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38094. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38095. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38096. var manager = mesh.morphTargetManager;
  38097. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38098. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38099. for (var index = 0; index < influencers; index++) {
  38100. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38101. if (normal) {
  38102. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38103. }
  38104. if (tangent) {
  38105. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38106. }
  38107. if (attribs.length > maxAttributesCount) {
  38108. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38109. }
  38110. }
  38111. }
  38112. };
  38113. /**
  38114. * Prepares the list of attributes required for bones according to the effect defines.
  38115. * @param attribs The current list of supported attribs
  38116. * @param mesh The mesh to prepare the bones attributes for
  38117. * @param defines The current Defines of the effect
  38118. * @param fallbacks The current efffect fallback strategy
  38119. */
  38120. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38121. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38122. fallbacks.addCPUSkinningFallback(0, mesh);
  38123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38125. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38126. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38127. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38128. }
  38129. }
  38130. };
  38131. /**
  38132. * Prepares the list of attributes required for instances according to the effect defines.
  38133. * @param attribs The current list of supported attribs
  38134. * @param defines The current Defines of the effect
  38135. */
  38136. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38137. if (defines["INSTANCES"]) {
  38138. attribs.push("world0");
  38139. attribs.push("world1");
  38140. attribs.push("world2");
  38141. attribs.push("world3");
  38142. }
  38143. };
  38144. /**
  38145. * Binds the light shadow information to the effect for the given mesh.
  38146. * @param light The light containing the generator
  38147. * @param scene The scene the lights belongs to
  38148. * @param mesh The mesh we are binding the information to render
  38149. * @param lightIndex The light index in the effect used to render the mesh
  38150. * @param effect The effect we are binding the data to
  38151. */
  38152. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38153. if (light.shadowEnabled && mesh.receiveShadows) {
  38154. var shadowGenerator = light.getShadowGenerator();
  38155. if (shadowGenerator) {
  38156. shadowGenerator.bindShadowLight(lightIndex, effect);
  38157. }
  38158. }
  38159. };
  38160. /**
  38161. * Binds the light information to the effect.
  38162. * @param light The light containing the generator
  38163. * @param effect The effect we are binding the data to
  38164. * @param lightIndex The light index in the effect used to render
  38165. */
  38166. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38167. light.transferToEffect(effect, lightIndex + "");
  38168. };
  38169. /**
  38170. * Binds the lights information from the scene to the effect for the given mesh.
  38171. * @param scene The scene the lights belongs to
  38172. * @param mesh The mesh we are binding the information to render
  38173. * @param effect The effect we are binding the data to
  38174. * @param defines The generated defines for the effect
  38175. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38176. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38177. */
  38178. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38179. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38180. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38181. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38182. for (var i = 0; i < len; i++) {
  38183. var light = mesh._lightSources[i];
  38184. var iAsString = i.toString();
  38185. var scaledIntensity = light.getScaledIntensity();
  38186. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38187. MaterialHelper.BindLightProperties(light, effect, i);
  38188. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38189. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38190. if (defines["SPECULARTERM"]) {
  38191. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38192. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38193. }
  38194. // Shadows
  38195. if (scene.shadowsEnabled) {
  38196. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38197. }
  38198. light._uniformBuffer.update();
  38199. }
  38200. };
  38201. /**
  38202. * Binds the fog information from the scene to the effect for the given mesh.
  38203. * @param scene The scene the lights belongs to
  38204. * @param mesh The mesh we are binding the information to render
  38205. * @param effect The effect we are binding the data to
  38206. */
  38207. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38208. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38209. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38210. effect.setColor3("vFogColor", scene.fogColor);
  38211. }
  38212. };
  38213. /**
  38214. * Binds the bones information from the mesh to the effect.
  38215. * @param mesh The mesh we are binding the information to render
  38216. * @param effect The effect we are binding the data to
  38217. */
  38218. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38219. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38220. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38221. if (matrices && effect) {
  38222. effect.setMatrices("mBones", matrices);
  38223. }
  38224. }
  38225. };
  38226. /**
  38227. * Binds the morph targets information from the mesh to the effect.
  38228. * @param abstractMesh The mesh we are binding the information to render
  38229. * @param effect The effect we are binding the data to
  38230. */
  38231. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38232. var manager = abstractMesh.morphTargetManager;
  38233. if (!abstractMesh || !manager) {
  38234. return;
  38235. }
  38236. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38237. };
  38238. /**
  38239. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38240. * @param defines The generated defines used in the effect
  38241. * @param effect The effect we are binding the data to
  38242. * @param scene The scene we are willing to render with logarithmic scale for
  38243. */
  38244. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38245. if (defines["LOGARITHMICDEPTH"]) {
  38246. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38247. }
  38248. };
  38249. /**
  38250. * Binds the clip plane information from the scene to the effect.
  38251. * @param scene The scene the clip plane information are extracted from
  38252. * @param effect The effect we are binding the data to
  38253. */
  38254. MaterialHelper.BindClipPlane = function (effect, scene) {
  38255. if (scene.clipPlane) {
  38256. var clipPlane = scene.clipPlane;
  38257. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38258. }
  38259. };
  38260. return MaterialHelper;
  38261. }());
  38262. BABYLON.MaterialHelper = MaterialHelper;
  38263. })(BABYLON || (BABYLON = {}));
  38264. //# sourceMappingURL=babylon.materialHelper.js.map
  38265. var BABYLON;
  38266. (function (BABYLON) {
  38267. var PushMaterial = /** @class */ (function (_super) {
  38268. __extends(PushMaterial, _super);
  38269. function PushMaterial(name, scene) {
  38270. var _this = _super.call(this, name, scene) || this;
  38271. _this._normalMatrix = new BABYLON.Matrix();
  38272. _this.storeEffectOnSubMeshes = true;
  38273. return _this;
  38274. }
  38275. PushMaterial.prototype.getEffect = function () {
  38276. return this._activeEffect;
  38277. };
  38278. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38279. if (!mesh) {
  38280. return false;
  38281. }
  38282. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38283. return true;
  38284. }
  38285. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38286. };
  38287. /**
  38288. * Binds the given world matrix to the active effect
  38289. *
  38290. * @param world the matrix to bind
  38291. */
  38292. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38293. this._activeEffect.setMatrix("world", world);
  38294. };
  38295. /**
  38296. * Binds the given normal matrix to the active effect
  38297. *
  38298. * @param normalMatrix the matrix to bind
  38299. */
  38300. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38301. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38302. };
  38303. PushMaterial.prototype.bind = function (world, mesh) {
  38304. if (!mesh) {
  38305. return;
  38306. }
  38307. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38308. };
  38309. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38310. if (effect === void 0) { effect = null; }
  38311. _super.prototype._afterBind.call(this, mesh);
  38312. this.getScene()._cachedEffect = effect;
  38313. };
  38314. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38315. if (visibility === void 0) { visibility = 1; }
  38316. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38317. };
  38318. return PushMaterial;
  38319. }(BABYLON.Material));
  38320. BABYLON.PushMaterial = PushMaterial;
  38321. })(BABYLON || (BABYLON = {}));
  38322. //# sourceMappingURL=babylon.pushMaterial.js.map
  38323. var BABYLON;
  38324. (function (BABYLON) {
  38325. /** @ignore */
  38326. var StandardMaterialDefines = /** @class */ (function (_super) {
  38327. __extends(StandardMaterialDefines, _super);
  38328. function StandardMaterialDefines() {
  38329. var _this = _super.call(this) || this;
  38330. _this.MAINUV1 = false;
  38331. _this.MAINUV2 = false;
  38332. _this.DIFFUSE = false;
  38333. _this.DIFFUSEDIRECTUV = 0;
  38334. _this.AMBIENT = false;
  38335. _this.AMBIENTDIRECTUV = 0;
  38336. _this.OPACITY = false;
  38337. _this.OPACITYDIRECTUV = 0;
  38338. _this.OPACITYRGB = false;
  38339. _this.REFLECTION = false;
  38340. _this.EMISSIVE = false;
  38341. _this.EMISSIVEDIRECTUV = 0;
  38342. _this.SPECULAR = false;
  38343. _this.SPECULARDIRECTUV = 0;
  38344. _this.BUMP = false;
  38345. _this.BUMPDIRECTUV = 0;
  38346. _this.PARALLAX = false;
  38347. _this.PARALLAXOCCLUSION = false;
  38348. _this.SPECULAROVERALPHA = false;
  38349. _this.CLIPPLANE = false;
  38350. _this.ALPHATEST = false;
  38351. _this.DEPTHPREPASS = false;
  38352. _this.ALPHAFROMDIFFUSE = false;
  38353. _this.POINTSIZE = false;
  38354. _this.FOG = false;
  38355. _this.SPECULARTERM = false;
  38356. _this.DIFFUSEFRESNEL = false;
  38357. _this.OPACITYFRESNEL = false;
  38358. _this.REFLECTIONFRESNEL = false;
  38359. _this.REFRACTIONFRESNEL = false;
  38360. _this.EMISSIVEFRESNEL = false;
  38361. _this.FRESNEL = false;
  38362. _this.NORMAL = false;
  38363. _this.UV1 = false;
  38364. _this.UV2 = false;
  38365. _this.VERTEXCOLOR = false;
  38366. _this.VERTEXALPHA = false;
  38367. _this.NUM_BONE_INFLUENCERS = 0;
  38368. _this.BonesPerMesh = 0;
  38369. _this.INSTANCES = false;
  38370. _this.GLOSSINESS = false;
  38371. _this.ROUGHNESS = false;
  38372. _this.EMISSIVEASILLUMINATION = false;
  38373. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38374. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38375. _this.LIGHTMAP = false;
  38376. _this.LIGHTMAPDIRECTUV = 0;
  38377. _this.OBJECTSPACE_NORMALMAP = false;
  38378. _this.USELIGHTMAPASSHADOWMAP = false;
  38379. _this.REFLECTIONMAP_3D = false;
  38380. _this.REFLECTIONMAP_SPHERICAL = false;
  38381. _this.REFLECTIONMAP_PLANAR = false;
  38382. _this.REFLECTIONMAP_CUBIC = false;
  38383. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38384. _this.REFLECTIONMAP_PROJECTION = false;
  38385. _this.REFLECTIONMAP_SKYBOX = false;
  38386. _this.REFLECTIONMAP_EXPLICIT = false;
  38387. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38388. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38389. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38390. _this.INVERTCUBICMAP = false;
  38391. _this.LOGARITHMICDEPTH = false;
  38392. _this.REFRACTION = false;
  38393. _this.REFRACTIONMAP_3D = false;
  38394. _this.REFLECTIONOVERALPHA = false;
  38395. _this.TWOSIDEDLIGHTING = false;
  38396. _this.SHADOWFLOAT = false;
  38397. _this.MORPHTARGETS = false;
  38398. _this.MORPHTARGETS_NORMAL = false;
  38399. _this.MORPHTARGETS_TANGENT = false;
  38400. _this.NUM_MORPH_INFLUENCERS = 0;
  38401. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38402. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38403. _this.IMAGEPROCESSING = false;
  38404. _this.VIGNETTE = false;
  38405. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38406. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38407. _this.TONEMAPPING = false;
  38408. _this.CONTRAST = false;
  38409. _this.COLORCURVES = false;
  38410. _this.COLORGRADING = false;
  38411. _this.COLORGRADING3D = false;
  38412. _this.SAMPLER3DGREENDEPTH = false;
  38413. _this.SAMPLER3DBGRMAP = false;
  38414. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38415. _this.EXPOSURE = false;
  38416. _this.rebuild();
  38417. return _this;
  38418. }
  38419. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38420. var modes = [
  38421. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38422. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38423. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38424. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38425. ];
  38426. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38427. var mode = modes_1[_i];
  38428. this[mode] = (mode === modeToEnable);
  38429. }
  38430. };
  38431. return StandardMaterialDefines;
  38432. }(BABYLON.MaterialDefines));
  38433. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38434. var StandardMaterial = /** @class */ (function (_super) {
  38435. __extends(StandardMaterial, _super);
  38436. function StandardMaterial(name, scene) {
  38437. var _this = _super.call(this, name, scene) || this;
  38438. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38439. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38440. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38441. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38442. _this.specularPower = 64;
  38443. _this._useAlphaFromDiffuseTexture = false;
  38444. _this._useEmissiveAsIllumination = false;
  38445. _this._linkEmissiveWithDiffuse = false;
  38446. _this._useSpecularOverAlpha = false;
  38447. _this._useReflectionOverAlpha = false;
  38448. _this._disableLighting = false;
  38449. _this._useObjectSpaceNormalMap = false;
  38450. _this._useParallax = false;
  38451. _this._useParallaxOcclusion = false;
  38452. _this.parallaxScaleBias = 0.05;
  38453. _this._roughness = 0;
  38454. _this.indexOfRefraction = 0.98;
  38455. _this.invertRefractionY = true;
  38456. _this._useLightmapAsShadowmap = false;
  38457. _this._useReflectionFresnelFromSpecular = false;
  38458. _this._useGlossinessFromSpecularMapAlpha = false;
  38459. _this._maxSimultaneousLights = 4;
  38460. /**
  38461. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38462. */
  38463. _this._invertNormalMapX = false;
  38464. /**
  38465. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38466. */
  38467. _this._invertNormalMapY = false;
  38468. /**
  38469. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38470. */
  38471. _this._twoSidedLighting = false;
  38472. _this._renderTargets = new BABYLON.SmartArray(16);
  38473. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38474. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38475. // Setup the default processing configuration to the scene.
  38476. _this._attachImageProcessingConfiguration(null);
  38477. _this.getRenderTargetTextures = function () {
  38478. _this._renderTargets.reset();
  38479. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38480. _this._renderTargets.push(_this._reflectionTexture);
  38481. }
  38482. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38483. _this._renderTargets.push(_this._refractionTexture);
  38484. }
  38485. return _this._renderTargets;
  38486. };
  38487. return _this;
  38488. }
  38489. ;
  38490. ;
  38491. ;
  38492. ;
  38493. ;
  38494. ;
  38495. ;
  38496. ;
  38497. ;
  38498. ;
  38499. ;
  38500. ;
  38501. ;
  38502. ;
  38503. ;
  38504. ;
  38505. ;
  38506. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38507. /**
  38508. * Gets the image processing configuration used either in this material.
  38509. */
  38510. get: function () {
  38511. return this._imageProcessingConfiguration;
  38512. },
  38513. /**
  38514. * Sets the Default image processing configuration used either in the this material.
  38515. *
  38516. * If sets to null, the scene one is in use.
  38517. */
  38518. set: function (value) {
  38519. this._attachImageProcessingConfiguration(value);
  38520. // Ensure the effect will be rebuilt.
  38521. this._markAllSubMeshesAsTexturesDirty();
  38522. },
  38523. enumerable: true,
  38524. configurable: true
  38525. });
  38526. /**
  38527. * Attaches a new image processing configuration to the Standard Material.
  38528. * @param configuration
  38529. */
  38530. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38531. var _this = this;
  38532. if (configuration === this._imageProcessingConfiguration) {
  38533. return;
  38534. }
  38535. // Detaches observer.
  38536. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38537. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38538. }
  38539. // Pick the scene configuration if needed.
  38540. if (!configuration) {
  38541. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38542. }
  38543. else {
  38544. this._imageProcessingConfiguration = configuration;
  38545. }
  38546. // Attaches observer.
  38547. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38548. _this._markAllSubMeshesAsImageProcessingDirty();
  38549. });
  38550. };
  38551. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38552. /**
  38553. * Gets wether the color curves effect is enabled.
  38554. */
  38555. get: function () {
  38556. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38557. },
  38558. /**
  38559. * Sets wether the color curves effect is enabled.
  38560. */
  38561. set: function (value) {
  38562. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38563. },
  38564. enumerable: true,
  38565. configurable: true
  38566. });
  38567. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38568. /**
  38569. * Gets wether the color grading effect is enabled.
  38570. */
  38571. get: function () {
  38572. return this.imageProcessingConfiguration.colorGradingEnabled;
  38573. },
  38574. /**
  38575. * Gets wether the color grading effect is enabled.
  38576. */
  38577. set: function (value) {
  38578. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38579. },
  38580. enumerable: true,
  38581. configurable: true
  38582. });
  38583. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38584. /**
  38585. * Gets wether tonemapping is enabled or not.
  38586. */
  38587. get: function () {
  38588. return this._imageProcessingConfiguration.toneMappingEnabled;
  38589. },
  38590. /**
  38591. * Sets wether tonemapping is enabled or not
  38592. */
  38593. set: function (value) {
  38594. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38595. },
  38596. enumerable: true,
  38597. configurable: true
  38598. });
  38599. ;
  38600. ;
  38601. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38602. /**
  38603. * The camera exposure used on this material.
  38604. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38605. * This corresponds to a photographic exposure.
  38606. */
  38607. get: function () {
  38608. return this._imageProcessingConfiguration.exposure;
  38609. },
  38610. /**
  38611. * The camera exposure used on this material.
  38612. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38613. * This corresponds to a photographic exposure.
  38614. */
  38615. set: function (value) {
  38616. this._imageProcessingConfiguration.exposure = value;
  38617. },
  38618. enumerable: true,
  38619. configurable: true
  38620. });
  38621. ;
  38622. ;
  38623. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38624. /**
  38625. * Gets The camera contrast used on this material.
  38626. */
  38627. get: function () {
  38628. return this._imageProcessingConfiguration.contrast;
  38629. },
  38630. /**
  38631. * Sets The camera contrast used on this material.
  38632. */
  38633. set: function (value) {
  38634. this._imageProcessingConfiguration.contrast = value;
  38635. },
  38636. enumerable: true,
  38637. configurable: true
  38638. });
  38639. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38640. /**
  38641. * Gets the Color Grading 2D Lookup Texture.
  38642. */
  38643. get: function () {
  38644. return this._imageProcessingConfiguration.colorGradingTexture;
  38645. },
  38646. /**
  38647. * Sets the Color Grading 2D Lookup Texture.
  38648. */
  38649. set: function (value) {
  38650. this._imageProcessingConfiguration.colorGradingTexture = value;
  38651. },
  38652. enumerable: true,
  38653. configurable: true
  38654. });
  38655. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38656. /**
  38657. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38658. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38659. * 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;
  38660. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38661. */
  38662. get: function () {
  38663. return this._imageProcessingConfiguration.colorCurves;
  38664. },
  38665. /**
  38666. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38667. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38668. * 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;
  38669. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38670. */
  38671. set: function (value) {
  38672. this._imageProcessingConfiguration.colorCurves = value;
  38673. },
  38674. enumerable: true,
  38675. configurable: true
  38676. });
  38677. StandardMaterial.prototype.getClassName = function () {
  38678. return "StandardMaterial";
  38679. };
  38680. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38681. get: function () {
  38682. return this._useLogarithmicDepth;
  38683. },
  38684. set: function (value) {
  38685. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38686. this._markAllSubMeshesAsMiscDirty();
  38687. },
  38688. enumerable: true,
  38689. configurable: true
  38690. });
  38691. StandardMaterial.prototype.needAlphaBlending = function () {
  38692. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38693. };
  38694. StandardMaterial.prototype.needAlphaTesting = function () {
  38695. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38696. };
  38697. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38698. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38699. };
  38700. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38701. return this._diffuseTexture;
  38702. };
  38703. /**
  38704. * Child classes can use it to update shaders
  38705. */
  38706. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38707. if (useInstances === void 0) { useInstances = false; }
  38708. if (subMesh.effect && this.isFrozen) {
  38709. if (this._wasPreviouslyReady && subMesh.effect) {
  38710. return true;
  38711. }
  38712. }
  38713. if (!subMesh._materialDefines) {
  38714. subMesh._materialDefines = new StandardMaterialDefines();
  38715. }
  38716. var scene = this.getScene();
  38717. var defines = subMesh._materialDefines;
  38718. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38719. if (defines._renderId === scene.getRenderId()) {
  38720. return true;
  38721. }
  38722. }
  38723. var engine = scene.getEngine();
  38724. // Lights
  38725. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38726. // Textures
  38727. if (defines._areTexturesDirty) {
  38728. defines._needUVs = false;
  38729. defines.MAINUV1 = false;
  38730. defines.MAINUV2 = false;
  38731. if (scene.texturesEnabled) {
  38732. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38733. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38734. return false;
  38735. }
  38736. else {
  38737. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38738. }
  38739. }
  38740. else {
  38741. defines.DIFFUSE = false;
  38742. }
  38743. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38744. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38745. return false;
  38746. }
  38747. else {
  38748. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38749. }
  38750. }
  38751. else {
  38752. defines.AMBIENT = false;
  38753. }
  38754. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38755. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38756. return false;
  38757. }
  38758. else {
  38759. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38760. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38761. }
  38762. }
  38763. else {
  38764. defines.OPACITY = false;
  38765. }
  38766. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38767. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38768. return false;
  38769. }
  38770. else {
  38771. defines._needNormals = true;
  38772. defines.REFLECTION = true;
  38773. defines.ROUGHNESS = (this._roughness > 0);
  38774. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38775. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38776. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38777. switch (this._reflectionTexture.coordinatesMode) {
  38778. case BABYLON.Texture.CUBIC_MODE:
  38779. case BABYLON.Texture.INVCUBIC_MODE:
  38780. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38781. break;
  38782. case BABYLON.Texture.EXPLICIT_MODE:
  38783. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38784. break;
  38785. case BABYLON.Texture.PLANAR_MODE:
  38786. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38787. break;
  38788. case BABYLON.Texture.PROJECTION_MODE:
  38789. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38790. break;
  38791. case BABYLON.Texture.SKYBOX_MODE:
  38792. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38793. break;
  38794. case BABYLON.Texture.SPHERICAL_MODE:
  38795. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38796. break;
  38797. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38798. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38799. break;
  38800. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38801. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38802. break;
  38803. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38804. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38805. break;
  38806. }
  38807. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38808. }
  38809. }
  38810. else {
  38811. defines.REFLECTION = false;
  38812. }
  38813. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38814. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38815. return false;
  38816. }
  38817. else {
  38818. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38819. }
  38820. }
  38821. else {
  38822. defines.EMISSIVE = false;
  38823. }
  38824. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38825. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38826. return false;
  38827. }
  38828. else {
  38829. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38830. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38831. }
  38832. }
  38833. else {
  38834. defines.LIGHTMAP = false;
  38835. }
  38836. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38837. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38838. return false;
  38839. }
  38840. else {
  38841. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38842. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38843. }
  38844. }
  38845. else {
  38846. defines.SPECULAR = false;
  38847. }
  38848. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38849. // Bump texure can not be not blocking.
  38850. if (!this._bumpTexture.isReady()) {
  38851. return false;
  38852. }
  38853. else {
  38854. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38855. defines.PARALLAX = this._useParallax;
  38856. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38857. }
  38858. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  38859. }
  38860. else {
  38861. defines.BUMP = false;
  38862. }
  38863. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38864. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38865. return false;
  38866. }
  38867. else {
  38868. defines._needUVs = true;
  38869. defines.REFRACTION = true;
  38870. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38871. }
  38872. }
  38873. else {
  38874. defines.REFRACTION = false;
  38875. }
  38876. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38877. }
  38878. else {
  38879. defines.DIFFUSE = false;
  38880. defines.AMBIENT = false;
  38881. defines.OPACITY = false;
  38882. defines.REFLECTION = false;
  38883. defines.EMISSIVE = false;
  38884. defines.LIGHTMAP = false;
  38885. defines.BUMP = false;
  38886. defines.REFRACTION = false;
  38887. }
  38888. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38889. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38890. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38891. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38892. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38893. }
  38894. if (defines._areImageProcessingDirty) {
  38895. if (!this._imageProcessingConfiguration.isReady()) {
  38896. return false;
  38897. }
  38898. this._imageProcessingConfiguration.prepareDefines(defines);
  38899. }
  38900. if (defines._areFresnelDirty) {
  38901. if (StandardMaterial.FresnelEnabled) {
  38902. // Fresnel
  38903. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38904. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38905. this._reflectionFresnelParameters) {
  38906. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38907. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38908. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38909. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38910. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38911. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38912. defines._needNormals = true;
  38913. defines.FRESNEL = true;
  38914. }
  38915. }
  38916. else {
  38917. defines.FRESNEL = false;
  38918. }
  38919. }
  38920. // Misc.
  38921. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38922. // Attribs
  38923. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38924. // Values that need to be evaluated on every frame
  38925. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38926. // Get correct effect
  38927. if (defines.isDirty) {
  38928. defines.markAsProcessed();
  38929. scene.resetCachedMaterial();
  38930. // Fallbacks
  38931. var fallbacks = new BABYLON.EffectFallbacks();
  38932. if (defines.REFLECTION) {
  38933. fallbacks.addFallback(0, "REFLECTION");
  38934. }
  38935. if (defines.SPECULAR) {
  38936. fallbacks.addFallback(0, "SPECULAR");
  38937. }
  38938. if (defines.BUMP) {
  38939. fallbacks.addFallback(0, "BUMP");
  38940. }
  38941. if (defines.PARALLAX) {
  38942. fallbacks.addFallback(1, "PARALLAX");
  38943. }
  38944. if (defines.PARALLAXOCCLUSION) {
  38945. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38946. }
  38947. if (defines.SPECULAROVERALPHA) {
  38948. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38949. }
  38950. if (defines.FOG) {
  38951. fallbacks.addFallback(1, "FOG");
  38952. }
  38953. if (defines.POINTSIZE) {
  38954. fallbacks.addFallback(0, "POINTSIZE");
  38955. }
  38956. if (defines.LOGARITHMICDEPTH) {
  38957. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38958. }
  38959. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38960. if (defines.SPECULARTERM) {
  38961. fallbacks.addFallback(0, "SPECULARTERM");
  38962. }
  38963. if (defines.DIFFUSEFRESNEL) {
  38964. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38965. }
  38966. if (defines.OPACITYFRESNEL) {
  38967. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38968. }
  38969. if (defines.REFLECTIONFRESNEL) {
  38970. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38971. }
  38972. if (defines.EMISSIVEFRESNEL) {
  38973. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38974. }
  38975. if (defines.FRESNEL) {
  38976. fallbacks.addFallback(4, "FRESNEL");
  38977. }
  38978. //Attributes
  38979. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38980. if (defines.NORMAL) {
  38981. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38982. }
  38983. if (defines.UV1) {
  38984. attribs.push(BABYLON.VertexBuffer.UVKind);
  38985. }
  38986. if (defines.UV2) {
  38987. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38988. }
  38989. if (defines.VERTEXCOLOR) {
  38990. attribs.push(BABYLON.VertexBuffer.ColorKind);
  38991. }
  38992. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  38993. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  38994. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  38995. var shaderName = "default";
  38996. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  38997. "vFogInfos", "vFogColor", "pointSize",
  38998. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  38999. "mBones",
  39000. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39001. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39002. "vReflectionPosition", "vReflectionSize",
  39003. "logarithmicDepthConstant", "vTangentSpaceParams"
  39004. ];
  39005. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39006. var uniformBuffers = ["Material", "Scene"];
  39007. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39008. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39009. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39010. uniformsNames: uniforms,
  39011. uniformBuffersNames: uniformBuffers,
  39012. samplers: samplers,
  39013. defines: defines,
  39014. maxSimultaneousLights: this._maxSimultaneousLights
  39015. });
  39016. if (this.customShaderNameResolve) {
  39017. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39018. }
  39019. var join = defines.toString();
  39020. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39021. attributes: attribs,
  39022. uniformsNames: uniforms,
  39023. uniformBuffersNames: uniformBuffers,
  39024. samplers: samplers,
  39025. defines: join,
  39026. fallbacks: fallbacks,
  39027. onCompiled: this.onCompiled,
  39028. onError: this.onError,
  39029. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39030. }, engine), defines);
  39031. this.buildUniformLayout();
  39032. }
  39033. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39034. return false;
  39035. }
  39036. defines._renderId = scene.getRenderId();
  39037. this._wasPreviouslyReady = true;
  39038. return true;
  39039. };
  39040. StandardMaterial.prototype.buildUniformLayout = function () {
  39041. // Order is important !
  39042. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39043. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39044. this._uniformBuffer.addUniform("opacityParts", 4);
  39045. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39046. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39047. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39048. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39049. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39050. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39051. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39052. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39053. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39054. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39055. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39056. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39057. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39058. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39059. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39060. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39061. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39062. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39063. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39064. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39065. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39066. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39067. this._uniformBuffer.addUniform("specularMatrix", 16);
  39068. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39069. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39070. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39071. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39072. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39073. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39074. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39075. this._uniformBuffer.addUniform("pointSize", 1);
  39076. this._uniformBuffer.create();
  39077. };
  39078. StandardMaterial.prototype.unbind = function () {
  39079. if (this._activeEffect) {
  39080. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39081. this._activeEffect.setTexture("reflection2DSampler", null);
  39082. }
  39083. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39084. this._activeEffect.setTexture("refraction2DSampler", null);
  39085. }
  39086. }
  39087. _super.prototype.unbind.call(this);
  39088. };
  39089. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39090. var scene = this.getScene();
  39091. var defines = subMesh._materialDefines;
  39092. if (!defines) {
  39093. return;
  39094. }
  39095. var effect = subMesh.effect;
  39096. if (!effect) {
  39097. return;
  39098. }
  39099. this._activeEffect = effect;
  39100. // Matrices
  39101. this.bindOnlyWorldMatrix(world);
  39102. // Normal Matrix
  39103. if (defines.OBJECTSPACE_NORMALMAP) {
  39104. world.toNormalMatrix(this._normalMatrix);
  39105. this.bindOnlyNormalMatrix(this._normalMatrix);
  39106. }
  39107. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39108. // Bones
  39109. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39110. if (mustRebind) {
  39111. this._uniformBuffer.bindToEffect(effect, "Material");
  39112. this.bindViewProjection(effect);
  39113. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39114. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39115. // Fresnel
  39116. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39117. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39118. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39119. }
  39120. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39121. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39122. }
  39123. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39124. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39125. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39126. }
  39127. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39128. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39129. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39130. }
  39131. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39132. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39133. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39134. }
  39135. }
  39136. // Textures
  39137. if (scene.texturesEnabled) {
  39138. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39139. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39140. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39141. }
  39142. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39143. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39144. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39145. }
  39146. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39147. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39148. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39149. }
  39150. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39151. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39152. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39153. if (this._reflectionTexture.boundingBoxSize) {
  39154. var cubeTexture = this._reflectionTexture;
  39155. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39156. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39157. }
  39158. }
  39159. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39160. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39161. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39162. }
  39163. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39164. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39165. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39166. }
  39167. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39168. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39169. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39170. }
  39171. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39172. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39173. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39174. if (scene._mirroredCameraPosition) {
  39175. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39176. }
  39177. else {
  39178. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39179. }
  39180. }
  39181. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39182. var depth = 1.0;
  39183. if (!this._refractionTexture.isCube) {
  39184. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39185. if (this._refractionTexture.depth) {
  39186. depth = this._refractionTexture.depth;
  39187. }
  39188. }
  39189. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39190. }
  39191. }
  39192. // Point size
  39193. if (this.pointsCloud) {
  39194. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39195. }
  39196. if (defines.SPECULARTERM) {
  39197. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39198. }
  39199. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39200. // Diffuse
  39201. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39202. }
  39203. // Textures
  39204. if (scene.texturesEnabled) {
  39205. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39206. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39207. }
  39208. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39209. effect.setTexture("ambientSampler", this._ambientTexture);
  39210. }
  39211. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39212. effect.setTexture("opacitySampler", this._opacityTexture);
  39213. }
  39214. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39215. if (this._reflectionTexture.isCube) {
  39216. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39217. }
  39218. else {
  39219. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39220. }
  39221. }
  39222. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39223. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39224. }
  39225. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39226. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39227. }
  39228. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39229. effect.setTexture("specularSampler", this._specularTexture);
  39230. }
  39231. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39232. effect.setTexture("bumpSampler", this._bumpTexture);
  39233. }
  39234. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39235. var depth = 1.0;
  39236. if (this._refractionTexture.isCube) {
  39237. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39238. }
  39239. else {
  39240. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39241. }
  39242. }
  39243. }
  39244. // Clip plane
  39245. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39246. // Colors
  39247. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39248. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39249. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39250. }
  39251. if (mustRebind || !this.isFrozen) {
  39252. // Lights
  39253. if (scene.lightsEnabled && !this._disableLighting) {
  39254. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39255. }
  39256. // View
  39257. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39258. this.bindView(effect);
  39259. }
  39260. // Fog
  39261. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39262. // Morph targets
  39263. if (defines.NUM_MORPH_INFLUENCERS) {
  39264. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39265. }
  39266. // Log. depth
  39267. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39268. // image processing
  39269. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39270. this._imageProcessingConfiguration.bind(this._activeEffect);
  39271. }
  39272. }
  39273. this._uniformBuffer.update();
  39274. this._afterBind(mesh, this._activeEffect);
  39275. };
  39276. StandardMaterial.prototype.getAnimatables = function () {
  39277. var results = [];
  39278. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39279. results.push(this._diffuseTexture);
  39280. }
  39281. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39282. results.push(this._ambientTexture);
  39283. }
  39284. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39285. results.push(this._opacityTexture);
  39286. }
  39287. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39288. results.push(this._reflectionTexture);
  39289. }
  39290. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39291. results.push(this._emissiveTexture);
  39292. }
  39293. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39294. results.push(this._specularTexture);
  39295. }
  39296. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39297. results.push(this._bumpTexture);
  39298. }
  39299. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39300. results.push(this._lightmapTexture);
  39301. }
  39302. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39303. results.push(this._refractionTexture);
  39304. }
  39305. return results;
  39306. };
  39307. StandardMaterial.prototype.getActiveTextures = function () {
  39308. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39309. if (this._diffuseTexture) {
  39310. activeTextures.push(this._diffuseTexture);
  39311. }
  39312. if (this._ambientTexture) {
  39313. activeTextures.push(this._ambientTexture);
  39314. }
  39315. if (this._opacityTexture) {
  39316. activeTextures.push(this._opacityTexture);
  39317. }
  39318. if (this._reflectionTexture) {
  39319. activeTextures.push(this._reflectionTexture);
  39320. }
  39321. if (this._emissiveTexture) {
  39322. activeTextures.push(this._emissiveTexture);
  39323. }
  39324. if (this._specularTexture) {
  39325. activeTextures.push(this._specularTexture);
  39326. }
  39327. if (this._bumpTexture) {
  39328. activeTextures.push(this._bumpTexture);
  39329. }
  39330. if (this._lightmapTexture) {
  39331. activeTextures.push(this._lightmapTexture);
  39332. }
  39333. if (this._refractionTexture) {
  39334. activeTextures.push(this._refractionTexture);
  39335. }
  39336. return activeTextures;
  39337. };
  39338. StandardMaterial.prototype.hasTexture = function (texture) {
  39339. if (_super.prototype.hasTexture.call(this, texture)) {
  39340. return true;
  39341. }
  39342. if (this._diffuseTexture === texture) {
  39343. return true;
  39344. }
  39345. if (this._ambientTexture === texture) {
  39346. return true;
  39347. }
  39348. if (this._opacityTexture === texture) {
  39349. return true;
  39350. }
  39351. if (this._reflectionTexture === texture) {
  39352. return true;
  39353. }
  39354. if (this._emissiveTexture === texture) {
  39355. return true;
  39356. }
  39357. if (this._specularTexture === texture) {
  39358. return true;
  39359. }
  39360. if (this._bumpTexture === texture) {
  39361. return true;
  39362. }
  39363. if (this._lightmapTexture === texture) {
  39364. return true;
  39365. }
  39366. if (this._refractionTexture === texture) {
  39367. return true;
  39368. }
  39369. return false;
  39370. };
  39371. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39372. if (forceDisposeTextures) {
  39373. if (this._diffuseTexture) {
  39374. this._diffuseTexture.dispose();
  39375. }
  39376. if (this._ambientTexture) {
  39377. this._ambientTexture.dispose();
  39378. }
  39379. if (this._opacityTexture) {
  39380. this._opacityTexture.dispose();
  39381. }
  39382. if (this._reflectionTexture) {
  39383. this._reflectionTexture.dispose();
  39384. }
  39385. if (this._emissiveTexture) {
  39386. this._emissiveTexture.dispose();
  39387. }
  39388. if (this._specularTexture) {
  39389. this._specularTexture.dispose();
  39390. }
  39391. if (this._bumpTexture) {
  39392. this._bumpTexture.dispose();
  39393. }
  39394. if (this._lightmapTexture) {
  39395. this._lightmapTexture.dispose();
  39396. }
  39397. if (this._refractionTexture) {
  39398. this._refractionTexture.dispose();
  39399. }
  39400. }
  39401. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39402. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39403. }
  39404. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39405. };
  39406. StandardMaterial.prototype.clone = function (name) {
  39407. var _this = this;
  39408. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39409. result.name = name;
  39410. result.id = name;
  39411. return result;
  39412. };
  39413. StandardMaterial.prototype.serialize = function () {
  39414. return BABYLON.SerializationHelper.Serialize(this);
  39415. };
  39416. // Statics
  39417. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39418. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39419. };
  39420. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39421. get: function () {
  39422. return StandardMaterial._DiffuseTextureEnabled;
  39423. },
  39424. set: function (value) {
  39425. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39426. return;
  39427. }
  39428. StandardMaterial._DiffuseTextureEnabled = value;
  39429. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39430. },
  39431. enumerable: true,
  39432. configurable: true
  39433. });
  39434. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39435. get: function () {
  39436. return StandardMaterial._AmbientTextureEnabled;
  39437. },
  39438. set: function (value) {
  39439. if (StandardMaterial._AmbientTextureEnabled === value) {
  39440. return;
  39441. }
  39442. StandardMaterial._AmbientTextureEnabled = value;
  39443. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39444. },
  39445. enumerable: true,
  39446. configurable: true
  39447. });
  39448. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39449. get: function () {
  39450. return StandardMaterial._OpacityTextureEnabled;
  39451. },
  39452. set: function (value) {
  39453. if (StandardMaterial._OpacityTextureEnabled === value) {
  39454. return;
  39455. }
  39456. StandardMaterial._OpacityTextureEnabled = value;
  39457. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39458. },
  39459. enumerable: true,
  39460. configurable: true
  39461. });
  39462. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39463. get: function () {
  39464. return StandardMaterial._ReflectionTextureEnabled;
  39465. },
  39466. set: function (value) {
  39467. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39468. return;
  39469. }
  39470. StandardMaterial._ReflectionTextureEnabled = value;
  39471. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39472. },
  39473. enumerable: true,
  39474. configurable: true
  39475. });
  39476. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39477. get: function () {
  39478. return StandardMaterial._EmissiveTextureEnabled;
  39479. },
  39480. set: function (value) {
  39481. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39482. return;
  39483. }
  39484. StandardMaterial._EmissiveTextureEnabled = value;
  39485. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39486. },
  39487. enumerable: true,
  39488. configurable: true
  39489. });
  39490. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39491. get: function () {
  39492. return StandardMaterial._SpecularTextureEnabled;
  39493. },
  39494. set: function (value) {
  39495. if (StandardMaterial._SpecularTextureEnabled === value) {
  39496. return;
  39497. }
  39498. StandardMaterial._SpecularTextureEnabled = value;
  39499. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39500. },
  39501. enumerable: true,
  39502. configurable: true
  39503. });
  39504. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39505. get: function () {
  39506. return StandardMaterial._BumpTextureEnabled;
  39507. },
  39508. set: function (value) {
  39509. if (StandardMaterial._BumpTextureEnabled === value) {
  39510. return;
  39511. }
  39512. StandardMaterial._BumpTextureEnabled = value;
  39513. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39514. },
  39515. enumerable: true,
  39516. configurable: true
  39517. });
  39518. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39519. get: function () {
  39520. return StandardMaterial._LightmapTextureEnabled;
  39521. },
  39522. set: function (value) {
  39523. if (StandardMaterial._LightmapTextureEnabled === value) {
  39524. return;
  39525. }
  39526. StandardMaterial._LightmapTextureEnabled = value;
  39527. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39528. },
  39529. enumerable: true,
  39530. configurable: true
  39531. });
  39532. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39533. get: function () {
  39534. return StandardMaterial._RefractionTextureEnabled;
  39535. },
  39536. set: function (value) {
  39537. if (StandardMaterial._RefractionTextureEnabled === value) {
  39538. return;
  39539. }
  39540. StandardMaterial._RefractionTextureEnabled = value;
  39541. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39542. },
  39543. enumerable: true,
  39544. configurable: true
  39545. });
  39546. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39547. get: function () {
  39548. return StandardMaterial._ColorGradingTextureEnabled;
  39549. },
  39550. set: function (value) {
  39551. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39552. return;
  39553. }
  39554. StandardMaterial._ColorGradingTextureEnabled = value;
  39555. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39556. },
  39557. enumerable: true,
  39558. configurable: true
  39559. });
  39560. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39561. get: function () {
  39562. return StandardMaterial._FresnelEnabled;
  39563. },
  39564. set: function (value) {
  39565. if (StandardMaterial._FresnelEnabled === value) {
  39566. return;
  39567. }
  39568. StandardMaterial._FresnelEnabled = value;
  39569. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39570. },
  39571. enumerable: true,
  39572. configurable: true
  39573. });
  39574. // Flags used to enable or disable a type of texture for all Standard Materials
  39575. StandardMaterial._DiffuseTextureEnabled = true;
  39576. StandardMaterial._AmbientTextureEnabled = true;
  39577. StandardMaterial._OpacityTextureEnabled = true;
  39578. StandardMaterial._ReflectionTextureEnabled = true;
  39579. StandardMaterial._EmissiveTextureEnabled = true;
  39580. StandardMaterial._SpecularTextureEnabled = true;
  39581. StandardMaterial._BumpTextureEnabled = true;
  39582. StandardMaterial._LightmapTextureEnabled = true;
  39583. StandardMaterial._RefractionTextureEnabled = true;
  39584. StandardMaterial._ColorGradingTextureEnabled = true;
  39585. StandardMaterial._FresnelEnabled = true;
  39586. __decorate([
  39587. BABYLON.serializeAsTexture("diffuseTexture")
  39588. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39589. __decorate([
  39590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39591. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39592. __decorate([
  39593. BABYLON.serializeAsTexture("ambientTexture")
  39594. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39595. __decorate([
  39596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39597. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39598. __decorate([
  39599. BABYLON.serializeAsTexture("opacityTexture")
  39600. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39601. __decorate([
  39602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39603. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39604. __decorate([
  39605. BABYLON.serializeAsTexture("reflectionTexture")
  39606. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39607. __decorate([
  39608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39609. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39610. __decorate([
  39611. BABYLON.serializeAsTexture("emissiveTexture")
  39612. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39613. __decorate([
  39614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39615. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39616. __decorate([
  39617. BABYLON.serializeAsTexture("specularTexture")
  39618. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39619. __decorate([
  39620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39621. ], StandardMaterial.prototype, "specularTexture", void 0);
  39622. __decorate([
  39623. BABYLON.serializeAsTexture("bumpTexture")
  39624. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39625. __decorate([
  39626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39627. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39628. __decorate([
  39629. BABYLON.serializeAsTexture("lightmapTexture")
  39630. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39631. __decorate([
  39632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39633. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39634. __decorate([
  39635. BABYLON.serializeAsTexture("refractionTexture")
  39636. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39637. __decorate([
  39638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39639. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39640. __decorate([
  39641. BABYLON.serializeAsColor3("ambient")
  39642. ], StandardMaterial.prototype, "ambientColor", void 0);
  39643. __decorate([
  39644. BABYLON.serializeAsColor3("diffuse")
  39645. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39646. __decorate([
  39647. BABYLON.serializeAsColor3("specular")
  39648. ], StandardMaterial.prototype, "specularColor", void 0);
  39649. __decorate([
  39650. BABYLON.serializeAsColor3("emissive")
  39651. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39652. __decorate([
  39653. BABYLON.serialize()
  39654. ], StandardMaterial.prototype, "specularPower", void 0);
  39655. __decorate([
  39656. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39657. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39658. __decorate([
  39659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39660. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39661. __decorate([
  39662. BABYLON.serialize("useEmissiveAsIllumination")
  39663. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39664. __decorate([
  39665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39666. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39667. __decorate([
  39668. BABYLON.serialize("linkEmissiveWithDiffuse")
  39669. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39670. __decorate([
  39671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39672. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39673. __decorate([
  39674. BABYLON.serialize("useSpecularOverAlpha")
  39675. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39676. __decorate([
  39677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39678. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39679. __decorate([
  39680. BABYLON.serialize("useReflectionOverAlpha")
  39681. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39682. __decorate([
  39683. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39684. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39685. __decorate([
  39686. BABYLON.serialize("disableLighting")
  39687. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39688. __decorate([
  39689. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39690. ], StandardMaterial.prototype, "disableLighting", void 0);
  39691. __decorate([
  39692. BABYLON.serialize("useObjectSpaceNormalMap")
  39693. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  39694. __decorate([
  39695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39696. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  39697. __decorate([
  39698. BABYLON.serialize("useParallax")
  39699. ], StandardMaterial.prototype, "_useParallax", void 0);
  39700. __decorate([
  39701. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39702. ], StandardMaterial.prototype, "useParallax", void 0);
  39703. __decorate([
  39704. BABYLON.serialize("useParallaxOcclusion")
  39705. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39706. __decorate([
  39707. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39708. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39709. __decorate([
  39710. BABYLON.serialize()
  39711. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39712. __decorate([
  39713. BABYLON.serialize("roughness")
  39714. ], StandardMaterial.prototype, "_roughness", void 0);
  39715. __decorate([
  39716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39717. ], StandardMaterial.prototype, "roughness", void 0);
  39718. __decorate([
  39719. BABYLON.serialize()
  39720. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39721. __decorate([
  39722. BABYLON.serialize()
  39723. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39724. __decorate([
  39725. BABYLON.serialize("useLightmapAsShadowmap")
  39726. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39727. __decorate([
  39728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39729. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39730. __decorate([
  39731. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39732. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39733. __decorate([
  39734. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39735. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39736. __decorate([
  39737. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39738. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39739. __decorate([
  39740. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39741. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39742. __decorate([
  39743. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39744. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39745. __decorate([
  39746. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39747. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39748. __decorate([
  39749. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39750. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39751. __decorate([
  39752. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39753. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39754. __decorate([
  39755. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39756. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39757. __decorate([
  39758. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39759. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39760. __decorate([
  39761. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39762. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39763. __decorate([
  39764. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39765. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39766. __decorate([
  39767. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39768. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39769. __decorate([
  39770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39771. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39772. __decorate([
  39773. BABYLON.serialize("maxSimultaneousLights")
  39774. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39775. __decorate([
  39776. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39777. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39778. __decorate([
  39779. BABYLON.serialize("invertNormalMapX")
  39780. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39781. __decorate([
  39782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39783. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39784. __decorate([
  39785. BABYLON.serialize("invertNormalMapY")
  39786. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39787. __decorate([
  39788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39789. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39790. __decorate([
  39791. BABYLON.serialize("twoSidedLighting")
  39792. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39793. __decorate([
  39794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39795. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39796. __decorate([
  39797. BABYLON.serialize()
  39798. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39799. return StandardMaterial;
  39800. }(BABYLON.PushMaterial));
  39801. BABYLON.StandardMaterial = StandardMaterial;
  39802. })(BABYLON || (BABYLON = {}));
  39803. //# sourceMappingURL=babylon.standardMaterial.js.map
  39804. var BABYLON;
  39805. (function (BABYLON) {
  39806. /**
  39807. * Manages the defines for the PBR Material.
  39808. */
  39809. var PBRMaterialDefines = /** @class */ (function (_super) {
  39810. __extends(PBRMaterialDefines, _super);
  39811. /**
  39812. * Initializes the PBR Material defines.
  39813. */
  39814. function PBRMaterialDefines() {
  39815. var _this = _super.call(this) || this;
  39816. _this.PBR = true;
  39817. _this.MAINUV1 = false;
  39818. _this.MAINUV2 = false;
  39819. _this.UV1 = false;
  39820. _this.UV2 = false;
  39821. _this.ALBEDO = false;
  39822. _this.ALBEDODIRECTUV = 0;
  39823. _this.VERTEXCOLOR = false;
  39824. _this.AMBIENT = false;
  39825. _this.AMBIENTDIRECTUV = 0;
  39826. _this.AMBIENTINGRAYSCALE = false;
  39827. _this.OPACITY = false;
  39828. _this.VERTEXALPHA = false;
  39829. _this.OPACITYDIRECTUV = 0;
  39830. _this.OPACITYRGB = false;
  39831. _this.ALPHATEST = false;
  39832. _this.DEPTHPREPASS = false;
  39833. _this.ALPHABLEND = false;
  39834. _this.ALPHAFROMALBEDO = false;
  39835. _this.ALPHATESTVALUE = 0.5;
  39836. _this.SPECULAROVERALPHA = false;
  39837. _this.RADIANCEOVERALPHA = false;
  39838. _this.ALPHAFRESNEL = false;
  39839. _this.LINEARALPHAFRESNEL = false;
  39840. _this.PREMULTIPLYALPHA = false;
  39841. _this.EMISSIVE = false;
  39842. _this.EMISSIVEDIRECTUV = 0;
  39843. _this.REFLECTIVITY = false;
  39844. _this.REFLECTIVITYDIRECTUV = 0;
  39845. _this.SPECULARTERM = false;
  39846. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39847. _this.MICROSURFACEAUTOMATIC = false;
  39848. _this.LODBASEDMICROSFURACE = false;
  39849. _this.MICROSURFACEMAP = false;
  39850. _this.MICROSURFACEMAPDIRECTUV = 0;
  39851. _this.METALLICWORKFLOW = false;
  39852. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39853. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39854. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39855. _this.AOSTOREINMETALMAPRED = false;
  39856. _this.ENVIRONMENTBRDF = false;
  39857. _this.NORMAL = false;
  39858. _this.TANGENT = false;
  39859. _this.BUMP = false;
  39860. _this.BUMPDIRECTUV = 0;
  39861. _this.OBJECTSPACE_NORMALMAP = false;
  39862. _this.PARALLAX = false;
  39863. _this.PARALLAXOCCLUSION = false;
  39864. _this.NORMALXYSCALE = true;
  39865. _this.LIGHTMAP = false;
  39866. _this.LIGHTMAPDIRECTUV = 0;
  39867. _this.USELIGHTMAPASSHADOWMAP = false;
  39868. _this.REFLECTION = false;
  39869. _this.REFLECTIONMAP_3D = false;
  39870. _this.REFLECTIONMAP_SPHERICAL = false;
  39871. _this.REFLECTIONMAP_PLANAR = false;
  39872. _this.REFLECTIONMAP_CUBIC = false;
  39873. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39874. _this.REFLECTIONMAP_PROJECTION = false;
  39875. _this.REFLECTIONMAP_SKYBOX = false;
  39876. _this.REFLECTIONMAP_EXPLICIT = false;
  39877. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39878. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39879. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39880. _this.INVERTCUBICMAP = false;
  39881. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39882. _this.USESPHERICALINVERTEX = false;
  39883. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39884. _this.LODINREFLECTIONALPHA = false;
  39885. _this.GAMMAREFLECTION = false;
  39886. _this.RADIANCEOCCLUSION = false;
  39887. _this.HORIZONOCCLUSION = false;
  39888. _this.REFRACTION = false;
  39889. _this.REFRACTIONMAP_3D = false;
  39890. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39891. _this.LODINREFRACTIONALPHA = false;
  39892. _this.GAMMAREFRACTION = false;
  39893. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39894. _this.INSTANCES = false;
  39895. _this.NUM_BONE_INFLUENCERS = 0;
  39896. _this.BonesPerMesh = 0;
  39897. _this.NONUNIFORMSCALING = false;
  39898. _this.MORPHTARGETS = false;
  39899. _this.MORPHTARGETS_NORMAL = false;
  39900. _this.MORPHTARGETS_TANGENT = false;
  39901. _this.NUM_MORPH_INFLUENCERS = 0;
  39902. _this.IMAGEPROCESSING = false;
  39903. _this.VIGNETTE = false;
  39904. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39905. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39906. _this.TONEMAPPING = false;
  39907. _this.CONTRAST = false;
  39908. _this.COLORCURVES = false;
  39909. _this.COLORGRADING = false;
  39910. _this.COLORGRADING3D = false;
  39911. _this.SAMPLER3DGREENDEPTH = false;
  39912. _this.SAMPLER3DBGRMAP = false;
  39913. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39914. _this.EXPOSURE = false;
  39915. _this.USEPHYSICALLIGHTFALLOFF = false;
  39916. _this.TWOSIDEDLIGHTING = false;
  39917. _this.SHADOWFLOAT = false;
  39918. _this.CLIPPLANE = false;
  39919. _this.POINTSIZE = false;
  39920. _this.FOG = false;
  39921. _this.LOGARITHMICDEPTH = false;
  39922. _this.FORCENORMALFORWARD = false;
  39923. _this.rebuild();
  39924. return _this;
  39925. }
  39926. /**
  39927. * Resets the PBR Material defines.
  39928. */
  39929. PBRMaterialDefines.prototype.reset = function () {
  39930. _super.prototype.reset.call(this);
  39931. this.ALPHATESTVALUE = 0.5;
  39932. this.PBR = true;
  39933. };
  39934. return PBRMaterialDefines;
  39935. }(BABYLON.MaterialDefines));
  39936. /**
  39937. * The Physically based material base class of BJS.
  39938. *
  39939. * This offers the main features of a standard PBR material.
  39940. * For more information, please refer to the documentation :
  39941. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39942. */
  39943. var PBRBaseMaterial = /** @class */ (function (_super) {
  39944. __extends(PBRBaseMaterial, _super);
  39945. /**
  39946. * Instantiates a new PBRMaterial instance.
  39947. *
  39948. * @param name The material name
  39949. * @param scene The scene the material will be use in.
  39950. */
  39951. function PBRBaseMaterial(name, scene) {
  39952. var _this = _super.call(this, name, scene) || this;
  39953. /**
  39954. * Intensity of the direct lights e.g. the four lights available in your scene.
  39955. * This impacts both the direct diffuse and specular highlights.
  39956. */
  39957. _this._directIntensity = 1.0;
  39958. /**
  39959. * Intensity of the emissive part of the material.
  39960. * This helps controlling the emissive effect without modifying the emissive color.
  39961. */
  39962. _this._emissiveIntensity = 1.0;
  39963. /**
  39964. * Intensity of the environment e.g. how much the environment will light the object
  39965. * either through harmonics for rough material or through the refelction for shiny ones.
  39966. */
  39967. _this._environmentIntensity = 1.0;
  39968. /**
  39969. * This is a special control allowing the reduction of the specular highlights coming from the
  39970. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39971. */
  39972. _this._specularIntensity = 1.0;
  39973. /**
  39974. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39975. */
  39976. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39977. /**
  39978. * Debug Control allowing disabling the bump map on this material.
  39979. */
  39980. _this._disableBumpMap = false;
  39981. /**
  39982. * AKA Occlusion Texture Intensity in other nomenclature.
  39983. */
  39984. _this._ambientTextureStrength = 1.0;
  39985. /**
  39986. * The color of a material in ambient lighting.
  39987. */
  39988. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39989. /**
  39990. * AKA Diffuse Color in other nomenclature.
  39991. */
  39992. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  39993. /**
  39994. * AKA Specular Color in other nomenclature.
  39995. */
  39996. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  39997. /**
  39998. * The color applied when light is reflected from a material.
  39999. */
  40000. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40001. /**
  40002. * The color applied when light is emitted from a material.
  40003. */
  40004. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40005. /**
  40006. * AKA Glossiness in other nomenclature.
  40007. */
  40008. _this._microSurface = 0.9;
  40009. /**
  40010. * source material index of refraction (IOR)' / 'destination material IOR.
  40011. */
  40012. _this._indexOfRefraction = 0.66;
  40013. /**
  40014. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40015. */
  40016. _this._invertRefractionY = false;
  40017. /**
  40018. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40019. * Materials half opaque for instance using refraction could benefit from this control.
  40020. */
  40021. _this._linkRefractionWithTransparency = false;
  40022. /**
  40023. * Specifies that the material will use the light map as a show map.
  40024. */
  40025. _this._useLightmapAsShadowmap = false;
  40026. /**
  40027. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40028. * makes the reflect vector face the model (under horizon).
  40029. */
  40030. _this._useHorizonOcclusion = true;
  40031. /**
  40032. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40033. * too much the area relying on ambient texture to define their ambient occlusion.
  40034. */
  40035. _this._useRadianceOcclusion = true;
  40036. /**
  40037. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40038. */
  40039. _this._useAlphaFromAlbedoTexture = false;
  40040. /**
  40041. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40042. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40043. */
  40044. _this._useSpecularOverAlpha = true;
  40045. /**
  40046. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40047. */
  40048. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40049. /**
  40050. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40051. */
  40052. _this._useRoughnessFromMetallicTextureAlpha = true;
  40053. /**
  40054. * Specifies if the metallic texture contains the roughness information in its green channel.
  40055. */
  40056. _this._useRoughnessFromMetallicTextureGreen = false;
  40057. /**
  40058. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40059. */
  40060. _this._useMetallnessFromMetallicTextureBlue = false;
  40061. /**
  40062. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40063. */
  40064. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40065. /**
  40066. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40067. */
  40068. _this._useAmbientInGrayScale = false;
  40069. /**
  40070. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40071. * The material will try to infer what glossiness each pixel should be.
  40072. */
  40073. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40074. /**
  40075. * BJS is using an harcoded light falloff based on a manually sets up range.
  40076. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40077. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40078. */
  40079. _this._usePhysicalLightFalloff = true;
  40080. /**
  40081. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40082. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40083. */
  40084. _this._useRadianceOverAlpha = true;
  40085. /**
  40086. * Allows using an object space normal map (instead of tangent space).
  40087. */
  40088. _this._useObjectSpaceNormalMap = false;
  40089. /**
  40090. * Allows using the bump map in parallax mode.
  40091. */
  40092. _this._useParallax = false;
  40093. /**
  40094. * Allows using the bump map in parallax occlusion mode.
  40095. */
  40096. _this._useParallaxOcclusion = false;
  40097. /**
  40098. * Controls the scale bias of the parallax mode.
  40099. */
  40100. _this._parallaxScaleBias = 0.05;
  40101. /**
  40102. * If sets to true, disables all the lights affecting the material.
  40103. */
  40104. _this._disableLighting = false;
  40105. /**
  40106. * Number of Simultaneous lights allowed on the material.
  40107. */
  40108. _this._maxSimultaneousLights = 4;
  40109. /**
  40110. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40111. */
  40112. _this._invertNormalMapX = false;
  40113. /**
  40114. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40115. */
  40116. _this._invertNormalMapY = false;
  40117. /**
  40118. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40119. */
  40120. _this._twoSidedLighting = false;
  40121. /**
  40122. * Defines the alpha limits in alpha test mode.
  40123. */
  40124. _this._alphaCutOff = 0.4;
  40125. /**
  40126. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40127. */
  40128. _this._forceAlphaTest = false;
  40129. /**
  40130. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40131. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40132. */
  40133. _this._useAlphaFresnel = false;
  40134. /**
  40135. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40136. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40137. */
  40138. _this._useLinearAlphaFresnel = false;
  40139. /**
  40140. * The transparency mode of the material.
  40141. */
  40142. _this._transparencyMode = null;
  40143. /**
  40144. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40145. * from cos thetav and roughness:
  40146. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40147. */
  40148. _this._environmentBRDFTexture = null;
  40149. /**
  40150. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40151. */
  40152. _this._forceIrradianceInFragment = false;
  40153. /**
  40154. * Force normal to face away from face.
  40155. */
  40156. _this._forceNormalForward = false;
  40157. /**
  40158. * Force metallic workflow.
  40159. */
  40160. _this._forceMetallicWorkflow = false;
  40161. /**
  40162. * Stores the available render targets.
  40163. */
  40164. _this._renderTargets = new BABYLON.SmartArray(16);
  40165. /**
  40166. * Sets the global ambient color for the material used in lighting calculations.
  40167. */
  40168. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40169. // Setup the default processing configuration to the scene.
  40170. _this._attachImageProcessingConfiguration(null);
  40171. _this.getRenderTargetTextures = function () {
  40172. _this._renderTargets.reset();
  40173. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40174. _this._renderTargets.push(_this._reflectionTexture);
  40175. }
  40176. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40177. _this._renderTargets.push(_this._refractionTexture);
  40178. }
  40179. return _this._renderTargets;
  40180. };
  40181. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40182. return _this;
  40183. }
  40184. /**
  40185. * Attaches a new image processing configuration to the PBR Material.
  40186. * @param configuration
  40187. */
  40188. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40189. var _this = this;
  40190. if (configuration === this._imageProcessingConfiguration) {
  40191. return;
  40192. }
  40193. // Detaches observer.
  40194. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40195. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40196. }
  40197. // Pick the scene configuration if needed.
  40198. if (!configuration) {
  40199. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40200. }
  40201. else {
  40202. this._imageProcessingConfiguration = configuration;
  40203. }
  40204. // Attaches observer.
  40205. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40206. _this._markAllSubMeshesAsImageProcessingDirty();
  40207. });
  40208. };
  40209. /**
  40210. * Gets the name of the material class.
  40211. */
  40212. PBRBaseMaterial.prototype.getClassName = function () {
  40213. return "PBRBaseMaterial";
  40214. };
  40215. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40216. /**
  40217. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40218. */
  40219. get: function () {
  40220. return this._useLogarithmicDepth;
  40221. },
  40222. /**
  40223. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40224. */
  40225. set: function (value) {
  40226. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40227. },
  40228. enumerable: true,
  40229. configurable: true
  40230. });
  40231. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40232. /**
  40233. * Gets the current transparency mode.
  40234. */
  40235. get: function () {
  40236. return this._transparencyMode;
  40237. },
  40238. /**
  40239. * Sets the transparency mode of the material.
  40240. */
  40241. set: function (value) {
  40242. if (this._transparencyMode === value) {
  40243. return;
  40244. }
  40245. this._transparencyMode = value;
  40246. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40247. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40248. },
  40249. enumerable: true,
  40250. configurable: true
  40251. });
  40252. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40253. /**
  40254. * Returns true if alpha blending should be disabled.
  40255. */
  40256. get: function () {
  40257. return (this._linkRefractionWithTransparency ||
  40258. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40259. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40260. },
  40261. enumerable: true,
  40262. configurable: true
  40263. });
  40264. /**
  40265. * Specifies whether or not this material should be rendered in alpha blend mode.
  40266. */
  40267. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40268. if (this._disableAlphaBlending) {
  40269. return false;
  40270. }
  40271. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40272. };
  40273. /**
  40274. * Specifies if the mesh will require alpha blending.
  40275. * @param mesh - BJS mesh.
  40276. */
  40277. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40278. if (this._disableAlphaBlending) {
  40279. return false;
  40280. }
  40281. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40282. };
  40283. /**
  40284. * Specifies whether or not this material should be rendered in alpha test mode.
  40285. */
  40286. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40287. if (this._forceAlphaTest) {
  40288. return true;
  40289. }
  40290. if (this._linkRefractionWithTransparency) {
  40291. return false;
  40292. }
  40293. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40294. };
  40295. /**
  40296. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40297. */
  40298. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40299. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40300. };
  40301. /**
  40302. * Gets the texture used for the alpha test.
  40303. */
  40304. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40305. return this._albedoTexture;
  40306. };
  40307. /**
  40308. * Specifies that the submesh is ready to be used.
  40309. * @param mesh - BJS mesh.
  40310. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40311. * @param useInstances - Specifies that instances should be used.
  40312. * @returns - boolean indicating that the submesh is ready or not.
  40313. */
  40314. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40315. if (subMesh.effect && this.isFrozen) {
  40316. if (this._wasPreviouslyReady) {
  40317. return true;
  40318. }
  40319. }
  40320. if (!subMesh._materialDefines) {
  40321. subMesh._materialDefines = new PBRMaterialDefines();
  40322. }
  40323. var defines = subMesh._materialDefines;
  40324. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40325. if (defines._renderId === this.getScene().getRenderId()) {
  40326. return true;
  40327. }
  40328. }
  40329. var scene = this.getScene();
  40330. var engine = scene.getEngine();
  40331. if (defines._areTexturesDirty) {
  40332. if (scene.texturesEnabled) {
  40333. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40334. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40335. return false;
  40336. }
  40337. }
  40338. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40339. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40340. return false;
  40341. }
  40342. }
  40343. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40344. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40345. return false;
  40346. }
  40347. }
  40348. var reflectionTexture = this._getReflectionTexture();
  40349. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40350. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40351. return false;
  40352. }
  40353. }
  40354. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40355. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40356. return false;
  40357. }
  40358. }
  40359. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40360. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40361. return false;
  40362. }
  40363. }
  40364. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40365. if (this._metallicTexture) {
  40366. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40367. return false;
  40368. }
  40369. }
  40370. else if (this._reflectivityTexture) {
  40371. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40372. return false;
  40373. }
  40374. }
  40375. if (this._microSurfaceTexture) {
  40376. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40377. return false;
  40378. }
  40379. }
  40380. }
  40381. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40382. // Bump texture cannot be not blocking.
  40383. if (!this._bumpTexture.isReady()) {
  40384. return false;
  40385. }
  40386. }
  40387. var refractionTexture = this._getRefractionTexture();
  40388. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40389. if (!refractionTexture.isReadyOrNotBlocking()) {
  40390. return false;
  40391. }
  40392. }
  40393. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40394. // This is blocking.
  40395. if (!this._environmentBRDFTexture.isReady()) {
  40396. return false;
  40397. }
  40398. }
  40399. }
  40400. }
  40401. if (defines._areImageProcessingDirty) {
  40402. if (!this._imageProcessingConfiguration.isReady()) {
  40403. return false;
  40404. }
  40405. }
  40406. if (!engine.getCaps().standardDerivatives) {
  40407. var bufferMesh = null;
  40408. if (mesh.getClassName() === "InstancedMesh") {
  40409. bufferMesh = mesh.sourceMesh;
  40410. }
  40411. else if (mesh.getClassName() === "Mesh") {
  40412. bufferMesh = mesh;
  40413. }
  40414. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40415. bufferMesh.createNormals(true);
  40416. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40417. }
  40418. }
  40419. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40420. if (effect) {
  40421. scene.resetCachedMaterial();
  40422. subMesh.setEffect(effect, defines);
  40423. this.buildUniformLayout();
  40424. }
  40425. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40426. return false;
  40427. }
  40428. defines._renderId = scene.getRenderId();
  40429. this._wasPreviouslyReady = true;
  40430. return true;
  40431. };
  40432. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40433. if (onCompiled === void 0) { onCompiled = null; }
  40434. if (onError === void 0) { onError = null; }
  40435. if (useInstances === void 0) { useInstances = null; }
  40436. if (useClipPlane === void 0) { useClipPlane = null; }
  40437. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40438. if (!defines.isDirty) {
  40439. return null;
  40440. }
  40441. defines.markAsProcessed();
  40442. var scene = this.getScene();
  40443. var engine = scene.getEngine();
  40444. // Fallbacks
  40445. var fallbacks = new BABYLON.EffectFallbacks();
  40446. var fallbackRank = 0;
  40447. if (defines.USESPHERICALINVERTEX) {
  40448. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40449. }
  40450. if (defines.FOG) {
  40451. fallbacks.addFallback(fallbackRank, "FOG");
  40452. }
  40453. if (defines.POINTSIZE) {
  40454. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40455. }
  40456. if (defines.LOGARITHMICDEPTH) {
  40457. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40458. }
  40459. if (defines.PARALLAX) {
  40460. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40461. }
  40462. if (defines.PARALLAXOCCLUSION) {
  40463. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40464. }
  40465. if (defines.ENVIRONMENTBRDF) {
  40466. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40467. }
  40468. if (defines.TANGENT) {
  40469. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40470. }
  40471. if (defines.BUMP) {
  40472. fallbacks.addFallback(fallbackRank++, "BUMP");
  40473. }
  40474. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40475. if (defines.SPECULARTERM) {
  40476. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40477. }
  40478. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40479. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40480. }
  40481. if (defines.LIGHTMAP) {
  40482. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40483. }
  40484. if (defines.NORMAL) {
  40485. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40486. }
  40487. if (defines.AMBIENT) {
  40488. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40489. }
  40490. if (defines.EMISSIVE) {
  40491. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40492. }
  40493. if (defines.VERTEXCOLOR) {
  40494. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40495. }
  40496. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40497. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40498. }
  40499. if (defines.MORPHTARGETS) {
  40500. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40501. }
  40502. //Attributes
  40503. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40504. if (defines.NORMAL) {
  40505. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40506. }
  40507. if (defines.TANGENT) {
  40508. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40509. }
  40510. if (defines.UV1) {
  40511. attribs.push(BABYLON.VertexBuffer.UVKind);
  40512. }
  40513. if (defines.UV2) {
  40514. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40515. }
  40516. if (defines.VERTEXCOLOR) {
  40517. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40518. }
  40519. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40520. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40521. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40522. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40523. "vFogInfos", "vFogColor", "pointSize",
  40524. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40525. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40526. "mBones",
  40527. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40528. "vLightingIntensity",
  40529. "logarithmicDepthConstant",
  40530. "vSphericalX", "vSphericalY", "vSphericalZ",
  40531. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40532. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40533. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40534. "vTangentSpaceParams"
  40535. ];
  40536. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40537. "bumpSampler", "lightmapSampler", "opacitySampler",
  40538. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40539. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40540. "microSurfaceSampler", "environmentBrdfSampler"];
  40541. var uniformBuffers = ["Material", "Scene"];
  40542. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40543. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40544. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40545. uniformsNames: uniforms,
  40546. uniformBuffersNames: uniformBuffers,
  40547. samplers: samplers,
  40548. defines: defines,
  40549. maxSimultaneousLights: this._maxSimultaneousLights
  40550. });
  40551. var join = defines.toString();
  40552. return engine.createEffect("pbr", {
  40553. attributes: attribs,
  40554. uniformsNames: uniforms,
  40555. uniformBuffersNames: uniformBuffers,
  40556. samplers: samplers,
  40557. defines: join,
  40558. fallbacks: fallbacks,
  40559. onCompiled: onCompiled,
  40560. onError: onError,
  40561. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40562. }, engine);
  40563. };
  40564. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40565. if (useInstances === void 0) { useInstances = null; }
  40566. if (useClipPlane === void 0) { useClipPlane = null; }
  40567. var scene = this.getScene();
  40568. var engine = scene.getEngine();
  40569. // Lights
  40570. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40571. defines._needNormals = true;
  40572. // Textures
  40573. if (defines._areTexturesDirty) {
  40574. defines._needUVs = false;
  40575. if (scene.texturesEnabled) {
  40576. if (scene.getEngine().getCaps().textureLOD) {
  40577. defines.LODBASEDMICROSFURACE = true;
  40578. }
  40579. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40580. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40581. }
  40582. else {
  40583. defines.ALBEDO = false;
  40584. }
  40585. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40586. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40587. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40588. }
  40589. else {
  40590. defines.AMBIENT = false;
  40591. }
  40592. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40593. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40594. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40595. }
  40596. else {
  40597. defines.OPACITY = false;
  40598. }
  40599. var reflectionTexture = this._getReflectionTexture();
  40600. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40601. defines.REFLECTION = true;
  40602. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40603. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40604. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40605. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40606. defines.INVERTCUBICMAP = true;
  40607. }
  40608. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40609. switch (reflectionTexture.coordinatesMode) {
  40610. case BABYLON.Texture.CUBIC_MODE:
  40611. case BABYLON.Texture.INVCUBIC_MODE:
  40612. defines.REFLECTIONMAP_CUBIC = true;
  40613. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40614. break;
  40615. case BABYLON.Texture.EXPLICIT_MODE:
  40616. defines.REFLECTIONMAP_EXPLICIT = true;
  40617. break;
  40618. case BABYLON.Texture.PLANAR_MODE:
  40619. defines.REFLECTIONMAP_PLANAR = true;
  40620. break;
  40621. case BABYLON.Texture.PROJECTION_MODE:
  40622. defines.REFLECTIONMAP_PROJECTION = true;
  40623. break;
  40624. case BABYLON.Texture.SKYBOX_MODE:
  40625. defines.REFLECTIONMAP_SKYBOX = true;
  40626. break;
  40627. case BABYLON.Texture.SPHERICAL_MODE:
  40628. defines.REFLECTIONMAP_SPHERICAL = true;
  40629. break;
  40630. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40631. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40632. break;
  40633. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40634. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40635. break;
  40636. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40637. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40638. break;
  40639. }
  40640. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40641. if (reflectionTexture.sphericalPolynomial) {
  40642. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40643. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40644. defines.USESPHERICALINVERTEX = false;
  40645. }
  40646. else {
  40647. defines.USESPHERICALINVERTEX = true;
  40648. }
  40649. }
  40650. }
  40651. }
  40652. else {
  40653. defines.REFLECTION = false;
  40654. defines.REFLECTIONMAP_3D = false;
  40655. defines.REFLECTIONMAP_SPHERICAL = false;
  40656. defines.REFLECTIONMAP_PLANAR = false;
  40657. defines.REFLECTIONMAP_CUBIC = false;
  40658. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40659. defines.REFLECTIONMAP_PROJECTION = false;
  40660. defines.REFLECTIONMAP_SKYBOX = false;
  40661. defines.REFLECTIONMAP_EXPLICIT = false;
  40662. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40663. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40664. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40665. defines.INVERTCUBICMAP = false;
  40666. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40667. defines.USESPHERICALINVERTEX = false;
  40668. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40669. defines.LODINREFLECTIONALPHA = false;
  40670. defines.GAMMAREFLECTION = false;
  40671. }
  40672. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40673. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40674. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40675. }
  40676. else {
  40677. defines.LIGHTMAP = false;
  40678. }
  40679. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40680. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40681. }
  40682. else {
  40683. defines.EMISSIVE = false;
  40684. }
  40685. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40686. if (this._metallicTexture) {
  40687. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40688. defines.METALLICWORKFLOW = true;
  40689. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40690. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40691. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40692. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40693. }
  40694. else if (this._reflectivityTexture) {
  40695. defines.METALLICWORKFLOW = false;
  40696. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40697. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40698. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40699. }
  40700. else {
  40701. defines.METALLICWORKFLOW = false;
  40702. defines.REFLECTIVITY = false;
  40703. }
  40704. if (this._microSurfaceTexture) {
  40705. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40706. }
  40707. else {
  40708. defines.MICROSURFACEMAP = false;
  40709. }
  40710. }
  40711. else {
  40712. defines.REFLECTIVITY = false;
  40713. defines.MICROSURFACEMAP = false;
  40714. }
  40715. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40716. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40717. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40718. defines.PARALLAX = true;
  40719. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40720. }
  40721. else {
  40722. defines.PARALLAX = false;
  40723. }
  40724. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40725. }
  40726. else {
  40727. defines.BUMP = false;
  40728. }
  40729. var refractionTexture = this._getRefractionTexture();
  40730. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40731. defines.REFRACTION = true;
  40732. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40733. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40734. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40735. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40736. if (this._linkRefractionWithTransparency) {
  40737. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40738. }
  40739. }
  40740. else {
  40741. defines.REFRACTION = false;
  40742. }
  40743. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40744. defines.ENVIRONMENTBRDF = true;
  40745. }
  40746. else {
  40747. defines.ENVIRONMENTBRDF = false;
  40748. }
  40749. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40750. defines.ALPHAFROMALBEDO = true;
  40751. }
  40752. else {
  40753. defines.ALPHAFROMALBEDO = false;
  40754. }
  40755. }
  40756. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40757. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40758. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40759. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40760. defines.METALLICWORKFLOW = true;
  40761. }
  40762. else {
  40763. defines.METALLICWORKFLOW = false;
  40764. }
  40765. if (!this.backFaceCulling && this._twoSidedLighting) {
  40766. defines.TWOSIDEDLIGHTING = true;
  40767. }
  40768. else {
  40769. defines.TWOSIDEDLIGHTING = false;
  40770. }
  40771. defines.ALPHATESTVALUE = this._alphaCutOff;
  40772. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40773. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40774. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40775. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40776. }
  40777. if (defines._areImageProcessingDirty) {
  40778. this._imageProcessingConfiguration.prepareDefines(defines);
  40779. }
  40780. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40781. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40782. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40783. // Misc.
  40784. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40785. // Values that need to be evaluated on every frame
  40786. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40787. // Attribs
  40788. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40789. };
  40790. /**
  40791. * Force shader compilation
  40792. */
  40793. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40794. var _this = this;
  40795. var localOptions = __assign({ clipPlane: false }, options);
  40796. var defines = new PBRMaterialDefines();
  40797. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40798. if (effect.isReady()) {
  40799. if (onCompiled) {
  40800. onCompiled(this);
  40801. }
  40802. }
  40803. else {
  40804. effect.onCompileObservable.add(function () {
  40805. if (onCompiled) {
  40806. onCompiled(_this);
  40807. }
  40808. });
  40809. }
  40810. };
  40811. /**
  40812. * Initializes the uniform buffer layout for the shader.
  40813. */
  40814. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40815. // Order is important !
  40816. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40817. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40818. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40819. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40820. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40821. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40822. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40823. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40824. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40825. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40826. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40827. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40828. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40829. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40830. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40831. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40832. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40833. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40834. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40835. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40836. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40837. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40838. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40839. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40840. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40841. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40842. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40843. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40844. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40845. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40846. this._uniformBuffer.addUniform("pointSize", 1);
  40847. this._uniformBuffer.create();
  40848. };
  40849. /**
  40850. * Unbinds the textures.
  40851. */
  40852. PBRBaseMaterial.prototype.unbind = function () {
  40853. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40854. this._uniformBuffer.setTexture("reflectionSampler", null);
  40855. }
  40856. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40857. this._uniformBuffer.setTexture("refractionSampler", null);
  40858. }
  40859. _super.prototype.unbind.call(this);
  40860. };
  40861. /**
  40862. * Binds the submesh data.
  40863. * @param world - The world matrix.
  40864. * @param mesh - The BJS mesh.
  40865. * @param subMesh - A submesh of the BJS mesh.
  40866. */
  40867. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40868. var scene = this.getScene();
  40869. var defines = subMesh._materialDefines;
  40870. if (!defines) {
  40871. return;
  40872. }
  40873. var effect = subMesh.effect;
  40874. if (!effect) {
  40875. return;
  40876. }
  40877. this._activeEffect = effect;
  40878. // Matrices
  40879. this.bindOnlyWorldMatrix(world);
  40880. // Normal Matrix
  40881. if (defines.OBJECTSPACE_NORMALMAP) {
  40882. world.toNormalMatrix(this._normalMatrix);
  40883. this.bindOnlyNormalMatrix(this._normalMatrix);
  40884. }
  40885. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40886. // Bones
  40887. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40888. var reflectionTexture = null;
  40889. if (mustRebind) {
  40890. this._uniformBuffer.bindToEffect(effect, "Material");
  40891. this.bindViewProjection(effect);
  40892. reflectionTexture = this._getReflectionTexture();
  40893. var refractionTexture = this._getRefractionTexture();
  40894. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40895. // Texture uniforms
  40896. if (scene.texturesEnabled) {
  40897. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40898. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40899. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40900. }
  40901. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40902. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40903. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40904. }
  40905. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40906. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40907. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40908. }
  40909. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40910. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40911. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40912. if (reflectionTexture.boundingBoxSize) {
  40913. var cubeTexture = reflectionTexture;
  40914. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40915. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40916. }
  40917. var polynomials = reflectionTexture.sphericalPolynomial;
  40918. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40919. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40920. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40921. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40922. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40923. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40924. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40925. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40926. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40927. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40928. }
  40929. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40930. }
  40931. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40932. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40933. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40934. }
  40935. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40936. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40937. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40938. }
  40939. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40940. if (this._metallicTexture) {
  40941. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40942. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40943. }
  40944. else if (this._reflectivityTexture) {
  40945. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40946. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40947. }
  40948. if (this._microSurfaceTexture) {
  40949. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40950. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40951. }
  40952. }
  40953. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40954. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40955. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40956. if (scene._mirroredCameraPosition) {
  40957. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40958. }
  40959. else {
  40960. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40961. }
  40962. }
  40963. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40964. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40965. var depth = 1.0;
  40966. if (!refractionTexture.isCube) {
  40967. if (refractionTexture.depth) {
  40968. depth = refractionTexture.depth;
  40969. }
  40970. }
  40971. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40972. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40973. }
  40974. }
  40975. // Point size
  40976. if (this.pointsCloud) {
  40977. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40978. }
  40979. // Colors
  40980. if (defines.METALLICWORKFLOW) {
  40981. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40982. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40983. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40984. }
  40985. else {
  40986. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40987. }
  40988. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40989. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40990. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  40991. // Misc
  40992. this._lightingInfos.x = this._directIntensity;
  40993. this._lightingInfos.y = this._emissiveIntensity;
  40994. this._lightingInfos.z = this._environmentIntensity;
  40995. this._lightingInfos.w = this._specularIntensity;
  40996. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  40997. }
  40998. // Textures
  40999. if (scene.texturesEnabled) {
  41000. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41001. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41002. }
  41003. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41004. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41005. }
  41006. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41007. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41008. }
  41009. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41010. if (defines.LODBASEDMICROSFURACE) {
  41011. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41012. }
  41013. else {
  41014. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41015. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41016. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41017. }
  41018. }
  41019. if (defines.ENVIRONMENTBRDF) {
  41020. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41021. }
  41022. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41023. if (defines.LODBASEDMICROSFURACE) {
  41024. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41025. }
  41026. else {
  41027. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41028. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41029. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41030. }
  41031. }
  41032. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41033. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41034. }
  41035. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41036. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41037. }
  41038. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41039. if (this._metallicTexture) {
  41040. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41041. }
  41042. else if (this._reflectivityTexture) {
  41043. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41044. }
  41045. if (this._microSurfaceTexture) {
  41046. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41047. }
  41048. }
  41049. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41050. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41051. }
  41052. }
  41053. // Clip plane
  41054. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41055. // Colors
  41056. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41057. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41058. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41059. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41060. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41061. }
  41062. if (mustRebind || !this.isFrozen) {
  41063. // Lights
  41064. if (scene.lightsEnabled && !this._disableLighting) {
  41065. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41066. }
  41067. // View
  41068. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41069. this.bindView(effect);
  41070. }
  41071. // Fog
  41072. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41073. // Morph targets
  41074. if (defines.NUM_MORPH_INFLUENCERS) {
  41075. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41076. }
  41077. // image processing
  41078. this._imageProcessingConfiguration.bind(this._activeEffect);
  41079. // Log. depth
  41080. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41081. }
  41082. this._uniformBuffer.update();
  41083. this._afterBind(mesh);
  41084. };
  41085. /**
  41086. * Returns the animatable textures.
  41087. * @returns - Array of animatable textures.
  41088. */
  41089. PBRBaseMaterial.prototype.getAnimatables = function () {
  41090. var results = [];
  41091. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41092. results.push(this._albedoTexture);
  41093. }
  41094. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41095. results.push(this._ambientTexture);
  41096. }
  41097. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41098. results.push(this._opacityTexture);
  41099. }
  41100. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41101. results.push(this._reflectionTexture);
  41102. }
  41103. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41104. results.push(this._emissiveTexture);
  41105. }
  41106. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41107. results.push(this._metallicTexture);
  41108. }
  41109. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41110. results.push(this._reflectivityTexture);
  41111. }
  41112. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41113. results.push(this._bumpTexture);
  41114. }
  41115. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41116. results.push(this._lightmapTexture);
  41117. }
  41118. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41119. results.push(this._refractionTexture);
  41120. }
  41121. return results;
  41122. };
  41123. /**
  41124. * Returns the texture used for reflections.
  41125. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41126. */
  41127. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41128. if (this._reflectionTexture) {
  41129. return this._reflectionTexture;
  41130. }
  41131. return this.getScene().environmentTexture;
  41132. };
  41133. /**
  41134. * Returns the texture used for refraction or null if none is used.
  41135. * @returns - Refection texture if present. If no refraction texture and refraction
  41136. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41137. */
  41138. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41139. if (this._refractionTexture) {
  41140. return this._refractionTexture;
  41141. }
  41142. if (this._linkRefractionWithTransparency) {
  41143. return this.getScene().environmentTexture;
  41144. }
  41145. return null;
  41146. };
  41147. /**
  41148. * Disposes the resources of the material.
  41149. * @param forceDisposeEffect - Forces the disposal of effects.
  41150. * @param forceDisposeTextures - Forces the disposal of all textures.
  41151. */
  41152. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41153. if (forceDisposeTextures) {
  41154. if (this._albedoTexture) {
  41155. this._albedoTexture.dispose();
  41156. }
  41157. if (this._ambientTexture) {
  41158. this._ambientTexture.dispose();
  41159. }
  41160. if (this._opacityTexture) {
  41161. this._opacityTexture.dispose();
  41162. }
  41163. if (this._reflectionTexture) {
  41164. this._reflectionTexture.dispose();
  41165. }
  41166. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41167. this._environmentBRDFTexture.dispose();
  41168. }
  41169. if (this._emissiveTexture) {
  41170. this._emissiveTexture.dispose();
  41171. }
  41172. if (this._metallicTexture) {
  41173. this._metallicTexture.dispose();
  41174. }
  41175. if (this._reflectivityTexture) {
  41176. this._reflectivityTexture.dispose();
  41177. }
  41178. if (this._bumpTexture) {
  41179. this._bumpTexture.dispose();
  41180. }
  41181. if (this._lightmapTexture) {
  41182. this._lightmapTexture.dispose();
  41183. }
  41184. if (this._refractionTexture) {
  41185. this._refractionTexture.dispose();
  41186. }
  41187. }
  41188. this._renderTargets.dispose();
  41189. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41190. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41191. }
  41192. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41193. };
  41194. /**
  41195. * Stores the reflectivity values based on metallic roughness workflow.
  41196. */
  41197. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41198. __decorate([
  41199. BABYLON.serializeAsImageProcessingConfiguration()
  41200. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41201. __decorate([
  41202. BABYLON.serialize()
  41203. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41204. __decorate([
  41205. BABYLON.serialize()
  41206. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41207. return PBRBaseMaterial;
  41208. }(BABYLON.PushMaterial));
  41209. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41210. })(BABYLON || (BABYLON = {}));
  41211. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41212. var BABYLON;
  41213. (function (BABYLON) {
  41214. /**
  41215. * The Physically based simple base material of BJS.
  41216. *
  41217. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41218. * It is used as the base class for both the specGloss and metalRough conventions.
  41219. */
  41220. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41221. __extends(PBRBaseSimpleMaterial, _super);
  41222. /**
  41223. * Instantiates a new PBRMaterial instance.
  41224. *
  41225. * @param name The material name
  41226. * @param scene The scene the material will be use in.
  41227. */
  41228. function PBRBaseSimpleMaterial(name, scene) {
  41229. var _this = _super.call(this, name, scene) || this;
  41230. /**
  41231. * Number of Simultaneous lights allowed on the material.
  41232. */
  41233. _this.maxSimultaneousLights = 4;
  41234. /**
  41235. * If sets to true, disables all the lights affecting the material.
  41236. */
  41237. _this.disableLighting = false;
  41238. /**
  41239. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41240. */
  41241. _this.invertNormalMapX = false;
  41242. /**
  41243. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41244. */
  41245. _this.invertNormalMapY = false;
  41246. /**
  41247. * Emissivie color used to self-illuminate the model.
  41248. */
  41249. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41250. /**
  41251. * Occlusion Channel Strenght.
  41252. */
  41253. _this.occlusionStrength = 1.0;
  41254. _this.useLightmapAsShadowmap = false;
  41255. _this._useAlphaFromAlbedoTexture = true;
  41256. _this._useAmbientInGrayScale = true;
  41257. return _this;
  41258. }
  41259. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41260. /**
  41261. * Gets the current double sided mode.
  41262. */
  41263. get: function () {
  41264. return this._twoSidedLighting;
  41265. },
  41266. /**
  41267. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41268. */
  41269. set: function (value) {
  41270. if (this._twoSidedLighting === value) {
  41271. return;
  41272. }
  41273. this._twoSidedLighting = value;
  41274. this.backFaceCulling = !value;
  41275. this._markAllSubMeshesAsTexturesDirty();
  41276. },
  41277. enumerable: true,
  41278. configurable: true
  41279. });
  41280. /**
  41281. * Return the active textures of the material.
  41282. */
  41283. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41284. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41285. if (this.environmentTexture) {
  41286. activeTextures.push(this.environmentTexture);
  41287. }
  41288. if (this.normalTexture) {
  41289. activeTextures.push(this.normalTexture);
  41290. }
  41291. if (this.emissiveTexture) {
  41292. activeTextures.push(this.emissiveTexture);
  41293. }
  41294. if (this.occlusionTexture) {
  41295. activeTextures.push(this.occlusionTexture);
  41296. }
  41297. if (this.lightmapTexture) {
  41298. activeTextures.push(this.lightmapTexture);
  41299. }
  41300. return activeTextures;
  41301. };
  41302. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41303. if (_super.prototype.hasTexture.call(this, texture)) {
  41304. return true;
  41305. }
  41306. if (this.lightmapTexture === texture) {
  41307. return true;
  41308. }
  41309. return false;
  41310. };
  41311. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41312. return "PBRBaseSimpleMaterial";
  41313. };
  41314. __decorate([
  41315. BABYLON.serialize(),
  41316. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41317. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41318. __decorate([
  41319. BABYLON.serialize(),
  41320. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41321. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41322. __decorate([
  41323. BABYLON.serializeAsTexture(),
  41324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41325. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41326. __decorate([
  41327. BABYLON.serialize(),
  41328. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41329. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41330. __decorate([
  41331. BABYLON.serialize(),
  41332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41333. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41334. __decorate([
  41335. BABYLON.serializeAsTexture(),
  41336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41337. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41338. __decorate([
  41339. BABYLON.serializeAsColor3("emissive"),
  41340. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41341. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41342. __decorate([
  41343. BABYLON.serializeAsTexture(),
  41344. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41345. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41346. __decorate([
  41347. BABYLON.serialize(),
  41348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41349. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41350. __decorate([
  41351. BABYLON.serializeAsTexture(),
  41352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41353. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41354. __decorate([
  41355. BABYLON.serialize(),
  41356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41357. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41358. __decorate([
  41359. BABYLON.serialize()
  41360. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41361. __decorate([
  41362. BABYLON.serializeAsTexture(),
  41363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41364. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41365. __decorate([
  41366. BABYLON.serialize(),
  41367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41368. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41369. return PBRBaseSimpleMaterial;
  41370. }(BABYLON.PBRBaseMaterial));
  41371. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41372. })(BABYLON || (BABYLON = {}));
  41373. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41374. var BABYLON;
  41375. (function (BABYLON) {
  41376. /**
  41377. * The Physically based material of BJS.
  41378. *
  41379. * This offers the main features of a standard PBR material.
  41380. * For more information, please refer to the documentation :
  41381. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41382. */
  41383. var PBRMaterial = /** @class */ (function (_super) {
  41384. __extends(PBRMaterial, _super);
  41385. /**
  41386. * Instantiates a new PBRMaterial instance.
  41387. *
  41388. * @param name The material name
  41389. * @param scene The scene the material will be use in.
  41390. */
  41391. function PBRMaterial(name, scene) {
  41392. var _this = _super.call(this, name, scene) || this;
  41393. /**
  41394. * Intensity of the direct lights e.g. the four lights available in your scene.
  41395. * This impacts both the direct diffuse and specular highlights.
  41396. */
  41397. _this.directIntensity = 1.0;
  41398. /**
  41399. * Intensity of the emissive part of the material.
  41400. * This helps controlling the emissive effect without modifying the emissive color.
  41401. */
  41402. _this.emissiveIntensity = 1.0;
  41403. /**
  41404. * Intensity of the environment e.g. how much the environment will light the object
  41405. * either through harmonics for rough material or through the refelction for shiny ones.
  41406. */
  41407. _this.environmentIntensity = 1.0;
  41408. /**
  41409. * This is a special control allowing the reduction of the specular highlights coming from the
  41410. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41411. */
  41412. _this.specularIntensity = 1.0;
  41413. /**
  41414. * Debug Control allowing disabling the bump map on this material.
  41415. */
  41416. _this.disableBumpMap = false;
  41417. /**
  41418. * AKA Occlusion Texture Intensity in other nomenclature.
  41419. */
  41420. _this.ambientTextureStrength = 1.0;
  41421. /**
  41422. * The color of a material in ambient lighting.
  41423. */
  41424. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41425. /**
  41426. * AKA Diffuse Color in other nomenclature.
  41427. */
  41428. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41429. /**
  41430. * AKA Specular Color in other nomenclature.
  41431. */
  41432. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41433. /**
  41434. * The color reflected from the material.
  41435. */
  41436. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41437. /**
  41438. * The color emitted from the material.
  41439. */
  41440. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41441. /**
  41442. * AKA Glossiness in other nomenclature.
  41443. */
  41444. _this.microSurface = 1.0;
  41445. /**
  41446. * source material index of refraction (IOR)' / 'destination material IOR.
  41447. */
  41448. _this.indexOfRefraction = 0.66;
  41449. /**
  41450. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41451. */
  41452. _this.invertRefractionY = false;
  41453. /**
  41454. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41455. * Materials half opaque for instance using refraction could benefit from this control.
  41456. */
  41457. _this.linkRefractionWithTransparency = false;
  41458. _this.useLightmapAsShadowmap = false;
  41459. /**
  41460. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41461. */
  41462. _this.useAlphaFromAlbedoTexture = false;
  41463. /**
  41464. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41465. */
  41466. _this.forceAlphaTest = false;
  41467. /**
  41468. * Defines the alpha limits in alpha test mode.
  41469. */
  41470. _this.alphaCutOff = 0.4;
  41471. /**
  41472. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41473. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41474. */
  41475. _this.useSpecularOverAlpha = true;
  41476. /**
  41477. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41478. */
  41479. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41480. /**
  41481. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41482. */
  41483. _this.useRoughnessFromMetallicTextureAlpha = true;
  41484. /**
  41485. * Specifies if the metallic texture contains the roughness information in its green channel.
  41486. */
  41487. _this.useRoughnessFromMetallicTextureGreen = false;
  41488. /**
  41489. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41490. */
  41491. _this.useMetallnessFromMetallicTextureBlue = false;
  41492. /**
  41493. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41494. */
  41495. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41496. /**
  41497. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41498. */
  41499. _this.useAmbientInGrayScale = false;
  41500. /**
  41501. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41502. * The material will try to infer what glossiness each pixel should be.
  41503. */
  41504. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41505. /**
  41506. * BJS is using an harcoded light falloff based on a manually sets up range.
  41507. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41508. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41509. */
  41510. _this.usePhysicalLightFalloff = true;
  41511. /**
  41512. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41513. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41514. */
  41515. _this.useRadianceOverAlpha = true;
  41516. /**
  41517. * Allows using an object space normal map (instead of tangent space).
  41518. */
  41519. _this.useObjectSpaceNormalMap = false;
  41520. /**
  41521. * Allows using the bump map in parallax mode.
  41522. */
  41523. _this.useParallax = false;
  41524. /**
  41525. * Allows using the bump map in parallax occlusion mode.
  41526. */
  41527. _this.useParallaxOcclusion = false;
  41528. /**
  41529. * Controls the scale bias of the parallax mode.
  41530. */
  41531. _this.parallaxScaleBias = 0.05;
  41532. /**
  41533. * If sets to true, disables all the lights affecting the material.
  41534. */
  41535. _this.disableLighting = false;
  41536. /**
  41537. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41538. */
  41539. _this.forceIrradianceInFragment = false;
  41540. /**
  41541. * Number of Simultaneous lights allowed on the material.
  41542. */
  41543. _this.maxSimultaneousLights = 4;
  41544. /**
  41545. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41546. */
  41547. _this.invertNormalMapX = false;
  41548. /**
  41549. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41550. */
  41551. _this.invertNormalMapY = false;
  41552. /**
  41553. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41554. */
  41555. _this.twoSidedLighting = false;
  41556. /**
  41557. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41558. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41559. */
  41560. _this.useAlphaFresnel = false;
  41561. /**
  41562. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41563. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41564. */
  41565. _this.useLinearAlphaFresnel = false;
  41566. /**
  41567. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41568. * And/Or occlude the blended part.
  41569. */
  41570. _this.environmentBRDFTexture = null;
  41571. /**
  41572. * Force normal to face away from face.
  41573. */
  41574. _this.forceNormalForward = false;
  41575. /**
  41576. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41577. * makes the reflect vector face the model (under horizon).
  41578. */
  41579. _this.useHorizonOcclusion = true;
  41580. /**
  41581. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41582. * too much the area relying on ambient texture to define their ambient occlusion.
  41583. */
  41584. _this.useRadianceOcclusion = true;
  41585. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41586. return _this;
  41587. }
  41588. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41589. /**
  41590. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41591. */
  41592. get: function () {
  41593. return this._PBRMATERIAL_OPAQUE;
  41594. },
  41595. enumerable: true,
  41596. configurable: true
  41597. });
  41598. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41599. /**
  41600. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41601. */
  41602. get: function () {
  41603. return this._PBRMATERIAL_ALPHATEST;
  41604. },
  41605. enumerable: true,
  41606. configurable: true
  41607. });
  41608. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41609. /**
  41610. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41611. */
  41612. get: function () {
  41613. return this._PBRMATERIAL_ALPHABLEND;
  41614. },
  41615. enumerable: true,
  41616. configurable: true
  41617. });
  41618. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41619. /**
  41620. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41621. * They are also discarded below the alpha cutoff threshold to improve performances.
  41622. */
  41623. get: function () {
  41624. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41625. },
  41626. enumerable: true,
  41627. configurable: true
  41628. });
  41629. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41630. /**
  41631. * Gets the image processing configuration used either in this material.
  41632. */
  41633. get: function () {
  41634. return this._imageProcessingConfiguration;
  41635. },
  41636. /**
  41637. * Sets the Default image processing configuration used either in the this material.
  41638. *
  41639. * If sets to null, the scene one is in use.
  41640. */
  41641. set: function (value) {
  41642. this._attachImageProcessingConfiguration(value);
  41643. // Ensure the effect will be rebuilt.
  41644. this._markAllSubMeshesAsTexturesDirty();
  41645. },
  41646. enumerable: true,
  41647. configurable: true
  41648. });
  41649. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41650. /**
  41651. * Gets wether the color curves effect is enabled.
  41652. */
  41653. get: function () {
  41654. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41655. },
  41656. /**
  41657. * Sets wether the color curves effect is enabled.
  41658. */
  41659. set: function (value) {
  41660. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41661. },
  41662. enumerable: true,
  41663. configurable: true
  41664. });
  41665. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41666. /**
  41667. * Gets wether the color grading effect is enabled.
  41668. */
  41669. get: function () {
  41670. return this.imageProcessingConfiguration.colorGradingEnabled;
  41671. },
  41672. /**
  41673. * Gets wether the color grading effect is enabled.
  41674. */
  41675. set: function (value) {
  41676. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41677. },
  41678. enumerable: true,
  41679. configurable: true
  41680. });
  41681. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41682. /**
  41683. * Gets wether tonemapping is enabled or not.
  41684. */
  41685. get: function () {
  41686. return this._imageProcessingConfiguration.toneMappingEnabled;
  41687. },
  41688. /**
  41689. * Sets wether tonemapping is enabled or not
  41690. */
  41691. set: function (value) {
  41692. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41693. },
  41694. enumerable: true,
  41695. configurable: true
  41696. });
  41697. ;
  41698. ;
  41699. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41700. /**
  41701. * The camera exposure used on this material.
  41702. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41703. * This corresponds to a photographic exposure.
  41704. */
  41705. get: function () {
  41706. return this._imageProcessingConfiguration.exposure;
  41707. },
  41708. /**
  41709. * The camera exposure used on this material.
  41710. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41711. * This corresponds to a photographic exposure.
  41712. */
  41713. set: function (value) {
  41714. this._imageProcessingConfiguration.exposure = value;
  41715. },
  41716. enumerable: true,
  41717. configurable: true
  41718. });
  41719. ;
  41720. ;
  41721. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41722. /**
  41723. * Gets The camera contrast used on this material.
  41724. */
  41725. get: function () {
  41726. return this._imageProcessingConfiguration.contrast;
  41727. },
  41728. /**
  41729. * Sets The camera contrast used on this material.
  41730. */
  41731. set: function (value) {
  41732. this._imageProcessingConfiguration.contrast = value;
  41733. },
  41734. enumerable: true,
  41735. configurable: true
  41736. });
  41737. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41738. /**
  41739. * Gets the Color Grading 2D Lookup Texture.
  41740. */
  41741. get: function () {
  41742. return this._imageProcessingConfiguration.colorGradingTexture;
  41743. },
  41744. /**
  41745. * Sets the Color Grading 2D Lookup Texture.
  41746. */
  41747. set: function (value) {
  41748. this._imageProcessingConfiguration.colorGradingTexture = value;
  41749. },
  41750. enumerable: true,
  41751. configurable: true
  41752. });
  41753. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41754. /**
  41755. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41756. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41757. * 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;
  41758. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41759. */
  41760. get: function () {
  41761. return this._imageProcessingConfiguration.colorCurves;
  41762. },
  41763. /**
  41764. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41765. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41766. * 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;
  41767. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41768. */
  41769. set: function (value) {
  41770. this._imageProcessingConfiguration.colorCurves = value;
  41771. },
  41772. enumerable: true,
  41773. configurable: true
  41774. });
  41775. /**
  41776. * Returns the name of this material class.
  41777. */
  41778. PBRMaterial.prototype.getClassName = function () {
  41779. return "PBRMaterial";
  41780. };
  41781. /**
  41782. * Returns an array of the actively used textures.
  41783. * @returns - Array of BaseTextures
  41784. */
  41785. PBRMaterial.prototype.getActiveTextures = function () {
  41786. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41787. if (this._albedoTexture) {
  41788. activeTextures.push(this._albedoTexture);
  41789. }
  41790. if (this._ambientTexture) {
  41791. activeTextures.push(this._ambientTexture);
  41792. }
  41793. if (this._opacityTexture) {
  41794. activeTextures.push(this._opacityTexture);
  41795. }
  41796. if (this._reflectionTexture) {
  41797. activeTextures.push(this._reflectionTexture);
  41798. }
  41799. if (this._emissiveTexture) {
  41800. activeTextures.push(this._emissiveTexture);
  41801. }
  41802. if (this._reflectivityTexture) {
  41803. activeTextures.push(this._reflectivityTexture);
  41804. }
  41805. if (this._metallicTexture) {
  41806. activeTextures.push(this._metallicTexture);
  41807. }
  41808. if (this._microSurfaceTexture) {
  41809. activeTextures.push(this._microSurfaceTexture);
  41810. }
  41811. if (this._bumpTexture) {
  41812. activeTextures.push(this._bumpTexture);
  41813. }
  41814. if (this._lightmapTexture) {
  41815. activeTextures.push(this._lightmapTexture);
  41816. }
  41817. if (this._refractionTexture) {
  41818. activeTextures.push(this._refractionTexture);
  41819. }
  41820. return activeTextures;
  41821. };
  41822. /**
  41823. * Checks to see if a texture is used in the material.
  41824. * @param texture - Base texture to use.
  41825. * @returns - Boolean specifying if a texture is used in the material.
  41826. */
  41827. PBRMaterial.prototype.hasTexture = function (texture) {
  41828. if (_super.prototype.hasTexture.call(this, texture)) {
  41829. return true;
  41830. }
  41831. if (this._albedoTexture === texture) {
  41832. return true;
  41833. }
  41834. if (this._ambientTexture === texture) {
  41835. return true;
  41836. }
  41837. if (this._opacityTexture === texture) {
  41838. return true;
  41839. }
  41840. if (this._reflectionTexture === texture) {
  41841. return true;
  41842. }
  41843. if (this._reflectivityTexture === texture) {
  41844. return true;
  41845. }
  41846. if (this._metallicTexture === texture) {
  41847. return true;
  41848. }
  41849. if (this._microSurfaceTexture === texture) {
  41850. return true;
  41851. }
  41852. if (this._bumpTexture === texture) {
  41853. return true;
  41854. }
  41855. if (this._lightmapTexture === texture) {
  41856. return true;
  41857. }
  41858. if (this._refractionTexture === texture) {
  41859. return true;
  41860. }
  41861. return false;
  41862. };
  41863. /**
  41864. * Makes a duplicate of the current material.
  41865. * @param name - name to use for the new material.
  41866. */
  41867. PBRMaterial.prototype.clone = function (name) {
  41868. var _this = this;
  41869. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41870. clone.id = name;
  41871. clone.name = name;
  41872. return clone;
  41873. };
  41874. /**
  41875. * Serializes this PBR Material.
  41876. * @returns - An object with the serialized material.
  41877. */
  41878. PBRMaterial.prototype.serialize = function () {
  41879. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41880. serializationObject.customType = "BABYLON.PBRMaterial";
  41881. return serializationObject;
  41882. };
  41883. // Statics
  41884. /**
  41885. * Parses a PBR Material from a serialized object.
  41886. * @param source - Serialized object.
  41887. * @param scene - BJS scene instance.
  41888. * @param rootUrl - url for the scene object
  41889. * @returns - PBRMaterial
  41890. */
  41891. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41892. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41893. };
  41894. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41895. /**
  41896. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41897. */
  41898. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41899. /**
  41900. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41901. */
  41902. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41903. /**
  41904. * 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.
  41905. * They are also discarded below the alpha cutoff threshold to improve performances.
  41906. */
  41907. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41908. __decorate([
  41909. BABYLON.serialize(),
  41910. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41911. ], PBRMaterial.prototype, "directIntensity", void 0);
  41912. __decorate([
  41913. BABYLON.serialize(),
  41914. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41915. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41916. __decorate([
  41917. BABYLON.serialize(),
  41918. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41919. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41920. __decorate([
  41921. BABYLON.serialize(),
  41922. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41923. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41924. __decorate([
  41925. BABYLON.serialize(),
  41926. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41927. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41928. __decorate([
  41929. BABYLON.serializeAsTexture(),
  41930. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41931. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41932. __decorate([
  41933. BABYLON.serializeAsTexture(),
  41934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41935. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41936. __decorate([
  41937. BABYLON.serialize(),
  41938. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41939. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41940. __decorate([
  41941. BABYLON.serializeAsTexture(),
  41942. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41943. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41944. __decorate([
  41945. BABYLON.serializeAsTexture(),
  41946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41947. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41948. __decorate([
  41949. BABYLON.serializeAsTexture(),
  41950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41951. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41952. __decorate([
  41953. BABYLON.serializeAsTexture(),
  41954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41955. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41956. __decorate([
  41957. BABYLON.serializeAsTexture(),
  41958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41959. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41960. __decorate([
  41961. BABYLON.serialize(),
  41962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41963. ], PBRMaterial.prototype, "metallic", void 0);
  41964. __decorate([
  41965. BABYLON.serialize(),
  41966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41967. ], PBRMaterial.prototype, "roughness", void 0);
  41968. __decorate([
  41969. BABYLON.serializeAsTexture(),
  41970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41971. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41972. __decorate([
  41973. BABYLON.serializeAsTexture(),
  41974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41975. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41976. __decorate([
  41977. BABYLON.serializeAsTexture(),
  41978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41979. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41980. __decorate([
  41981. BABYLON.serializeAsTexture(),
  41982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41983. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41984. __decorate([
  41985. BABYLON.serializeAsColor3("ambient"),
  41986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41987. ], PBRMaterial.prototype, "ambientColor", void 0);
  41988. __decorate([
  41989. BABYLON.serializeAsColor3("albedo"),
  41990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41991. ], PBRMaterial.prototype, "albedoColor", void 0);
  41992. __decorate([
  41993. BABYLON.serializeAsColor3("reflectivity"),
  41994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41995. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  41996. __decorate([
  41997. BABYLON.serializeAsColor3("reflection"),
  41998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41999. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42000. __decorate([
  42001. BABYLON.serializeAsColor3("emissive"),
  42002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42003. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42004. __decorate([
  42005. BABYLON.serialize(),
  42006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42007. ], PBRMaterial.prototype, "microSurface", void 0);
  42008. __decorate([
  42009. BABYLON.serialize(),
  42010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42011. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42012. __decorate([
  42013. BABYLON.serialize(),
  42014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42015. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42016. __decorate([
  42017. BABYLON.serialize(),
  42018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42019. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42020. __decorate([
  42021. BABYLON.serialize(),
  42022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42023. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42024. __decorate([
  42025. BABYLON.serialize(),
  42026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42027. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42028. __decorate([
  42029. BABYLON.serialize(),
  42030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42031. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42032. __decorate([
  42033. BABYLON.serialize(),
  42034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42035. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42036. __decorate([
  42037. BABYLON.serialize(),
  42038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42039. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42040. __decorate([
  42041. BABYLON.serialize(),
  42042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42043. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42044. __decorate([
  42045. BABYLON.serialize(),
  42046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42047. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42048. __decorate([
  42049. BABYLON.serialize(),
  42050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42051. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42052. __decorate([
  42053. BABYLON.serialize(),
  42054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42055. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42056. __decorate([
  42057. BABYLON.serialize(),
  42058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42059. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42060. __decorate([
  42061. BABYLON.serialize(),
  42062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42063. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42064. __decorate([
  42065. BABYLON.serialize(),
  42066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42067. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42068. __decorate([
  42069. BABYLON.serialize(),
  42070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42071. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42072. __decorate([
  42073. BABYLON.serialize(),
  42074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42075. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42076. __decorate([
  42077. BABYLON.serialize(),
  42078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42079. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42080. __decorate([
  42081. BABYLON.serialize(),
  42082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42083. ], PBRMaterial.prototype, "useParallax", void 0);
  42084. __decorate([
  42085. BABYLON.serialize(),
  42086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42087. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42088. __decorate([
  42089. BABYLON.serialize(),
  42090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42091. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42092. __decorate([
  42093. BABYLON.serialize(),
  42094. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42095. ], PBRMaterial.prototype, "disableLighting", void 0);
  42096. __decorate([
  42097. BABYLON.serialize(),
  42098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42099. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42100. __decorate([
  42101. BABYLON.serialize(),
  42102. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42103. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42104. __decorate([
  42105. BABYLON.serialize(),
  42106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42107. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42108. __decorate([
  42109. BABYLON.serialize(),
  42110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42111. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42112. __decorate([
  42113. BABYLON.serialize(),
  42114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42115. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42116. __decorate([
  42117. BABYLON.serialize(),
  42118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42119. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42120. __decorate([
  42121. BABYLON.serialize(),
  42122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42123. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42124. __decorate([
  42125. BABYLON.serializeAsTexture(),
  42126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42127. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42128. __decorate([
  42129. BABYLON.serialize(),
  42130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42131. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42132. __decorate([
  42133. BABYLON.serialize(),
  42134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42135. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42136. __decorate([
  42137. BABYLON.serialize(),
  42138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42139. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42140. return PBRMaterial;
  42141. }(BABYLON.PBRBaseMaterial));
  42142. BABYLON.PBRMaterial = PBRMaterial;
  42143. })(BABYLON || (BABYLON = {}));
  42144. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42145. var BABYLON;
  42146. (function (BABYLON) {
  42147. /**
  42148. * The PBR material of BJS following the metal roughness convention.
  42149. *
  42150. * This fits to the PBR convention in the GLTF definition:
  42151. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42152. */
  42153. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42154. __extends(PBRMetallicRoughnessMaterial, _super);
  42155. /**
  42156. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42157. *
  42158. * @param name The material name
  42159. * @param scene The scene the material will be use in.
  42160. */
  42161. function PBRMetallicRoughnessMaterial(name, scene) {
  42162. var _this = _super.call(this, name, scene) || this;
  42163. _this._useRoughnessFromMetallicTextureAlpha = false;
  42164. _this._useRoughnessFromMetallicTextureGreen = true;
  42165. _this._useMetallnessFromMetallicTextureBlue = true;
  42166. _this._forceMetallicWorkflow = true;
  42167. return _this;
  42168. }
  42169. /**
  42170. * Return the currrent class name of the material.
  42171. */
  42172. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42173. return "PBRMetallicRoughnessMaterial";
  42174. };
  42175. /**
  42176. * Return the active textures of the material.
  42177. */
  42178. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42179. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42180. if (this.baseTexture) {
  42181. activeTextures.push(this.baseTexture);
  42182. }
  42183. if (this.metallicRoughnessTexture) {
  42184. activeTextures.push(this.metallicRoughnessTexture);
  42185. }
  42186. return activeTextures;
  42187. };
  42188. /**
  42189. * Checks to see if a texture is used in the material.
  42190. * @param texture - Base texture to use.
  42191. * @returns - Boolean specifying if a texture is used in the material.
  42192. */
  42193. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42194. if (_super.prototype.hasTexture.call(this, texture)) {
  42195. return true;
  42196. }
  42197. if (this.baseTexture === texture) {
  42198. return true;
  42199. }
  42200. if (this.metallicRoughnessTexture === texture) {
  42201. return true;
  42202. }
  42203. return false;
  42204. };
  42205. /**
  42206. * Makes a duplicate of the current material.
  42207. * @param name - name to use for the new material.
  42208. */
  42209. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42210. var _this = this;
  42211. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42212. clone.id = name;
  42213. clone.name = name;
  42214. return clone;
  42215. };
  42216. /**
  42217. * Serialize the material to a parsable JSON object.
  42218. */
  42219. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42220. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42221. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42222. return serializationObject;
  42223. };
  42224. /**
  42225. * Parses a JSON object correponding to the serialize function.
  42226. */
  42227. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42228. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42229. };
  42230. __decorate([
  42231. BABYLON.serializeAsColor3(),
  42232. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42233. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42234. __decorate([
  42235. BABYLON.serializeAsTexture(),
  42236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42237. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42238. __decorate([
  42239. BABYLON.serialize(),
  42240. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42241. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42242. __decorate([
  42243. BABYLON.serialize(),
  42244. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42245. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42246. __decorate([
  42247. BABYLON.serializeAsTexture(),
  42248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42249. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42250. return PBRMetallicRoughnessMaterial;
  42251. }(BABYLON.PBRBaseSimpleMaterial));
  42252. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42253. })(BABYLON || (BABYLON = {}));
  42254. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42255. var BABYLON;
  42256. (function (BABYLON) {
  42257. /**
  42258. * The PBR material of BJS following the specular glossiness convention.
  42259. *
  42260. * This fits to the PBR convention in the GLTF definition:
  42261. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42262. */
  42263. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42264. __extends(PBRSpecularGlossinessMaterial, _super);
  42265. /**
  42266. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42267. *
  42268. * @param name The material name
  42269. * @param scene The scene the material will be use in.
  42270. */
  42271. function PBRSpecularGlossinessMaterial(name, scene) {
  42272. var _this = _super.call(this, name, scene) || this;
  42273. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42274. return _this;
  42275. }
  42276. /**
  42277. * Return the currrent class name of the material.
  42278. */
  42279. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42280. return "PBRSpecularGlossinessMaterial";
  42281. };
  42282. /**
  42283. * Return the active textures of the material.
  42284. */
  42285. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42286. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42287. if (this.diffuseTexture) {
  42288. activeTextures.push(this.diffuseTexture);
  42289. }
  42290. if (this.specularGlossinessTexture) {
  42291. activeTextures.push(this.specularGlossinessTexture);
  42292. }
  42293. return activeTextures;
  42294. };
  42295. /**
  42296. * Checks to see if a texture is used in the material.
  42297. * @param texture - Base texture to use.
  42298. * @returns - Boolean specifying if a texture is used in the material.
  42299. */
  42300. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42301. if (_super.prototype.hasTexture.call(this, texture)) {
  42302. return true;
  42303. }
  42304. if (this.diffuseTexture === texture) {
  42305. return true;
  42306. }
  42307. if (this.specularGlossinessTexture === texture) {
  42308. return true;
  42309. }
  42310. return false;
  42311. };
  42312. /**
  42313. * Makes a duplicate of the current material.
  42314. * @param name - name to use for the new material.
  42315. */
  42316. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42317. var _this = this;
  42318. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42319. clone.id = name;
  42320. clone.name = name;
  42321. return clone;
  42322. };
  42323. /**
  42324. * Serialize the material to a parsable JSON object.
  42325. */
  42326. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42327. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42328. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42329. return serializationObject;
  42330. };
  42331. /**
  42332. * Parses a JSON object correponding to the serialize function.
  42333. */
  42334. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42335. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42336. };
  42337. __decorate([
  42338. BABYLON.serializeAsColor3("diffuse"),
  42339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42340. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42341. __decorate([
  42342. BABYLON.serializeAsTexture(),
  42343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42344. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42345. __decorate([
  42346. BABYLON.serializeAsColor3("specular"),
  42347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42348. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42349. __decorate([
  42350. BABYLON.serialize(),
  42351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42352. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42353. __decorate([
  42354. BABYLON.serializeAsTexture(),
  42355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42356. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42357. return PBRSpecularGlossinessMaterial;
  42358. }(BABYLON.PBRBaseSimpleMaterial));
  42359. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42360. })(BABYLON || (BABYLON = {}));
  42361. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42362. var BABYLON;
  42363. (function (BABYLON) {
  42364. BABYLON.CameraInputTypes = {};
  42365. var CameraInputsManager = /** @class */ (function () {
  42366. function CameraInputsManager(camera) {
  42367. this.attached = {};
  42368. this.camera = camera;
  42369. this.checkInputs = function () { };
  42370. }
  42371. /**
  42372. * Add an input method to a camera.
  42373. * builtin inputs example: camera.inputs.addGamepad();
  42374. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42375. * @param input camera input method
  42376. */
  42377. CameraInputsManager.prototype.add = function (input) {
  42378. var type = input.getSimpleName();
  42379. if (this.attached[type]) {
  42380. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42381. return;
  42382. }
  42383. this.attached[type] = input;
  42384. input.camera = this.camera;
  42385. //for checkInputs, we are dynamically creating a function
  42386. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42387. if (input.checkInputs) {
  42388. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42389. }
  42390. if (this.attachedElement) {
  42391. input.attachControl(this.attachedElement);
  42392. }
  42393. };
  42394. /**
  42395. * Remove a specific input method from a camera
  42396. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42397. * @param inputToRemove camera input method
  42398. */
  42399. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42400. for (var cam in this.attached) {
  42401. var input = this.attached[cam];
  42402. if (input === inputToRemove) {
  42403. input.detachControl(this.attachedElement);
  42404. input.camera = null;
  42405. delete this.attached[cam];
  42406. this.rebuildInputCheck();
  42407. }
  42408. }
  42409. };
  42410. CameraInputsManager.prototype.removeByType = function (inputType) {
  42411. for (var cam in this.attached) {
  42412. var input = this.attached[cam];
  42413. if (input.getClassName() === inputType) {
  42414. input.detachControl(this.attachedElement);
  42415. input.camera = null;
  42416. delete this.attached[cam];
  42417. this.rebuildInputCheck();
  42418. }
  42419. }
  42420. };
  42421. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42422. var current = this.checkInputs;
  42423. return function () {
  42424. current();
  42425. fn();
  42426. };
  42427. };
  42428. CameraInputsManager.prototype.attachInput = function (input) {
  42429. if (this.attachedElement) {
  42430. input.attachControl(this.attachedElement, this.noPreventDefault);
  42431. }
  42432. };
  42433. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42434. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42435. if (this.attachedElement) {
  42436. return;
  42437. }
  42438. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42439. this.attachedElement = element;
  42440. this.noPreventDefault = noPreventDefault;
  42441. for (var cam in this.attached) {
  42442. this.attached[cam].attachControl(element, noPreventDefault);
  42443. }
  42444. };
  42445. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42446. if (disconnect === void 0) { disconnect = false; }
  42447. if (this.attachedElement !== element) {
  42448. return;
  42449. }
  42450. for (var cam in this.attached) {
  42451. this.attached[cam].detachControl(element);
  42452. if (disconnect) {
  42453. this.attached[cam].camera = null;
  42454. }
  42455. }
  42456. this.attachedElement = null;
  42457. };
  42458. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42459. this.checkInputs = function () { };
  42460. for (var cam in this.attached) {
  42461. var input = this.attached[cam];
  42462. if (input.checkInputs) {
  42463. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42464. }
  42465. }
  42466. };
  42467. /**
  42468. * Remove all attached input methods from a camera
  42469. */
  42470. CameraInputsManager.prototype.clear = function () {
  42471. if (this.attachedElement) {
  42472. this.detachElement(this.attachedElement, true);
  42473. }
  42474. this.attached = {};
  42475. this.attachedElement = null;
  42476. this.checkInputs = function () { };
  42477. };
  42478. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42479. var inputs = {};
  42480. for (var cam in this.attached) {
  42481. var input = this.attached[cam];
  42482. var res = BABYLON.SerializationHelper.Serialize(input);
  42483. inputs[input.getClassName()] = res;
  42484. }
  42485. serializedCamera.inputsmgr = inputs;
  42486. };
  42487. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42488. var parsedInputs = parsedCamera.inputsmgr;
  42489. if (parsedInputs) {
  42490. this.clear();
  42491. for (var n in parsedInputs) {
  42492. var construct = BABYLON.CameraInputTypes[n];
  42493. if (construct) {
  42494. var parsedinput = parsedInputs[n];
  42495. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42496. this.add(input);
  42497. }
  42498. }
  42499. }
  42500. else {
  42501. //2016-03-08 this part is for managing backward compatibility
  42502. for (var n in this.attached) {
  42503. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42504. if (construct) {
  42505. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42506. this.remove(this.attached[n]);
  42507. this.add(input);
  42508. }
  42509. }
  42510. }
  42511. };
  42512. return CameraInputsManager;
  42513. }());
  42514. BABYLON.CameraInputsManager = CameraInputsManager;
  42515. })(BABYLON || (BABYLON = {}));
  42516. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42517. var BABYLON;
  42518. (function (BABYLON) {
  42519. var TargetCamera = /** @class */ (function (_super) {
  42520. __extends(TargetCamera, _super);
  42521. function TargetCamera(name, position, scene) {
  42522. var _this = _super.call(this, name, position, scene) || this;
  42523. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42524. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42525. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42526. _this.speed = 2.0;
  42527. _this.noRotationConstraint = false;
  42528. _this.lockedTarget = null;
  42529. _this._currentTarget = BABYLON.Vector3.Zero();
  42530. _this._viewMatrix = BABYLON.Matrix.Zero();
  42531. _this._camMatrix = BABYLON.Matrix.Zero();
  42532. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42533. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42534. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42535. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42536. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42537. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42538. _this._tempMatrix = BABYLON.Matrix.Zero();
  42539. return _this;
  42540. }
  42541. TargetCamera.prototype.getFrontPosition = function (distance) {
  42542. this.getWorldMatrix();
  42543. var direction = this.getTarget().subtract(this.position);
  42544. direction.normalize();
  42545. direction.scaleInPlace(distance);
  42546. return this.globalPosition.add(direction);
  42547. };
  42548. TargetCamera.prototype._getLockedTargetPosition = function () {
  42549. if (!this.lockedTarget) {
  42550. return null;
  42551. }
  42552. if (this.lockedTarget.absolutePosition) {
  42553. this.lockedTarget.computeWorldMatrix();
  42554. }
  42555. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42556. };
  42557. TargetCamera.prototype.storeState = function () {
  42558. this._storedPosition = this.position.clone();
  42559. this._storedRotation = this.rotation.clone();
  42560. if (this.rotationQuaternion) {
  42561. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42562. }
  42563. return _super.prototype.storeState.call(this);
  42564. };
  42565. /**
  42566. * Restored camera state. You must call storeState() first
  42567. */
  42568. TargetCamera.prototype._restoreStateValues = function () {
  42569. if (!_super.prototype._restoreStateValues.call(this)) {
  42570. return false;
  42571. }
  42572. this.position = this._storedPosition.clone();
  42573. this.rotation = this._storedRotation.clone();
  42574. if (this.rotationQuaternion) {
  42575. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42576. }
  42577. this.cameraDirection.copyFromFloats(0, 0, 0);
  42578. this.cameraRotation.copyFromFloats(0, 0);
  42579. return true;
  42580. };
  42581. // Cache
  42582. TargetCamera.prototype._initCache = function () {
  42583. _super.prototype._initCache.call(this);
  42584. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42585. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42586. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42587. };
  42588. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42589. if (!ignoreParentClass) {
  42590. _super.prototype._updateCache.call(this);
  42591. }
  42592. var lockedTargetPosition = this._getLockedTargetPosition();
  42593. if (!lockedTargetPosition) {
  42594. this._cache.lockedTarget = null;
  42595. }
  42596. else {
  42597. if (!this._cache.lockedTarget) {
  42598. this._cache.lockedTarget = lockedTargetPosition.clone();
  42599. }
  42600. else {
  42601. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42602. }
  42603. }
  42604. this._cache.rotation.copyFrom(this.rotation);
  42605. if (this.rotationQuaternion)
  42606. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42607. };
  42608. // Synchronized
  42609. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42610. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42611. return false;
  42612. }
  42613. var lockedTargetPosition = this._getLockedTargetPosition();
  42614. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42615. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42616. };
  42617. // Methods
  42618. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42619. var engine = this.getEngine();
  42620. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42621. };
  42622. // Target
  42623. TargetCamera.prototype.setTarget = function (target) {
  42624. this.upVector.normalize();
  42625. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42626. this._camMatrix.invert();
  42627. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42628. var vDir = target.subtract(this.position);
  42629. if (vDir.x >= 0.0) {
  42630. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42631. }
  42632. else {
  42633. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42634. }
  42635. this.rotation.z = 0;
  42636. if (isNaN(this.rotation.x)) {
  42637. this.rotation.x = 0;
  42638. }
  42639. if (isNaN(this.rotation.y)) {
  42640. this.rotation.y = 0;
  42641. }
  42642. if (isNaN(this.rotation.z)) {
  42643. this.rotation.z = 0;
  42644. }
  42645. if (this.rotationQuaternion) {
  42646. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42647. }
  42648. };
  42649. /**
  42650. * Return the current target position of the camera. This value is expressed in local space.
  42651. */
  42652. TargetCamera.prototype.getTarget = function () {
  42653. return this._currentTarget;
  42654. };
  42655. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42656. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42657. };
  42658. TargetCamera.prototype._updatePosition = function () {
  42659. if (this.parent) {
  42660. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42661. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42662. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42663. return;
  42664. }
  42665. this.position.addInPlace(this.cameraDirection);
  42666. };
  42667. TargetCamera.prototype._checkInputs = function () {
  42668. var needToMove = this._decideIfNeedsToMove();
  42669. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42670. // Move
  42671. if (needToMove) {
  42672. this._updatePosition();
  42673. }
  42674. // Rotate
  42675. if (needToRotate) {
  42676. this.rotation.x += this.cameraRotation.x;
  42677. this.rotation.y += this.cameraRotation.y;
  42678. //rotate, if quaternion is set and rotation was used
  42679. if (this.rotationQuaternion) {
  42680. var len = this.rotation.lengthSquared();
  42681. if (len) {
  42682. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42683. }
  42684. }
  42685. if (!this.noRotationConstraint) {
  42686. var limit = (Math.PI / 2) * 0.95;
  42687. if (this.rotation.x > limit)
  42688. this.rotation.x = limit;
  42689. if (this.rotation.x < -limit)
  42690. this.rotation.x = -limit;
  42691. }
  42692. }
  42693. // Inertia
  42694. if (needToMove) {
  42695. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42696. this.cameraDirection.x = 0;
  42697. }
  42698. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42699. this.cameraDirection.y = 0;
  42700. }
  42701. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42702. this.cameraDirection.z = 0;
  42703. }
  42704. this.cameraDirection.scaleInPlace(this.inertia);
  42705. }
  42706. if (needToRotate) {
  42707. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42708. this.cameraRotation.x = 0;
  42709. }
  42710. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42711. this.cameraRotation.y = 0;
  42712. }
  42713. this.cameraRotation.scaleInPlace(this.inertia);
  42714. }
  42715. _super.prototype._checkInputs.call(this);
  42716. };
  42717. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42718. if (this.rotationQuaternion) {
  42719. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42720. }
  42721. else {
  42722. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42723. }
  42724. //update the up vector!
  42725. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42726. };
  42727. TargetCamera.prototype._getViewMatrix = function () {
  42728. if (this.lockedTarget) {
  42729. this.setTarget(this._getLockedTargetPosition());
  42730. }
  42731. // Compute
  42732. this._updateCameraRotationMatrix();
  42733. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42734. // Computing target and final matrix
  42735. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42736. if (this.getScene().useRightHandedSystem) {
  42737. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42738. }
  42739. else {
  42740. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42741. }
  42742. return this._viewMatrix;
  42743. };
  42744. /**
  42745. * @override
  42746. * Override Camera.createRigCamera
  42747. */
  42748. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42749. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42750. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42751. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42752. if (!this.rotationQuaternion) {
  42753. this.rotationQuaternion = new BABYLON.Quaternion();
  42754. }
  42755. rigCamera._cameraRigParams = {};
  42756. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42757. }
  42758. return rigCamera;
  42759. }
  42760. return null;
  42761. };
  42762. /**
  42763. * @override
  42764. * Override Camera._updateRigCameras
  42765. */
  42766. TargetCamera.prototype._updateRigCameras = function () {
  42767. var camLeft = this._rigCameras[0];
  42768. var camRight = this._rigCameras[1];
  42769. switch (this.cameraRigMode) {
  42770. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42771. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42772. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42773. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42774. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42775. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42776. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42777. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42778. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42779. camLeft.setTarget(this.getTarget());
  42780. camRight.setTarget(this.getTarget());
  42781. break;
  42782. case BABYLON.Camera.RIG_MODE_VR:
  42783. if (camLeft.rotationQuaternion) {
  42784. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42785. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42786. }
  42787. else {
  42788. camLeft.rotation.copyFrom(this.rotation);
  42789. camRight.rotation.copyFrom(this.rotation);
  42790. }
  42791. camLeft.position.copyFrom(this.position);
  42792. camRight.position.copyFrom(this.position);
  42793. break;
  42794. }
  42795. _super.prototype._updateRigCameras.call(this);
  42796. };
  42797. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42798. if (!this._rigCamTransformMatrix) {
  42799. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42800. }
  42801. var target = this.getTarget();
  42802. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42803. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42804. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42805. };
  42806. TargetCamera.prototype.getClassName = function () {
  42807. return "TargetCamera";
  42808. };
  42809. __decorate([
  42810. BABYLON.serializeAsVector3()
  42811. ], TargetCamera.prototype, "rotation", void 0);
  42812. __decorate([
  42813. BABYLON.serialize()
  42814. ], TargetCamera.prototype, "speed", void 0);
  42815. __decorate([
  42816. BABYLON.serializeAsMeshReference("lockedTargetId")
  42817. ], TargetCamera.prototype, "lockedTarget", void 0);
  42818. return TargetCamera;
  42819. }(BABYLON.Camera));
  42820. BABYLON.TargetCamera = TargetCamera;
  42821. })(BABYLON || (BABYLON = {}));
  42822. //# sourceMappingURL=babylon.targetCamera.js.map
  42823. var BABYLON;
  42824. (function (BABYLON) {
  42825. var FreeCameraMouseInput = /** @class */ (function () {
  42826. function FreeCameraMouseInput(touchEnabled) {
  42827. if (touchEnabled === void 0) { touchEnabled = true; }
  42828. this.touchEnabled = touchEnabled;
  42829. this.buttons = [0, 1, 2];
  42830. this.angularSensibility = 2000.0;
  42831. this.previousPosition = null;
  42832. }
  42833. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42834. var _this = this;
  42835. var engine = this.camera.getEngine();
  42836. if (!this._pointerInput) {
  42837. this._pointerInput = function (p, s) {
  42838. var evt = p.event;
  42839. if (engine.isInVRExclusivePointerMode) {
  42840. return;
  42841. }
  42842. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42843. return;
  42844. }
  42845. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42846. return;
  42847. }
  42848. var srcElement = (evt.srcElement || evt.target);
  42849. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42850. try {
  42851. srcElement.setPointerCapture(evt.pointerId);
  42852. }
  42853. catch (e) {
  42854. //Nothing to do with the error. Execution will continue.
  42855. }
  42856. _this.previousPosition = {
  42857. x: evt.clientX,
  42858. y: evt.clientY
  42859. };
  42860. if (!noPreventDefault) {
  42861. evt.preventDefault();
  42862. element.focus();
  42863. }
  42864. }
  42865. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42866. try {
  42867. srcElement.releasePointerCapture(evt.pointerId);
  42868. }
  42869. catch (e) {
  42870. //Nothing to do with the error.
  42871. }
  42872. _this.previousPosition = null;
  42873. if (!noPreventDefault) {
  42874. evt.preventDefault();
  42875. }
  42876. }
  42877. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42878. if (!_this.previousPosition || engine.isPointerLock) {
  42879. return;
  42880. }
  42881. var offsetX = evt.clientX - _this.previousPosition.x;
  42882. var offsetY = evt.clientY - _this.previousPosition.y;
  42883. if (_this.camera.getScene().useRightHandedSystem) {
  42884. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42885. }
  42886. else {
  42887. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42888. }
  42889. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42890. _this.previousPosition = {
  42891. x: evt.clientX,
  42892. y: evt.clientY
  42893. };
  42894. if (!noPreventDefault) {
  42895. evt.preventDefault();
  42896. }
  42897. }
  42898. };
  42899. }
  42900. this._onMouseMove = function (evt) {
  42901. if (!engine.isPointerLock) {
  42902. return;
  42903. }
  42904. if (engine.isInVRExclusivePointerMode) {
  42905. return;
  42906. }
  42907. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42908. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42909. if (_this.camera.getScene().useRightHandedSystem) {
  42910. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42911. }
  42912. else {
  42913. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42914. }
  42915. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42916. _this.previousPosition = null;
  42917. if (!noPreventDefault) {
  42918. evt.preventDefault();
  42919. }
  42920. };
  42921. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42922. element.addEventListener("mousemove", this._onMouseMove, false);
  42923. };
  42924. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42925. if (this._observer && element) {
  42926. this.camera.getScene().onPointerObservable.remove(this._observer);
  42927. if (this._onMouseMove) {
  42928. element.removeEventListener("mousemove", this._onMouseMove);
  42929. }
  42930. this._observer = null;
  42931. this._onMouseMove = null;
  42932. this.previousPosition = null;
  42933. }
  42934. };
  42935. FreeCameraMouseInput.prototype.getClassName = function () {
  42936. return "FreeCameraMouseInput";
  42937. };
  42938. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42939. return "mouse";
  42940. };
  42941. __decorate([
  42942. BABYLON.serialize()
  42943. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42944. __decorate([
  42945. BABYLON.serialize()
  42946. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42947. return FreeCameraMouseInput;
  42948. }());
  42949. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42950. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42951. })(BABYLON || (BABYLON = {}));
  42952. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42953. var BABYLON;
  42954. (function (BABYLON) {
  42955. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42956. function FreeCameraKeyboardMoveInput() {
  42957. this._keys = new Array();
  42958. this.keysUp = [38];
  42959. this.keysDown = [40];
  42960. this.keysLeft = [37];
  42961. this.keysRight = [39];
  42962. }
  42963. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42964. var _this = this;
  42965. if (this._onCanvasBlurObserver) {
  42966. return;
  42967. }
  42968. this._scene = this.camera.getScene();
  42969. this._engine = this._scene.getEngine();
  42970. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42971. _this._keys = [];
  42972. });
  42973. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42974. var evt = info.event;
  42975. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42976. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42977. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42978. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42979. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42980. var index = _this._keys.indexOf(evt.keyCode);
  42981. if (index === -1) {
  42982. _this._keys.push(evt.keyCode);
  42983. }
  42984. if (!noPreventDefault) {
  42985. evt.preventDefault();
  42986. }
  42987. }
  42988. }
  42989. else {
  42990. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42991. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42992. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42993. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42994. var index = _this._keys.indexOf(evt.keyCode);
  42995. if (index >= 0) {
  42996. _this._keys.splice(index, 1);
  42997. }
  42998. if (!noPreventDefault) {
  42999. evt.preventDefault();
  43000. }
  43001. }
  43002. }
  43003. });
  43004. };
  43005. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43006. if (this._scene) {
  43007. if (this._onKeyboardObserver) {
  43008. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43009. }
  43010. if (this._onCanvasBlurObserver) {
  43011. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43012. }
  43013. this._onKeyboardObserver = null;
  43014. this._onCanvasBlurObserver = null;
  43015. }
  43016. this._keys = [];
  43017. };
  43018. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43019. if (this._onKeyboardObserver) {
  43020. var camera = this.camera;
  43021. // Keyboard
  43022. for (var index = 0; index < this._keys.length; index++) {
  43023. var keyCode = this._keys[index];
  43024. var speed = camera._computeLocalCameraSpeed();
  43025. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43026. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43027. }
  43028. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43029. camera._localDirection.copyFromFloats(0, 0, speed);
  43030. }
  43031. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43032. camera._localDirection.copyFromFloats(speed, 0, 0);
  43033. }
  43034. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43035. camera._localDirection.copyFromFloats(0, 0, -speed);
  43036. }
  43037. if (camera.getScene().useRightHandedSystem) {
  43038. camera._localDirection.z *= -1;
  43039. }
  43040. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43041. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43042. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43043. }
  43044. }
  43045. };
  43046. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43047. return "FreeCameraKeyboardMoveInput";
  43048. };
  43049. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43050. this._keys = [];
  43051. };
  43052. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43053. return "keyboard";
  43054. };
  43055. __decorate([
  43056. BABYLON.serialize()
  43057. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43058. __decorate([
  43059. BABYLON.serialize()
  43060. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43061. __decorate([
  43062. BABYLON.serialize()
  43063. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43064. __decorate([
  43065. BABYLON.serialize()
  43066. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43067. return FreeCameraKeyboardMoveInput;
  43068. }());
  43069. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43070. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43071. })(BABYLON || (BABYLON = {}));
  43072. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43073. var BABYLON;
  43074. (function (BABYLON) {
  43075. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43076. __extends(FreeCameraInputsManager, _super);
  43077. function FreeCameraInputsManager(camera) {
  43078. return _super.call(this, camera) || this;
  43079. }
  43080. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43081. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43082. return this;
  43083. };
  43084. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43085. if (touchEnabled === void 0) { touchEnabled = true; }
  43086. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43087. return this;
  43088. };
  43089. FreeCameraInputsManager.prototype.addGamepad = function () {
  43090. this.add(new BABYLON.FreeCameraGamepadInput());
  43091. return this;
  43092. };
  43093. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43094. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43095. return this;
  43096. };
  43097. FreeCameraInputsManager.prototype.addTouch = function () {
  43098. this.add(new BABYLON.FreeCameraTouchInput());
  43099. return this;
  43100. };
  43101. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43102. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43103. return this;
  43104. };
  43105. return FreeCameraInputsManager;
  43106. }(BABYLON.CameraInputsManager));
  43107. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43108. })(BABYLON || (BABYLON = {}));
  43109. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43110. var BABYLON;
  43111. (function (BABYLON) {
  43112. var FreeCamera = /** @class */ (function (_super) {
  43113. __extends(FreeCamera, _super);
  43114. function FreeCamera(name, position, scene) {
  43115. var _this = _super.call(this, name, position, scene) || this;
  43116. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43117. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43118. _this.checkCollisions = false;
  43119. _this.applyGravity = false;
  43120. _this._needMoveForGravity = false;
  43121. _this._oldPosition = BABYLON.Vector3.Zero();
  43122. _this._diffPosition = BABYLON.Vector3.Zero();
  43123. _this._newPosition = BABYLON.Vector3.Zero();
  43124. // Collisions
  43125. _this._collisionMask = -1;
  43126. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43127. if (collidedMesh === void 0) { collidedMesh = null; }
  43128. //TODO move this to the collision coordinator!
  43129. if (_this.getScene().workerCollisions)
  43130. newPosition.multiplyInPlace(_this._collider._radius);
  43131. var updatePosition = function (newPos) {
  43132. _this._newPosition.copyFrom(newPos);
  43133. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43134. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43135. _this.position.addInPlace(_this._diffPosition);
  43136. if (_this.onCollide && collidedMesh) {
  43137. _this.onCollide(collidedMesh);
  43138. }
  43139. }
  43140. };
  43141. updatePosition(newPosition);
  43142. };
  43143. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43144. _this.inputs.addKeyboard().addMouse();
  43145. return _this;
  43146. }
  43147. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43148. //-- begin properties for backward compatibility for inputs
  43149. /**
  43150. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43151. * Higher values reduce sensitivity.
  43152. */
  43153. get: function () {
  43154. var mouse = this.inputs.attached["mouse"];
  43155. if (mouse)
  43156. return mouse.angularSensibility;
  43157. return 0;
  43158. },
  43159. /**
  43160. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43161. * Higher values reduce sensitivity.
  43162. */
  43163. set: function (value) {
  43164. var mouse = this.inputs.attached["mouse"];
  43165. if (mouse)
  43166. mouse.angularSensibility = value;
  43167. },
  43168. enumerable: true,
  43169. configurable: true
  43170. });
  43171. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43172. get: function () {
  43173. var keyboard = this.inputs.attached["keyboard"];
  43174. if (keyboard)
  43175. return keyboard.keysUp;
  43176. return [];
  43177. },
  43178. set: function (value) {
  43179. var keyboard = this.inputs.attached["keyboard"];
  43180. if (keyboard)
  43181. keyboard.keysUp = value;
  43182. },
  43183. enumerable: true,
  43184. configurable: true
  43185. });
  43186. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43187. get: function () {
  43188. var keyboard = this.inputs.attached["keyboard"];
  43189. if (keyboard)
  43190. return keyboard.keysDown;
  43191. return [];
  43192. },
  43193. set: function (value) {
  43194. var keyboard = this.inputs.attached["keyboard"];
  43195. if (keyboard)
  43196. keyboard.keysDown = value;
  43197. },
  43198. enumerable: true,
  43199. configurable: true
  43200. });
  43201. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43202. get: function () {
  43203. var keyboard = this.inputs.attached["keyboard"];
  43204. if (keyboard)
  43205. return keyboard.keysLeft;
  43206. return [];
  43207. },
  43208. set: function (value) {
  43209. var keyboard = this.inputs.attached["keyboard"];
  43210. if (keyboard)
  43211. keyboard.keysLeft = value;
  43212. },
  43213. enumerable: true,
  43214. configurable: true
  43215. });
  43216. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43217. get: function () {
  43218. var keyboard = this.inputs.attached["keyboard"];
  43219. if (keyboard)
  43220. return keyboard.keysRight;
  43221. return [];
  43222. },
  43223. set: function (value) {
  43224. var keyboard = this.inputs.attached["keyboard"];
  43225. if (keyboard)
  43226. keyboard.keysRight = value;
  43227. },
  43228. enumerable: true,
  43229. configurable: true
  43230. });
  43231. // Controls
  43232. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43233. this.inputs.attachElement(element, noPreventDefault);
  43234. };
  43235. FreeCamera.prototype.detachControl = function (element) {
  43236. this.inputs.detachElement(element);
  43237. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43238. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43239. };
  43240. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43241. get: function () {
  43242. return this._collisionMask;
  43243. },
  43244. set: function (mask) {
  43245. this._collisionMask = !isNaN(mask) ? mask : -1;
  43246. },
  43247. enumerable: true,
  43248. configurable: true
  43249. });
  43250. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43251. var globalPosition;
  43252. if (this.parent) {
  43253. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43254. }
  43255. else {
  43256. globalPosition = this.position;
  43257. }
  43258. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43259. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43260. if (!this._collider) {
  43261. this._collider = new BABYLON.Collider();
  43262. }
  43263. this._collider._radius = this.ellipsoid;
  43264. this._collider.collisionMask = this._collisionMask;
  43265. //no need for clone, as long as gravity is not on.
  43266. var actualDisplacement = displacement;
  43267. //add gravity to the direction to prevent the dual-collision checking
  43268. if (this.applyGravity) {
  43269. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43270. actualDisplacement = displacement.add(this.getScene().gravity);
  43271. }
  43272. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43273. };
  43274. FreeCamera.prototype._checkInputs = function () {
  43275. if (!this._localDirection) {
  43276. this._localDirection = BABYLON.Vector3.Zero();
  43277. this._transformedDirection = BABYLON.Vector3.Zero();
  43278. }
  43279. this.inputs.checkInputs();
  43280. _super.prototype._checkInputs.call(this);
  43281. };
  43282. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43283. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43284. };
  43285. FreeCamera.prototype._updatePosition = function () {
  43286. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43287. this._collideWithWorld(this.cameraDirection);
  43288. }
  43289. else {
  43290. _super.prototype._updatePosition.call(this);
  43291. }
  43292. };
  43293. FreeCamera.prototype.dispose = function () {
  43294. this.inputs.clear();
  43295. _super.prototype.dispose.call(this);
  43296. };
  43297. FreeCamera.prototype.getClassName = function () {
  43298. return "FreeCamera";
  43299. };
  43300. __decorate([
  43301. BABYLON.serializeAsVector3()
  43302. ], FreeCamera.prototype, "ellipsoid", void 0);
  43303. __decorate([
  43304. BABYLON.serializeAsVector3()
  43305. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43306. __decorate([
  43307. BABYLON.serialize()
  43308. ], FreeCamera.prototype, "checkCollisions", void 0);
  43309. __decorate([
  43310. BABYLON.serialize()
  43311. ], FreeCamera.prototype, "applyGravity", void 0);
  43312. return FreeCamera;
  43313. }(BABYLON.TargetCamera));
  43314. BABYLON.FreeCamera = FreeCamera;
  43315. })(BABYLON || (BABYLON = {}));
  43316. //# sourceMappingURL=babylon.freeCamera.js.map
  43317. var BABYLON;
  43318. (function (BABYLON) {
  43319. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43320. function ArcRotateCameraKeyboardMoveInput() {
  43321. this._keys = new Array();
  43322. this.keysUp = [38];
  43323. this.keysDown = [40];
  43324. this.keysLeft = [37];
  43325. this.keysRight = [39];
  43326. this.keysReset = [220];
  43327. this.panningSensibility = 50.0;
  43328. this.zoomingSensibility = 25.0;
  43329. this.useAltToZoom = true;
  43330. }
  43331. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43332. var _this = this;
  43333. if (this._onCanvasBlurObserver) {
  43334. return;
  43335. }
  43336. this._scene = this.camera.getScene();
  43337. this._engine = this._scene.getEngine();
  43338. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43339. _this._keys = [];
  43340. });
  43341. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43342. var evt = info.event;
  43343. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43344. _this._ctrlPressed = evt.ctrlKey;
  43345. _this._altPressed = evt.altKey;
  43346. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43347. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43348. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43349. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43350. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43351. var index = _this._keys.indexOf(evt.keyCode);
  43352. if (index === -1) {
  43353. _this._keys.push(evt.keyCode);
  43354. }
  43355. if (evt.preventDefault) {
  43356. if (!noPreventDefault) {
  43357. evt.preventDefault();
  43358. }
  43359. }
  43360. }
  43361. }
  43362. else {
  43363. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43364. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43365. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43366. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43367. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43368. var index = _this._keys.indexOf(evt.keyCode);
  43369. if (index >= 0) {
  43370. _this._keys.splice(index, 1);
  43371. }
  43372. if (evt.preventDefault) {
  43373. if (!noPreventDefault) {
  43374. evt.preventDefault();
  43375. }
  43376. }
  43377. }
  43378. }
  43379. });
  43380. };
  43381. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43382. if (this._scene) {
  43383. if (this._onKeyboardObserver) {
  43384. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43385. }
  43386. if (this._onCanvasBlurObserver) {
  43387. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43388. }
  43389. this._onKeyboardObserver = null;
  43390. this._onCanvasBlurObserver = null;
  43391. }
  43392. this._keys = [];
  43393. };
  43394. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43395. if (this._onKeyboardObserver) {
  43396. var camera = this.camera;
  43397. for (var index = 0; index < this._keys.length; index++) {
  43398. var keyCode = this._keys[index];
  43399. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43400. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43401. camera.inertialPanningX -= 1 / this.panningSensibility;
  43402. }
  43403. else {
  43404. camera.inertialAlphaOffset -= 0.01;
  43405. }
  43406. }
  43407. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43408. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43409. camera.inertialPanningY += 1 / this.panningSensibility;
  43410. }
  43411. else if (this._altPressed && this.useAltToZoom) {
  43412. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43413. }
  43414. else {
  43415. camera.inertialBetaOffset -= 0.01;
  43416. }
  43417. }
  43418. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43419. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43420. camera.inertialPanningX += 1 / this.panningSensibility;
  43421. }
  43422. else {
  43423. camera.inertialAlphaOffset += 0.01;
  43424. }
  43425. }
  43426. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43427. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43428. camera.inertialPanningY -= 1 / this.panningSensibility;
  43429. }
  43430. else if (this._altPressed && this.useAltToZoom) {
  43431. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43432. }
  43433. else {
  43434. camera.inertialBetaOffset += 0.01;
  43435. }
  43436. }
  43437. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43438. camera.restoreState();
  43439. }
  43440. }
  43441. }
  43442. };
  43443. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43444. return "ArcRotateCameraKeyboardMoveInput";
  43445. };
  43446. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43447. return "keyboard";
  43448. };
  43449. __decorate([
  43450. BABYLON.serialize()
  43451. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43452. __decorate([
  43453. BABYLON.serialize()
  43454. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43455. __decorate([
  43456. BABYLON.serialize()
  43457. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43458. __decorate([
  43459. BABYLON.serialize()
  43460. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43461. __decorate([
  43462. BABYLON.serialize()
  43463. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43464. __decorate([
  43465. BABYLON.serialize()
  43466. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43467. __decorate([
  43468. BABYLON.serialize()
  43469. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43470. __decorate([
  43471. BABYLON.serialize()
  43472. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43473. return ArcRotateCameraKeyboardMoveInput;
  43474. }());
  43475. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43476. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43477. })(BABYLON || (BABYLON = {}));
  43478. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43479. var BABYLON;
  43480. (function (BABYLON) {
  43481. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43482. function ArcRotateCameraMouseWheelInput() {
  43483. this.wheelPrecision = 3.0;
  43484. /**
  43485. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43486. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43487. */
  43488. this.wheelDeltaPercentage = 0;
  43489. }
  43490. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43491. var _this = this;
  43492. this._wheel = function (p, s) {
  43493. //sanity check - this should be a PointerWheel event.
  43494. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43495. return;
  43496. var event = p.event;
  43497. var delta = 0;
  43498. if (event.wheelDelta) {
  43499. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43500. }
  43501. else if (event.detail) {
  43502. delta = -event.detail / _this.wheelPrecision;
  43503. }
  43504. if (delta)
  43505. _this.camera.inertialRadiusOffset += delta;
  43506. if (event.preventDefault) {
  43507. if (!noPreventDefault) {
  43508. event.preventDefault();
  43509. }
  43510. }
  43511. };
  43512. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43513. };
  43514. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43515. if (this._observer && element) {
  43516. this.camera.getScene().onPointerObservable.remove(this._observer);
  43517. this._observer = null;
  43518. this._wheel = null;
  43519. }
  43520. };
  43521. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43522. return "ArcRotateCameraMouseWheelInput";
  43523. };
  43524. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43525. return "mousewheel";
  43526. };
  43527. __decorate([
  43528. BABYLON.serialize()
  43529. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43530. __decorate([
  43531. BABYLON.serialize()
  43532. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43533. return ArcRotateCameraMouseWheelInput;
  43534. }());
  43535. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43536. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43537. })(BABYLON || (BABYLON = {}));
  43538. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43539. var BABYLON;
  43540. (function (BABYLON) {
  43541. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43542. function ArcRotateCameraPointersInput() {
  43543. this.buttons = [0, 1, 2];
  43544. this.angularSensibilityX = 1000.0;
  43545. this.angularSensibilityY = 1000.0;
  43546. this.pinchPrecision = 12.0;
  43547. /**
  43548. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43549. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43550. */
  43551. this.pinchDeltaPercentage = 0;
  43552. this.panningSensibility = 1000.0;
  43553. this.multiTouchPanning = true;
  43554. this.multiTouchPanAndZoom = true;
  43555. this._isPanClick = false;
  43556. this.pinchInwards = true;
  43557. }
  43558. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43559. var _this = this;
  43560. var engine = this.camera.getEngine();
  43561. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43562. var pointA = null;
  43563. var pointB = null;
  43564. var previousPinchSquaredDistance = 0;
  43565. var initialDistance = 0;
  43566. var twoFingerActivityCount = 0;
  43567. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43568. this._pointerInput = function (p, s) {
  43569. var evt = p.event;
  43570. var isTouch = p.event.pointerType === "touch";
  43571. if (engine.isInVRExclusivePointerMode) {
  43572. return;
  43573. }
  43574. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43575. return;
  43576. }
  43577. var srcElement = (evt.srcElement || evt.target);
  43578. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43579. try {
  43580. srcElement.setPointerCapture(evt.pointerId);
  43581. }
  43582. catch (e) {
  43583. //Nothing to do with the error. Execution will continue.
  43584. }
  43585. // Manage panning with pan button click
  43586. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43587. // manage pointers
  43588. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43589. if (pointA === null) {
  43590. pointA = cacheSoloPointer;
  43591. }
  43592. else if (pointB === null) {
  43593. pointB = cacheSoloPointer;
  43594. }
  43595. if (!noPreventDefault) {
  43596. evt.preventDefault();
  43597. element.focus();
  43598. }
  43599. }
  43600. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43601. _this.camera.restoreState();
  43602. }
  43603. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43604. try {
  43605. srcElement.releasePointerCapture(evt.pointerId);
  43606. }
  43607. catch (e) {
  43608. //Nothing to do with the error.
  43609. }
  43610. cacheSoloPointer = null;
  43611. previousPinchSquaredDistance = 0;
  43612. previousMultiTouchPanPosition.isPaning = false;
  43613. previousMultiTouchPanPosition.isPinching = false;
  43614. twoFingerActivityCount = 0;
  43615. initialDistance = 0;
  43616. if (!isTouch) {
  43617. pointB = null; // Mouse and pen are mono pointer
  43618. }
  43619. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43620. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43621. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43622. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43623. if (engine.badOS) {
  43624. pointA = pointB = null;
  43625. }
  43626. else {
  43627. //only remove the impacted pointer in case of multitouch allowing on most
  43628. //platforms switching from rotate to zoom and pan seamlessly.
  43629. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43630. pointA = pointB;
  43631. pointB = null;
  43632. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43633. }
  43634. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43635. pointB = null;
  43636. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43637. }
  43638. else {
  43639. pointA = pointB = null;
  43640. }
  43641. }
  43642. if (!noPreventDefault) {
  43643. evt.preventDefault();
  43644. }
  43645. }
  43646. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43647. if (!noPreventDefault) {
  43648. evt.preventDefault();
  43649. }
  43650. // One button down
  43651. if (pointA && pointB === null && cacheSoloPointer) {
  43652. if (_this.panningSensibility !== 0 &&
  43653. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43654. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43655. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43656. }
  43657. else {
  43658. var offsetX = evt.clientX - cacheSoloPointer.x;
  43659. var offsetY = evt.clientY - cacheSoloPointer.y;
  43660. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43661. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43662. }
  43663. cacheSoloPointer.x = evt.clientX;
  43664. cacheSoloPointer.y = evt.clientY;
  43665. }
  43666. else if (pointA && pointB) {
  43667. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43668. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43669. ed.x = evt.clientX;
  43670. ed.y = evt.clientY;
  43671. var direction = _this.pinchInwards ? 1 : -1;
  43672. var distX = pointA.x - pointB.x;
  43673. var distY = pointA.y - pointB.y;
  43674. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43675. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43676. if (previousPinchSquaredDistance === 0) {
  43677. initialDistance = pinchDistance;
  43678. previousPinchSquaredDistance = pinchSquaredDistance;
  43679. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43680. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43681. return;
  43682. }
  43683. if (_this.multiTouchPanAndZoom) {
  43684. if (_this.pinchDeltaPercentage) {
  43685. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43686. }
  43687. else {
  43688. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43689. (_this.pinchPrecision *
  43690. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43691. direction);
  43692. }
  43693. if (_this.panningSensibility !== 0) {
  43694. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43695. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43696. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43697. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43698. previousMultiTouchPanPosition.x = pointersCenterX;
  43699. previousMultiTouchPanPosition.y = pointersCenterY;
  43700. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43701. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43702. }
  43703. }
  43704. else {
  43705. twoFingerActivityCount++;
  43706. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43707. if (_this.pinchDeltaPercentage) {
  43708. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43709. }
  43710. else {
  43711. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43712. (_this.pinchPrecision *
  43713. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43714. direction);
  43715. }
  43716. previousMultiTouchPanPosition.isPaning = false;
  43717. previousMultiTouchPanPosition.isPinching = true;
  43718. }
  43719. else {
  43720. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43721. if (!previousMultiTouchPanPosition.isPaning) {
  43722. previousMultiTouchPanPosition.isPaning = true;
  43723. previousMultiTouchPanPosition.isPinching = false;
  43724. previousMultiTouchPanPosition.x = ed.x;
  43725. previousMultiTouchPanPosition.y = ed.y;
  43726. return;
  43727. }
  43728. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43729. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43730. }
  43731. }
  43732. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43733. previousMultiTouchPanPosition.x = ed.x;
  43734. previousMultiTouchPanPosition.y = ed.y;
  43735. }
  43736. }
  43737. previousPinchSquaredDistance = pinchSquaredDistance;
  43738. }
  43739. }
  43740. };
  43741. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43742. this._onContextMenu = function (evt) {
  43743. evt.preventDefault();
  43744. };
  43745. if (!this.camera._useCtrlForPanning) {
  43746. element.addEventListener("contextmenu", this._onContextMenu, false);
  43747. }
  43748. this._onLostFocus = function () {
  43749. //this._keys = [];
  43750. pointA = pointB = null;
  43751. previousPinchSquaredDistance = 0;
  43752. previousMultiTouchPanPosition.isPaning = false;
  43753. previousMultiTouchPanPosition.isPinching = false;
  43754. twoFingerActivityCount = 0;
  43755. cacheSoloPointer = null;
  43756. initialDistance = 0;
  43757. };
  43758. this._onMouseMove = function (evt) {
  43759. if (!engine.isPointerLock) {
  43760. return;
  43761. }
  43762. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43763. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43764. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43765. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43766. if (!noPreventDefault) {
  43767. evt.preventDefault();
  43768. }
  43769. };
  43770. this._onGestureStart = function (e) {
  43771. if (window.MSGesture === undefined) {
  43772. return;
  43773. }
  43774. if (!_this._MSGestureHandler) {
  43775. _this._MSGestureHandler = new MSGesture();
  43776. _this._MSGestureHandler.target = element;
  43777. }
  43778. _this._MSGestureHandler.addPointer(e.pointerId);
  43779. };
  43780. this._onGesture = function (e) {
  43781. _this.camera.radius *= e.scale;
  43782. if (e.preventDefault) {
  43783. if (!noPreventDefault) {
  43784. e.stopPropagation();
  43785. e.preventDefault();
  43786. }
  43787. }
  43788. };
  43789. element.addEventListener("mousemove", this._onMouseMove, false);
  43790. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43791. element.addEventListener("MSGestureChange", this._onGesture, false);
  43792. BABYLON.Tools.RegisterTopRootEvents([
  43793. { name: "blur", handler: this._onLostFocus }
  43794. ]);
  43795. };
  43796. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43797. if (this._onLostFocus) {
  43798. BABYLON.Tools.UnregisterTopRootEvents([
  43799. { name: "blur", handler: this._onLostFocus }
  43800. ]);
  43801. }
  43802. if (element && this._observer) {
  43803. this.camera.getScene().onPointerObservable.remove(this._observer);
  43804. this._observer = null;
  43805. if (this._onContextMenu) {
  43806. element.removeEventListener("contextmenu", this._onContextMenu);
  43807. }
  43808. if (this._onMouseMove) {
  43809. element.removeEventListener("mousemove", this._onMouseMove);
  43810. }
  43811. if (this._onGestureStart) {
  43812. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43813. }
  43814. if (this._onGesture) {
  43815. element.removeEventListener("MSGestureChange", this._onGesture);
  43816. }
  43817. this._isPanClick = false;
  43818. this.pinchInwards = true;
  43819. this._onMouseMove = null;
  43820. this._onGestureStart = null;
  43821. this._onGesture = null;
  43822. this._MSGestureHandler = null;
  43823. this._onLostFocus = null;
  43824. this._onContextMenu = null;
  43825. }
  43826. };
  43827. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43828. return "ArcRotateCameraPointersInput";
  43829. };
  43830. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43831. return "pointers";
  43832. };
  43833. __decorate([
  43834. BABYLON.serialize()
  43835. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43836. __decorate([
  43837. BABYLON.serialize()
  43838. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43839. __decorate([
  43840. BABYLON.serialize()
  43841. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43842. __decorate([
  43843. BABYLON.serialize()
  43844. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43845. __decorate([
  43846. BABYLON.serialize()
  43847. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43848. __decorate([
  43849. BABYLON.serialize()
  43850. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43851. __decorate([
  43852. BABYLON.serialize()
  43853. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43854. __decorate([
  43855. BABYLON.serialize()
  43856. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43857. return ArcRotateCameraPointersInput;
  43858. }());
  43859. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43860. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43861. })(BABYLON || (BABYLON = {}));
  43862. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43863. var BABYLON;
  43864. (function (BABYLON) {
  43865. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43866. __extends(ArcRotateCameraInputsManager, _super);
  43867. function ArcRotateCameraInputsManager(camera) {
  43868. return _super.call(this, camera) || this;
  43869. }
  43870. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43871. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43872. return this;
  43873. };
  43874. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43875. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43876. return this;
  43877. };
  43878. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43879. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43880. return this;
  43881. };
  43882. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43883. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43884. return this;
  43885. };
  43886. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43887. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43888. return this;
  43889. };
  43890. return ArcRotateCameraInputsManager;
  43891. }(BABYLON.CameraInputsManager));
  43892. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43893. })(BABYLON || (BABYLON = {}));
  43894. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43895. var BABYLON;
  43896. (function (BABYLON) {
  43897. var ArcRotateCamera = /** @class */ (function (_super) {
  43898. __extends(ArcRotateCamera, _super);
  43899. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43900. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43901. _this.inertialAlphaOffset = 0;
  43902. _this.inertialBetaOffset = 0;
  43903. _this.inertialRadiusOffset = 0;
  43904. _this.lowerAlphaLimit = null;
  43905. _this.upperAlphaLimit = null;
  43906. _this.lowerBetaLimit = 0.01;
  43907. _this.upperBetaLimit = Math.PI;
  43908. _this.lowerRadiusLimit = null;
  43909. _this.upperRadiusLimit = null;
  43910. _this.inertialPanningX = 0;
  43911. _this.inertialPanningY = 0;
  43912. _this.pinchToPanMaxDistance = 20;
  43913. _this.panningDistanceLimit = null;
  43914. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43915. _this.panningInertia = 0.9;
  43916. //-- end properties for backward compatibility for inputs
  43917. _this.zoomOnFactor = 1;
  43918. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43919. _this.allowUpsideDown = true;
  43920. _this._viewMatrix = new BABYLON.Matrix();
  43921. // Panning
  43922. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43923. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43924. _this.checkCollisions = false;
  43925. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43926. _this._previousPosition = BABYLON.Vector3.Zero();
  43927. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43928. _this._newPosition = BABYLON.Vector3.Zero();
  43929. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43930. if (collidedMesh === void 0) { collidedMesh = null; }
  43931. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43932. newPosition.multiplyInPlace(_this._collider._radius);
  43933. }
  43934. if (!collidedMesh) {
  43935. _this._previousPosition.copyFrom(_this.position);
  43936. }
  43937. else {
  43938. _this.setPosition(newPosition);
  43939. if (_this.onCollide) {
  43940. _this.onCollide(collidedMesh);
  43941. }
  43942. }
  43943. // Recompute because of constraints
  43944. var cosa = Math.cos(_this.alpha);
  43945. var sina = Math.sin(_this.alpha);
  43946. var cosb = Math.cos(_this.beta);
  43947. var sinb = Math.sin(_this.beta);
  43948. if (sinb === 0) {
  43949. sinb = 0.0001;
  43950. }
  43951. var target = _this._getTargetPosition();
  43952. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43953. _this.position.copyFrom(_this._newPosition);
  43954. var up = _this.upVector;
  43955. if (_this.allowUpsideDown && _this.beta < 0) {
  43956. up = up.clone();
  43957. up = up.negate();
  43958. }
  43959. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43960. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43961. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43962. _this._collisionTriggered = false;
  43963. };
  43964. _this._target = BABYLON.Vector3.Zero();
  43965. if (target) {
  43966. _this.setTarget(target);
  43967. }
  43968. _this.alpha = alpha;
  43969. _this.beta = beta;
  43970. _this.radius = radius;
  43971. _this.getViewMatrix();
  43972. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43973. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43974. return _this;
  43975. }
  43976. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43977. get: function () {
  43978. return this._target;
  43979. },
  43980. set: function (value) {
  43981. this.setTarget(value);
  43982. },
  43983. enumerable: true,
  43984. configurable: true
  43985. });
  43986. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43987. //-- begin properties for backward compatibility for inputs
  43988. get: function () {
  43989. var pointers = this.inputs.attached["pointers"];
  43990. if (pointers)
  43991. return pointers.angularSensibilityX;
  43992. return 0;
  43993. },
  43994. set: function (value) {
  43995. var pointers = this.inputs.attached["pointers"];
  43996. if (pointers) {
  43997. pointers.angularSensibilityX = value;
  43998. }
  43999. },
  44000. enumerable: true,
  44001. configurable: true
  44002. });
  44003. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44004. get: function () {
  44005. var pointers = this.inputs.attached["pointers"];
  44006. if (pointers)
  44007. return pointers.angularSensibilityY;
  44008. return 0;
  44009. },
  44010. set: function (value) {
  44011. var pointers = this.inputs.attached["pointers"];
  44012. if (pointers) {
  44013. pointers.angularSensibilityY = value;
  44014. }
  44015. },
  44016. enumerable: true,
  44017. configurable: true
  44018. });
  44019. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44020. get: function () {
  44021. var pointers = this.inputs.attached["pointers"];
  44022. if (pointers)
  44023. return pointers.pinchPrecision;
  44024. return 0;
  44025. },
  44026. set: function (value) {
  44027. var pointers = this.inputs.attached["pointers"];
  44028. if (pointers) {
  44029. pointers.pinchPrecision = value;
  44030. }
  44031. },
  44032. enumerable: true,
  44033. configurable: true
  44034. });
  44035. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44036. get: function () {
  44037. var pointers = this.inputs.attached["pointers"];
  44038. if (pointers)
  44039. return pointers.pinchDeltaPercentage;
  44040. return 0;
  44041. },
  44042. set: function (value) {
  44043. var pointers = this.inputs.attached["pointers"];
  44044. if (pointers) {
  44045. pointers.pinchDeltaPercentage = value;
  44046. }
  44047. },
  44048. enumerable: true,
  44049. configurable: true
  44050. });
  44051. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44052. get: function () {
  44053. var pointers = this.inputs.attached["pointers"];
  44054. if (pointers)
  44055. return pointers.panningSensibility;
  44056. return 0;
  44057. },
  44058. set: function (value) {
  44059. var pointers = this.inputs.attached["pointers"];
  44060. if (pointers) {
  44061. pointers.panningSensibility = value;
  44062. }
  44063. },
  44064. enumerable: true,
  44065. configurable: true
  44066. });
  44067. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44068. get: function () {
  44069. var keyboard = this.inputs.attached["keyboard"];
  44070. if (keyboard)
  44071. return keyboard.keysUp;
  44072. return [];
  44073. },
  44074. set: function (value) {
  44075. var keyboard = this.inputs.attached["keyboard"];
  44076. if (keyboard)
  44077. keyboard.keysUp = value;
  44078. },
  44079. enumerable: true,
  44080. configurable: true
  44081. });
  44082. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44083. get: function () {
  44084. var keyboard = this.inputs.attached["keyboard"];
  44085. if (keyboard)
  44086. return keyboard.keysDown;
  44087. return [];
  44088. },
  44089. set: function (value) {
  44090. var keyboard = this.inputs.attached["keyboard"];
  44091. if (keyboard)
  44092. keyboard.keysDown = value;
  44093. },
  44094. enumerable: true,
  44095. configurable: true
  44096. });
  44097. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44098. get: function () {
  44099. var keyboard = this.inputs.attached["keyboard"];
  44100. if (keyboard)
  44101. return keyboard.keysLeft;
  44102. return [];
  44103. },
  44104. set: function (value) {
  44105. var keyboard = this.inputs.attached["keyboard"];
  44106. if (keyboard)
  44107. keyboard.keysLeft = value;
  44108. },
  44109. enumerable: true,
  44110. configurable: true
  44111. });
  44112. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44113. get: function () {
  44114. var keyboard = this.inputs.attached["keyboard"];
  44115. if (keyboard)
  44116. return keyboard.keysRight;
  44117. return [];
  44118. },
  44119. set: function (value) {
  44120. var keyboard = this.inputs.attached["keyboard"];
  44121. if (keyboard)
  44122. keyboard.keysRight = value;
  44123. },
  44124. enumerable: true,
  44125. configurable: true
  44126. });
  44127. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44128. get: function () {
  44129. var mousewheel = this.inputs.attached["mousewheel"];
  44130. if (mousewheel)
  44131. return mousewheel.wheelPrecision;
  44132. return 0;
  44133. },
  44134. set: function (value) {
  44135. var mousewheel = this.inputs.attached["mousewheel"];
  44136. if (mousewheel)
  44137. mousewheel.wheelPrecision = value;
  44138. },
  44139. enumerable: true,
  44140. configurable: true
  44141. });
  44142. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44143. get: function () {
  44144. var mousewheel = this.inputs.attached["mousewheel"];
  44145. if (mousewheel)
  44146. return mousewheel.wheelDeltaPercentage;
  44147. return 0;
  44148. },
  44149. set: function (value) {
  44150. var mousewheel = this.inputs.attached["mousewheel"];
  44151. if (mousewheel)
  44152. mousewheel.wheelDeltaPercentage = value;
  44153. },
  44154. enumerable: true,
  44155. configurable: true
  44156. });
  44157. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44158. get: function () {
  44159. return this._bouncingBehavior;
  44160. },
  44161. enumerable: true,
  44162. configurable: true
  44163. });
  44164. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44165. get: function () {
  44166. return this._bouncingBehavior != null;
  44167. },
  44168. set: function (value) {
  44169. if (value === this.useBouncingBehavior) {
  44170. return;
  44171. }
  44172. if (value) {
  44173. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44174. this.addBehavior(this._bouncingBehavior);
  44175. }
  44176. else if (this._bouncingBehavior) {
  44177. this.removeBehavior(this._bouncingBehavior);
  44178. this._bouncingBehavior = null;
  44179. }
  44180. },
  44181. enumerable: true,
  44182. configurable: true
  44183. });
  44184. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44185. get: function () {
  44186. return this._framingBehavior;
  44187. },
  44188. enumerable: true,
  44189. configurable: true
  44190. });
  44191. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44192. get: function () {
  44193. return this._framingBehavior != null;
  44194. },
  44195. set: function (value) {
  44196. if (value === this.useFramingBehavior) {
  44197. return;
  44198. }
  44199. if (value) {
  44200. this._framingBehavior = new BABYLON.FramingBehavior();
  44201. this.addBehavior(this._framingBehavior);
  44202. }
  44203. else if (this._framingBehavior) {
  44204. this.removeBehavior(this._framingBehavior);
  44205. this._framingBehavior = null;
  44206. }
  44207. },
  44208. enumerable: true,
  44209. configurable: true
  44210. });
  44211. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44212. get: function () {
  44213. return this._autoRotationBehavior;
  44214. },
  44215. enumerable: true,
  44216. configurable: true
  44217. });
  44218. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44219. get: function () {
  44220. return this._autoRotationBehavior != null;
  44221. },
  44222. set: function (value) {
  44223. if (value === this.useAutoRotationBehavior) {
  44224. return;
  44225. }
  44226. if (value) {
  44227. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44228. this.addBehavior(this._autoRotationBehavior);
  44229. }
  44230. else if (this._autoRotationBehavior) {
  44231. this.removeBehavior(this._autoRotationBehavior);
  44232. this._autoRotationBehavior = null;
  44233. }
  44234. },
  44235. enumerable: true,
  44236. configurable: true
  44237. });
  44238. // Cache
  44239. ArcRotateCamera.prototype._initCache = function () {
  44240. _super.prototype._initCache.call(this);
  44241. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44242. this._cache.alpha = undefined;
  44243. this._cache.beta = undefined;
  44244. this._cache.radius = undefined;
  44245. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44246. };
  44247. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44248. if (!ignoreParentClass) {
  44249. _super.prototype._updateCache.call(this);
  44250. }
  44251. this._cache._target.copyFrom(this._getTargetPosition());
  44252. this._cache.alpha = this.alpha;
  44253. this._cache.beta = this.beta;
  44254. this._cache.radius = this.radius;
  44255. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44256. };
  44257. ArcRotateCamera.prototype._getTargetPosition = function () {
  44258. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44259. var pos = this._targetHost.getAbsolutePosition();
  44260. if (this._targetBoundingCenter) {
  44261. pos.addToRef(this._targetBoundingCenter, this._target);
  44262. }
  44263. else {
  44264. this._target.copyFrom(pos);
  44265. }
  44266. }
  44267. var lockedTargetPosition = this._getLockedTargetPosition();
  44268. if (lockedTargetPosition) {
  44269. return lockedTargetPosition;
  44270. }
  44271. return this._target;
  44272. };
  44273. ArcRotateCamera.prototype.storeState = function () {
  44274. this._storedAlpha = this.alpha;
  44275. this._storedBeta = this.beta;
  44276. this._storedRadius = this.radius;
  44277. this._storedTarget = this._getTargetPosition().clone();
  44278. return _super.prototype.storeState.call(this);
  44279. };
  44280. /**
  44281. * Restored camera state. You must call storeState() first
  44282. */
  44283. ArcRotateCamera.prototype._restoreStateValues = function () {
  44284. if (!_super.prototype._restoreStateValues.call(this)) {
  44285. return false;
  44286. }
  44287. this.alpha = this._storedAlpha;
  44288. this.beta = this._storedBeta;
  44289. this.radius = this._storedRadius;
  44290. this.setTarget(this._storedTarget.clone());
  44291. this.inertialAlphaOffset = 0;
  44292. this.inertialBetaOffset = 0;
  44293. this.inertialRadiusOffset = 0;
  44294. this.inertialPanningX = 0;
  44295. this.inertialPanningY = 0;
  44296. return true;
  44297. };
  44298. // Synchronized
  44299. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44300. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44301. return false;
  44302. return this._cache._target.equals(this._getTargetPosition())
  44303. && this._cache.alpha === this.alpha
  44304. && this._cache.beta === this.beta
  44305. && this._cache.radius === this.radius
  44306. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44307. };
  44308. // Methods
  44309. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44310. var _this = this;
  44311. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44312. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44313. this._useCtrlForPanning = useCtrlForPanning;
  44314. this._panningMouseButton = panningMouseButton;
  44315. this.inputs.attachElement(element, noPreventDefault);
  44316. this._reset = function () {
  44317. _this.inertialAlphaOffset = 0;
  44318. _this.inertialBetaOffset = 0;
  44319. _this.inertialRadiusOffset = 0;
  44320. _this.inertialPanningX = 0;
  44321. _this.inertialPanningY = 0;
  44322. };
  44323. };
  44324. ArcRotateCamera.prototype.detachControl = function (element) {
  44325. this.inputs.detachElement(element);
  44326. if (this._reset) {
  44327. this._reset();
  44328. }
  44329. };
  44330. ArcRotateCamera.prototype._checkInputs = function () {
  44331. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44332. if (this._collisionTriggered) {
  44333. return;
  44334. }
  44335. this.inputs.checkInputs();
  44336. // Inertia
  44337. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44338. if (this.getScene().useRightHandedSystem) {
  44339. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44340. }
  44341. else {
  44342. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44343. }
  44344. this.beta += this.inertialBetaOffset;
  44345. this.radius -= this.inertialRadiusOffset;
  44346. this.inertialAlphaOffset *= this.inertia;
  44347. this.inertialBetaOffset *= this.inertia;
  44348. this.inertialRadiusOffset *= this.inertia;
  44349. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44350. this.inertialAlphaOffset = 0;
  44351. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44352. this.inertialBetaOffset = 0;
  44353. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44354. this.inertialRadiusOffset = 0;
  44355. }
  44356. // Panning inertia
  44357. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44358. if (!this._localDirection) {
  44359. this._localDirection = BABYLON.Vector3.Zero();
  44360. this._transformedDirection = BABYLON.Vector3.Zero();
  44361. }
  44362. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44363. this._localDirection.multiplyInPlace(this.panningAxis);
  44364. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44365. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44366. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44367. if (!this.panningAxis.y) {
  44368. this._transformedDirection.y = 0;
  44369. }
  44370. if (!this._targetHost) {
  44371. if (this.panningDistanceLimit) {
  44372. this._transformedDirection.addInPlace(this._target);
  44373. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44374. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44375. this._target.copyFrom(this._transformedDirection);
  44376. }
  44377. }
  44378. else {
  44379. this._target.addInPlace(this._transformedDirection);
  44380. }
  44381. }
  44382. this.inertialPanningX *= this.panningInertia;
  44383. this.inertialPanningY *= this.panningInertia;
  44384. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44385. this.inertialPanningX = 0;
  44386. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44387. this.inertialPanningY = 0;
  44388. }
  44389. // Limits
  44390. this._checkLimits();
  44391. _super.prototype._checkInputs.call(this);
  44392. };
  44393. ArcRotateCamera.prototype._checkLimits = function () {
  44394. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44395. if (this.allowUpsideDown && this.beta > Math.PI) {
  44396. this.beta = this.beta - (2 * Math.PI);
  44397. }
  44398. }
  44399. else {
  44400. if (this.beta < this.lowerBetaLimit) {
  44401. this.beta = this.lowerBetaLimit;
  44402. }
  44403. }
  44404. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44405. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44406. this.beta = this.beta + (2 * Math.PI);
  44407. }
  44408. }
  44409. else {
  44410. if (this.beta > this.upperBetaLimit) {
  44411. this.beta = this.upperBetaLimit;
  44412. }
  44413. }
  44414. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44415. this.alpha = this.lowerAlphaLimit;
  44416. }
  44417. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44418. this.alpha = this.upperAlphaLimit;
  44419. }
  44420. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44421. this.radius = this.lowerRadiusLimit;
  44422. }
  44423. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44424. this.radius = this.upperRadiusLimit;
  44425. }
  44426. };
  44427. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44428. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44429. this.radius = radiusv3.length();
  44430. if (this.radius === 0) {
  44431. this.radius = 0.0001; // Just to avoid division by zero
  44432. }
  44433. // Alpha
  44434. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44435. if (radiusv3.z < 0) {
  44436. this.alpha = 2 * Math.PI - this.alpha;
  44437. }
  44438. // Beta
  44439. this.beta = Math.acos(radiusv3.y / this.radius);
  44440. this._checkLimits();
  44441. };
  44442. ArcRotateCamera.prototype.setPosition = function (position) {
  44443. if (this.position.equals(position)) {
  44444. return;
  44445. }
  44446. this.position.copyFrom(position);
  44447. this.rebuildAnglesAndRadius();
  44448. };
  44449. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44450. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44451. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44452. if (target.getBoundingInfo) {
  44453. if (toBoundingCenter) {
  44454. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44455. }
  44456. else {
  44457. this._targetBoundingCenter = null;
  44458. }
  44459. this._targetHost = target;
  44460. this._target = this._getTargetPosition();
  44461. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44462. }
  44463. else {
  44464. var newTarget = target;
  44465. var currentTarget = this._getTargetPosition();
  44466. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44467. return;
  44468. }
  44469. this._targetHost = null;
  44470. this._target = newTarget;
  44471. this._targetBoundingCenter = null;
  44472. this.onMeshTargetChangedObservable.notifyObservers(null);
  44473. }
  44474. this.rebuildAnglesAndRadius();
  44475. };
  44476. ArcRotateCamera.prototype._getViewMatrix = function () {
  44477. // Compute
  44478. var cosa = Math.cos(this.alpha);
  44479. var sina = Math.sin(this.alpha);
  44480. var cosb = Math.cos(this.beta);
  44481. var sinb = Math.sin(this.beta);
  44482. if (sinb === 0) {
  44483. sinb = 0.0001;
  44484. }
  44485. var target = this._getTargetPosition();
  44486. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44487. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44488. if (!this._collider) {
  44489. this._collider = new BABYLON.Collider();
  44490. }
  44491. this._collider._radius = this.collisionRadius;
  44492. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44493. this._collisionTriggered = true;
  44494. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44495. }
  44496. else {
  44497. this.position.copyFrom(this._newPosition);
  44498. var up = this.upVector;
  44499. if (this.allowUpsideDown && sinb < 0) {
  44500. up = up.clone();
  44501. up = up.negate();
  44502. }
  44503. if (this.getScene().useRightHandedSystem) {
  44504. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44505. }
  44506. else {
  44507. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44508. }
  44509. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44510. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44511. }
  44512. this._currentTarget = target;
  44513. return this._viewMatrix;
  44514. };
  44515. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44516. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44517. meshes = meshes || this.getScene().meshes;
  44518. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44519. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44520. this.radius = distance * this.zoomOnFactor;
  44521. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44522. };
  44523. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44524. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44525. var meshesOrMinMaxVector;
  44526. var distance;
  44527. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44528. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44529. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44530. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44531. }
  44532. else {
  44533. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44534. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44535. distance = minMaxVectorAndDistance.distance;
  44536. }
  44537. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44538. if (!doNotUpdateMaxZ) {
  44539. this.maxZ = distance * 2;
  44540. }
  44541. };
  44542. /**
  44543. * @override
  44544. * Override Camera.createRigCamera
  44545. */
  44546. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44547. var alphaShift = 0;
  44548. switch (this.cameraRigMode) {
  44549. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44550. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44551. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44552. case BABYLON.Camera.RIG_MODE_VR:
  44553. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44554. break;
  44555. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44556. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44557. break;
  44558. }
  44559. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44560. rigCam._cameraRigParams = {};
  44561. return rigCam;
  44562. };
  44563. /**
  44564. * @override
  44565. * Override Camera._updateRigCameras
  44566. */
  44567. ArcRotateCamera.prototype._updateRigCameras = function () {
  44568. var camLeft = this._rigCameras[0];
  44569. var camRight = this._rigCameras[1];
  44570. camLeft.beta = camRight.beta = this.beta;
  44571. camLeft.radius = camRight.radius = this.radius;
  44572. switch (this.cameraRigMode) {
  44573. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44574. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44575. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44576. case BABYLON.Camera.RIG_MODE_VR:
  44577. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44578. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44579. break;
  44580. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44581. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44582. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44583. break;
  44584. }
  44585. _super.prototype._updateRigCameras.call(this);
  44586. };
  44587. ArcRotateCamera.prototype.dispose = function () {
  44588. this.inputs.clear();
  44589. _super.prototype.dispose.call(this);
  44590. };
  44591. ArcRotateCamera.prototype.getClassName = function () {
  44592. return "ArcRotateCamera";
  44593. };
  44594. __decorate([
  44595. BABYLON.serialize()
  44596. ], ArcRotateCamera.prototype, "alpha", void 0);
  44597. __decorate([
  44598. BABYLON.serialize()
  44599. ], ArcRotateCamera.prototype, "beta", void 0);
  44600. __decorate([
  44601. BABYLON.serialize()
  44602. ], ArcRotateCamera.prototype, "radius", void 0);
  44603. __decorate([
  44604. BABYLON.serializeAsVector3("target")
  44605. ], ArcRotateCamera.prototype, "_target", void 0);
  44606. __decorate([
  44607. BABYLON.serialize()
  44608. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44609. __decorate([
  44610. BABYLON.serialize()
  44611. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44612. __decorate([
  44613. BABYLON.serialize()
  44614. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44615. __decorate([
  44616. BABYLON.serialize()
  44617. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44618. __decorate([
  44619. BABYLON.serialize()
  44620. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44621. __decorate([
  44622. BABYLON.serialize()
  44623. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44624. __decorate([
  44625. BABYLON.serialize()
  44626. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44627. __decorate([
  44628. BABYLON.serialize()
  44629. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44630. __decorate([
  44631. BABYLON.serialize()
  44632. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44633. __decorate([
  44634. BABYLON.serialize()
  44635. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44636. __decorate([
  44637. BABYLON.serialize()
  44638. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44639. __decorate([
  44640. BABYLON.serialize()
  44641. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44642. __decorate([
  44643. BABYLON.serialize()
  44644. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44645. __decorate([
  44646. BABYLON.serializeAsVector3()
  44647. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44648. __decorate([
  44649. BABYLON.serialize()
  44650. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44651. __decorate([
  44652. BABYLON.serialize()
  44653. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44654. __decorate([
  44655. BABYLON.serialize()
  44656. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44657. return ArcRotateCamera;
  44658. }(BABYLON.TargetCamera));
  44659. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44660. })(BABYLON || (BABYLON = {}));
  44661. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44662. var BABYLON;
  44663. (function (BABYLON) {
  44664. /**
  44665. * The HemisphericLight simulates the ambient environment light,
  44666. * so the passed direction is the light reflection direction, not the incoming direction.
  44667. */
  44668. var HemisphericLight = /** @class */ (function (_super) {
  44669. __extends(HemisphericLight, _super);
  44670. /**
  44671. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44672. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44673. * The HemisphericLight can't cast shadows.
  44674. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44675. * @param name The friendly name of the light
  44676. * @param direction The direction of the light reflection
  44677. * @param scene The scene the light belongs to
  44678. */
  44679. function HemisphericLight(name, direction, scene) {
  44680. var _this = _super.call(this, name, scene) || this;
  44681. /**
  44682. * The groundColor is the light in the opposite direction to the one specified during creation.
  44683. * 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.
  44684. */
  44685. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44686. _this.direction = direction || BABYLON.Vector3.Up();
  44687. return _this;
  44688. }
  44689. HemisphericLight.prototype._buildUniformLayout = function () {
  44690. this._uniformBuffer.addUniform("vLightData", 4);
  44691. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44692. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44693. this._uniformBuffer.addUniform("vLightGround", 3);
  44694. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44695. this._uniformBuffer.addUniform("depthValues", 2);
  44696. this._uniformBuffer.create();
  44697. };
  44698. /**
  44699. * Returns the string "HemisphericLight".
  44700. * @return The class name
  44701. */
  44702. HemisphericLight.prototype.getClassName = function () {
  44703. return "HemisphericLight";
  44704. };
  44705. /**
  44706. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44707. * Returns the updated direction.
  44708. * @param target The target the direction should point to
  44709. * @return The computed direction
  44710. */
  44711. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44712. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44713. return this.direction;
  44714. };
  44715. /**
  44716. * Returns the shadow generator associated to the light.
  44717. * @returns Always null for hemispheric lights because it does not support shadows.
  44718. */
  44719. HemisphericLight.prototype.getShadowGenerator = function () {
  44720. return null;
  44721. };
  44722. /**
  44723. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44724. * @param effect The effect to update
  44725. * @param lightIndex The index of the light in the effect to update
  44726. * @returns The hemispheric light
  44727. */
  44728. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44729. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44730. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44731. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44732. return this;
  44733. };
  44734. /**
  44735. * @ignore internal use only.
  44736. */
  44737. HemisphericLight.prototype._getWorldMatrix = function () {
  44738. if (!this._worldMatrix) {
  44739. this._worldMatrix = BABYLON.Matrix.Identity();
  44740. }
  44741. return this._worldMatrix;
  44742. };
  44743. /**
  44744. * Returns the integer 3.
  44745. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44746. */
  44747. HemisphericLight.prototype.getTypeID = function () {
  44748. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44749. };
  44750. __decorate([
  44751. BABYLON.serializeAsColor3()
  44752. ], HemisphericLight.prototype, "groundColor", void 0);
  44753. __decorate([
  44754. BABYLON.serializeAsVector3()
  44755. ], HemisphericLight.prototype, "direction", void 0);
  44756. return HemisphericLight;
  44757. }(BABYLON.Light));
  44758. BABYLON.HemisphericLight = HemisphericLight;
  44759. })(BABYLON || (BABYLON = {}));
  44760. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44761. var BABYLON;
  44762. (function (BABYLON) {
  44763. /**
  44764. * Base implementation of @see IShadowLight
  44765. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44766. */
  44767. var ShadowLight = /** @class */ (function (_super) {
  44768. __extends(ShadowLight, _super);
  44769. function ShadowLight() {
  44770. var _this = _super !== null && _super.apply(this, arguments) || this;
  44771. _this._needProjectionMatrixCompute = true;
  44772. return _this;
  44773. }
  44774. ShadowLight.prototype._setPosition = function (value) {
  44775. this._position = value;
  44776. };
  44777. Object.defineProperty(ShadowLight.prototype, "position", {
  44778. /**
  44779. * Sets the position the shadow will be casted from. Also use as the light position for both
  44780. * point and spot lights.
  44781. */
  44782. get: function () {
  44783. return this._position;
  44784. },
  44785. /**
  44786. * Sets the position the shadow will be casted from. Also use as the light position for both
  44787. * point and spot lights.
  44788. */
  44789. set: function (value) {
  44790. this._setPosition(value);
  44791. },
  44792. enumerable: true,
  44793. configurable: true
  44794. });
  44795. ShadowLight.prototype._setDirection = function (value) {
  44796. this._direction = value;
  44797. };
  44798. Object.defineProperty(ShadowLight.prototype, "direction", {
  44799. /**
  44800. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44801. * Also use as the light direction on spot and directional lights.
  44802. */
  44803. get: function () {
  44804. return this._direction;
  44805. },
  44806. /**
  44807. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44808. * Also use as the light direction on spot and directional lights.
  44809. */
  44810. set: function (value) {
  44811. this._setDirection(value);
  44812. },
  44813. enumerable: true,
  44814. configurable: true
  44815. });
  44816. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44817. /**
  44818. * Gets the shadow projection clipping minimum z value.
  44819. */
  44820. get: function () {
  44821. return this._shadowMinZ;
  44822. },
  44823. /**
  44824. * Sets the shadow projection clipping minimum z value.
  44825. */
  44826. set: function (value) {
  44827. this._shadowMinZ = value;
  44828. this.forceProjectionMatrixCompute();
  44829. },
  44830. enumerable: true,
  44831. configurable: true
  44832. });
  44833. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44834. /**
  44835. * Sets the shadow projection clipping maximum z value.
  44836. */
  44837. get: function () {
  44838. return this._shadowMaxZ;
  44839. },
  44840. /**
  44841. * Gets the shadow projection clipping maximum z value.
  44842. */
  44843. set: function (value) {
  44844. this._shadowMaxZ = value;
  44845. this.forceProjectionMatrixCompute();
  44846. },
  44847. enumerable: true,
  44848. configurable: true
  44849. });
  44850. /**
  44851. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44852. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44853. */
  44854. ShadowLight.prototype.computeTransformedInformation = function () {
  44855. if (this.parent && this.parent.getWorldMatrix) {
  44856. if (!this.transformedPosition) {
  44857. this.transformedPosition = BABYLON.Vector3.Zero();
  44858. }
  44859. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44860. // In case the direction is present.
  44861. if (this.direction) {
  44862. if (!this.transformedDirection) {
  44863. this.transformedDirection = BABYLON.Vector3.Zero();
  44864. }
  44865. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44866. }
  44867. return true;
  44868. }
  44869. return false;
  44870. };
  44871. /**
  44872. * Return the depth scale used for the shadow map.
  44873. * @returns the depth scale.
  44874. */
  44875. ShadowLight.prototype.getDepthScale = function () {
  44876. return 50.0;
  44877. };
  44878. /**
  44879. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44880. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44881. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44882. */
  44883. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44884. return this.transformedDirection ? this.transformedDirection : this.direction;
  44885. };
  44886. /**
  44887. * Returns the ShadowLight absolute position in the World.
  44888. * @returns the position vector in world space
  44889. */
  44890. ShadowLight.prototype.getAbsolutePosition = function () {
  44891. return this.transformedPosition ? this.transformedPosition : this.position;
  44892. };
  44893. /**
  44894. * Sets the ShadowLight direction toward the passed target.
  44895. * @param target The point tot target in local space
  44896. * @returns the updated ShadowLight direction
  44897. */
  44898. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44899. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44900. return this.direction;
  44901. };
  44902. /**
  44903. * Returns the light rotation in euler definition.
  44904. * @returns the x y z rotation in local space.
  44905. */
  44906. ShadowLight.prototype.getRotation = function () {
  44907. this.direction.normalize();
  44908. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44909. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44910. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44911. };
  44912. /**
  44913. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44914. * @returns true if a cube texture needs to be use
  44915. */
  44916. ShadowLight.prototype.needCube = function () {
  44917. return false;
  44918. };
  44919. /**
  44920. * Detects if the projection matrix requires to be recomputed this frame.
  44921. * @returns true if it requires to be recomputed otherwise, false.
  44922. */
  44923. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44924. return this._needProjectionMatrixCompute;
  44925. };
  44926. /**
  44927. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44928. */
  44929. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44930. this._needProjectionMatrixCompute = true;
  44931. };
  44932. /**
  44933. * Get the world matrix of the sahdow lights.
  44934. * @ignore Internal Use Only
  44935. */
  44936. ShadowLight.prototype._getWorldMatrix = function () {
  44937. if (!this._worldMatrix) {
  44938. this._worldMatrix = BABYLON.Matrix.Identity();
  44939. }
  44940. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44941. return this._worldMatrix;
  44942. };
  44943. /**
  44944. * Gets the minZ used for shadow according to both the scene and the light.
  44945. * @param activeCamera The camera we are returning the min for
  44946. * @returns the depth min z
  44947. */
  44948. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44949. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44950. };
  44951. /**
  44952. * Gets the maxZ used for shadow according to both the scene and the light.
  44953. * @param activeCamera The camera we are returning the max for
  44954. * @returns the depth max z
  44955. */
  44956. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44957. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44958. };
  44959. /**
  44960. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44961. * @param matrix The materix to updated with the projection information
  44962. * @param viewMatrix The transform matrix of the light
  44963. * @param renderList The list of mesh to render in the map
  44964. * @returns The current light
  44965. */
  44966. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44967. if (this.customProjectionMatrixBuilder) {
  44968. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44969. }
  44970. else {
  44971. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44972. }
  44973. return this;
  44974. };
  44975. __decorate([
  44976. BABYLON.serializeAsVector3()
  44977. ], ShadowLight.prototype, "position", null);
  44978. __decorate([
  44979. BABYLON.serializeAsVector3()
  44980. ], ShadowLight.prototype, "direction", null);
  44981. __decorate([
  44982. BABYLON.serialize()
  44983. ], ShadowLight.prototype, "shadowMinZ", null);
  44984. __decorate([
  44985. BABYLON.serialize()
  44986. ], ShadowLight.prototype, "shadowMaxZ", null);
  44987. return ShadowLight;
  44988. }(BABYLON.Light));
  44989. BABYLON.ShadowLight = ShadowLight;
  44990. })(BABYLON || (BABYLON = {}));
  44991. //# sourceMappingURL=babylon.shadowLight.js.map
  44992. var BABYLON;
  44993. (function (BABYLON) {
  44994. /**
  44995. * A point light is a light defined by an unique point in world space.
  44996. * The light is emitted in every direction from this point.
  44997. * A good example of a point light is a standard light bulb.
  44998. * Documentation: https://doc.babylonjs.com/babylon101/lights
  44999. */
  45000. var PointLight = /** @class */ (function (_super) {
  45001. __extends(PointLight, _super);
  45002. /**
  45003. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45004. * A PointLight emits the light in every direction.
  45005. * It can cast shadows.
  45006. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45007. * ```javascript
  45008. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45009. * ```
  45010. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45011. * @param name The light friendly name
  45012. * @param position The position of the point light in the scene
  45013. * @param scene The scene the lights belongs to
  45014. */
  45015. function PointLight(name, position, scene) {
  45016. var _this = _super.call(this, name, scene) || this;
  45017. _this._shadowAngle = Math.PI / 2;
  45018. _this.position = position;
  45019. return _this;
  45020. }
  45021. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45022. /**
  45023. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45024. * This specifies what angle the shadow will use to be created.
  45025. *
  45026. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45027. */
  45028. get: function () {
  45029. return this._shadowAngle;
  45030. },
  45031. /**
  45032. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45033. * This specifies what angle the shadow will use to be created.
  45034. *
  45035. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45036. */
  45037. set: function (value) {
  45038. this._shadowAngle = value;
  45039. this.forceProjectionMatrixCompute();
  45040. },
  45041. enumerable: true,
  45042. configurable: true
  45043. });
  45044. Object.defineProperty(PointLight.prototype, "direction", {
  45045. /**
  45046. * Gets the direction if it has been set.
  45047. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45048. */
  45049. get: function () {
  45050. return this._direction;
  45051. },
  45052. /**
  45053. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45054. */
  45055. set: function (value) {
  45056. var previousNeedCube = this.needCube();
  45057. this._direction = value;
  45058. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45059. this._shadowGenerator.recreateShadowMap();
  45060. }
  45061. },
  45062. enumerable: true,
  45063. configurable: true
  45064. });
  45065. /**
  45066. * Returns the string "PointLight"
  45067. * @returns the class name
  45068. */
  45069. PointLight.prototype.getClassName = function () {
  45070. return "PointLight";
  45071. };
  45072. /**
  45073. * Returns the integer 0.
  45074. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45075. */
  45076. PointLight.prototype.getTypeID = function () {
  45077. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45078. };
  45079. /**
  45080. * Specifies wether or not the shadowmap should be a cube texture.
  45081. * @returns true if the shadowmap needs to be a cube texture.
  45082. */
  45083. PointLight.prototype.needCube = function () {
  45084. return !this.direction;
  45085. };
  45086. /**
  45087. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45088. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45089. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45090. */
  45091. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45092. if (this.direction) {
  45093. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45094. }
  45095. else {
  45096. switch (faceIndex) {
  45097. case 0:
  45098. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45099. case 1:
  45100. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45101. case 2:
  45102. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45103. case 3:
  45104. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45105. case 4:
  45106. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45107. case 5:
  45108. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45109. }
  45110. }
  45111. return BABYLON.Vector3.Zero();
  45112. };
  45113. /**
  45114. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45115. * - fov = PI / 2
  45116. * - aspect ratio : 1.0
  45117. * - z-near and far equal to the active camera minZ and maxZ.
  45118. * Returns the PointLight.
  45119. */
  45120. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45121. var activeCamera = this.getScene().activeCamera;
  45122. if (!activeCamera) {
  45123. return;
  45124. }
  45125. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45126. };
  45127. PointLight.prototype._buildUniformLayout = function () {
  45128. this._uniformBuffer.addUniform("vLightData", 4);
  45129. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45130. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45131. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45132. this._uniformBuffer.addUniform("depthValues", 2);
  45133. this._uniformBuffer.create();
  45134. };
  45135. /**
  45136. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45137. * @param effect The effect to update
  45138. * @param lightIndex The index of the light in the effect to update
  45139. * @returns The point light
  45140. */
  45141. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45142. if (this.computeTransformedInformation()) {
  45143. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45144. return this;
  45145. }
  45146. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45147. return this;
  45148. };
  45149. __decorate([
  45150. BABYLON.serialize()
  45151. ], PointLight.prototype, "shadowAngle", null);
  45152. return PointLight;
  45153. }(BABYLON.ShadowLight));
  45154. BABYLON.PointLight = PointLight;
  45155. })(BABYLON || (BABYLON = {}));
  45156. //# sourceMappingURL=babylon.pointLight.js.map
  45157. var BABYLON;
  45158. (function (BABYLON) {
  45159. /**
  45160. * A directional light is defined by a direction (what a surprise!).
  45161. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45162. * 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.
  45163. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45164. */
  45165. var DirectionalLight = /** @class */ (function (_super) {
  45166. __extends(DirectionalLight, _super);
  45167. /**
  45168. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45169. * The directional light is emitted from everywhere in the given direction.
  45170. * It can cast shawdows.
  45171. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45172. * @param name The friendly name of the light
  45173. * @param direction The direction of the light
  45174. * @param scene The scene the light belongs to
  45175. */
  45176. function DirectionalLight(name, direction, scene) {
  45177. var _this = _super.call(this, name, scene) || this;
  45178. _this._shadowFrustumSize = 0;
  45179. _this._shadowOrthoScale = 0.5;
  45180. /**
  45181. * Automatically compute the projection matrix to best fit (including all the casters)
  45182. * on each frame.
  45183. */
  45184. _this.autoUpdateExtends = true;
  45185. // Cache
  45186. _this._orthoLeft = Number.MAX_VALUE;
  45187. _this._orthoRight = Number.MIN_VALUE;
  45188. _this._orthoTop = Number.MIN_VALUE;
  45189. _this._orthoBottom = Number.MAX_VALUE;
  45190. _this.position = direction.scale(-1.0);
  45191. _this.direction = direction;
  45192. return _this;
  45193. }
  45194. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45195. /**
  45196. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45197. */
  45198. get: function () {
  45199. return this._shadowFrustumSize;
  45200. },
  45201. /**
  45202. * Specifies a fix frustum size for the shadow generation.
  45203. */
  45204. set: function (value) {
  45205. this._shadowFrustumSize = value;
  45206. this.forceProjectionMatrixCompute();
  45207. },
  45208. enumerable: true,
  45209. configurable: true
  45210. });
  45211. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45212. /**
  45213. * Gets the shadow projection scale against the optimal computed one.
  45214. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45215. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45216. */
  45217. get: function () {
  45218. return this._shadowOrthoScale;
  45219. },
  45220. /**
  45221. * Sets the shadow projection scale against the optimal computed one.
  45222. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45223. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45224. */
  45225. set: function (value) {
  45226. this._shadowOrthoScale = value;
  45227. this.forceProjectionMatrixCompute();
  45228. },
  45229. enumerable: true,
  45230. configurable: true
  45231. });
  45232. /**
  45233. * Returns the string "DirectionalLight".
  45234. * @return The class name
  45235. */
  45236. DirectionalLight.prototype.getClassName = function () {
  45237. return "DirectionalLight";
  45238. };
  45239. /**
  45240. * Returns the integer 1.
  45241. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45242. */
  45243. DirectionalLight.prototype.getTypeID = function () {
  45244. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45245. };
  45246. /**
  45247. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45248. * Returns the DirectionalLight Shadow projection matrix.
  45249. */
  45250. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45251. if (this.shadowFrustumSize > 0) {
  45252. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45253. }
  45254. else {
  45255. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45256. }
  45257. };
  45258. /**
  45259. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45260. * Returns the DirectionalLight Shadow projection matrix.
  45261. */
  45262. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45263. var activeCamera = this.getScene().activeCamera;
  45264. if (!activeCamera) {
  45265. return;
  45266. }
  45267. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45268. };
  45269. /**
  45270. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45271. * Returns the DirectionalLight Shadow projection matrix.
  45272. */
  45273. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45274. var activeCamera = this.getScene().activeCamera;
  45275. if (!activeCamera) {
  45276. return;
  45277. }
  45278. // Check extends
  45279. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45280. var tempVector3 = BABYLON.Vector3.Zero();
  45281. this._orthoLeft = Number.MAX_VALUE;
  45282. this._orthoRight = Number.MIN_VALUE;
  45283. this._orthoTop = Number.MIN_VALUE;
  45284. this._orthoBottom = Number.MAX_VALUE;
  45285. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45286. var mesh = renderList[meshIndex];
  45287. if (!mesh) {
  45288. continue;
  45289. }
  45290. var boundingInfo = mesh.getBoundingInfo();
  45291. var boundingBox = boundingInfo.boundingBox;
  45292. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45293. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45294. if (tempVector3.x < this._orthoLeft)
  45295. this._orthoLeft = tempVector3.x;
  45296. if (tempVector3.y < this._orthoBottom)
  45297. this._orthoBottom = tempVector3.y;
  45298. if (tempVector3.x > this._orthoRight)
  45299. this._orthoRight = tempVector3.x;
  45300. if (tempVector3.y > this._orthoTop)
  45301. this._orthoTop = tempVector3.y;
  45302. }
  45303. }
  45304. }
  45305. var xOffset = this._orthoRight - this._orthoLeft;
  45306. var yOffset = this._orthoTop - this._orthoBottom;
  45307. 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);
  45308. };
  45309. DirectionalLight.prototype._buildUniformLayout = function () {
  45310. this._uniformBuffer.addUniform("vLightData", 4);
  45311. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45312. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45313. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45314. this._uniformBuffer.addUniform("depthValues", 2);
  45315. this._uniformBuffer.create();
  45316. };
  45317. /**
  45318. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45319. * @param effect The effect to update
  45320. * @param lightIndex The index of the light in the effect to update
  45321. * @returns The directional light
  45322. */
  45323. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45324. if (this.computeTransformedInformation()) {
  45325. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45326. return this;
  45327. }
  45328. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45329. return this;
  45330. };
  45331. /**
  45332. * Gets the minZ used for shadow according to both the scene and the light.
  45333. *
  45334. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45335. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45336. * @param activeCamera The camera we are returning the min for
  45337. * @returns the depth min z
  45338. */
  45339. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45340. return 1;
  45341. };
  45342. /**
  45343. * Gets the maxZ used for shadow according to both the scene and the light.
  45344. *
  45345. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45346. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45347. * @param activeCamera The camera we are returning the max for
  45348. * @returns the depth max z
  45349. */
  45350. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45351. return 1;
  45352. };
  45353. __decorate([
  45354. BABYLON.serialize()
  45355. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45356. __decorate([
  45357. BABYLON.serialize()
  45358. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45359. __decorate([
  45360. BABYLON.serialize()
  45361. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45362. return DirectionalLight;
  45363. }(BABYLON.ShadowLight));
  45364. BABYLON.DirectionalLight = DirectionalLight;
  45365. })(BABYLON || (BABYLON = {}));
  45366. //# sourceMappingURL=babylon.directionalLight.js.map
  45367. var BABYLON;
  45368. (function (BABYLON) {
  45369. /**
  45370. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45371. * These values define a cone of light starting from the position, emitting toward the direction.
  45372. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45373. * and the exponent defines the speed of the decay of the light with distance (reach).
  45374. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45375. */
  45376. var SpotLight = /** @class */ (function (_super) {
  45377. __extends(SpotLight, _super);
  45378. /**
  45379. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45380. * It can cast shadows.
  45381. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45382. * @param name The light friendly name
  45383. * @param position The position of the spot light in the scene
  45384. * @param direction The direction of the light in the scene
  45385. * @param angle The cone angle of the light in Radians
  45386. * @param exponent The light decay speed with the distance from the emission spot
  45387. * @param scene The scene the lights belongs to
  45388. */
  45389. function SpotLight(name, position, direction, angle, exponent, scene) {
  45390. var _this = _super.call(this, name, scene) || this;
  45391. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45392. _this._projectionTextureLightNear = 1e-6;
  45393. _this._projectionTextureLightFar = 1000.0;
  45394. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45395. _this._projectionTextureViewLightDirty = true;
  45396. _this._projectionTextureProjectionLightDirty = true;
  45397. _this._projectionTextureDirty = true;
  45398. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45399. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45400. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45401. _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);
  45402. _this.position = position;
  45403. _this.direction = direction;
  45404. _this.angle = angle;
  45405. _this.exponent = exponent;
  45406. return _this;
  45407. }
  45408. Object.defineProperty(SpotLight.prototype, "angle", {
  45409. /**
  45410. * Gets the cone angle of the spot light in Radians.
  45411. */
  45412. get: function () {
  45413. return this._angle;
  45414. },
  45415. /**
  45416. * Sets the cone angle of the spot light in Radians.
  45417. */
  45418. set: function (value) {
  45419. this._angle = value;
  45420. this._projectionTextureProjectionLightDirty = true;
  45421. this.forceProjectionMatrixCompute();
  45422. },
  45423. enumerable: true,
  45424. configurable: true
  45425. });
  45426. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45427. /**
  45428. * Allows scaling the angle of the light for shadow generation only.
  45429. */
  45430. get: function () {
  45431. return this._shadowAngleScale;
  45432. },
  45433. /**
  45434. * Allows scaling the angle of the light for shadow generation only.
  45435. */
  45436. set: function (value) {
  45437. this._shadowAngleScale = value;
  45438. this.forceProjectionMatrixCompute();
  45439. },
  45440. enumerable: true,
  45441. configurable: true
  45442. });
  45443. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45444. /**
  45445. * Allows reading the projecton texture
  45446. */
  45447. get: function () {
  45448. return this._projectionTextureMatrix;
  45449. },
  45450. enumerable: true,
  45451. configurable: true
  45452. });
  45453. ;
  45454. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45455. /**
  45456. * Gets the near clip of the Spotlight for texture projection.
  45457. */
  45458. get: function () {
  45459. return this._projectionTextureLightNear;
  45460. },
  45461. /**
  45462. * Sets the near clip of the Spotlight for texture projection.
  45463. */
  45464. set: function (value) {
  45465. this._projectionTextureLightNear = value;
  45466. this._projectionTextureProjectionLightDirty = true;
  45467. },
  45468. enumerable: true,
  45469. configurable: true
  45470. });
  45471. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45472. /**
  45473. * Gets the far clip of the Spotlight for texture projection.
  45474. */
  45475. get: function () {
  45476. return this._projectionTextureLightFar;
  45477. },
  45478. /**
  45479. * Sets the far clip of the Spotlight for texture projection.
  45480. */
  45481. set: function (value) {
  45482. this._projectionTextureLightFar = value;
  45483. this._projectionTextureProjectionLightDirty = true;
  45484. },
  45485. enumerable: true,
  45486. configurable: true
  45487. });
  45488. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45489. /**
  45490. * Gets the Up vector of the Spotlight for texture projection.
  45491. */
  45492. get: function () {
  45493. return this._projectionTextureUpDirection;
  45494. },
  45495. /**
  45496. * Sets the Up vector of the Spotlight for texture projection.
  45497. */
  45498. set: function (value) {
  45499. this._projectionTextureUpDirection = value;
  45500. this._projectionTextureProjectionLightDirty = true;
  45501. },
  45502. enumerable: true,
  45503. configurable: true
  45504. });
  45505. ;
  45506. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45507. /**
  45508. * Gets the projection texture of the light.
  45509. */
  45510. get: function () {
  45511. return this._projectionTexture;
  45512. },
  45513. /**
  45514. * Sets the projection texture of the light.
  45515. */
  45516. set: function (value) {
  45517. this._projectionTexture = value;
  45518. this._projectionTextureDirty = true;
  45519. },
  45520. enumerable: true,
  45521. configurable: true
  45522. });
  45523. /**
  45524. * Returns the string "SpotLight".
  45525. * @returns the class name
  45526. */
  45527. SpotLight.prototype.getClassName = function () {
  45528. return "SpotLight";
  45529. };
  45530. /**
  45531. * Returns the integer 2.
  45532. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45533. */
  45534. SpotLight.prototype.getTypeID = function () {
  45535. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45536. };
  45537. /**
  45538. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45539. */
  45540. SpotLight.prototype._setDirection = function (value) {
  45541. _super.prototype._setDirection.call(this, value);
  45542. this._projectionTextureViewLightDirty = true;
  45543. };
  45544. /**
  45545. * Overrides the position setter to recompute the projection texture view light Matrix.
  45546. */
  45547. SpotLight.prototype._setPosition = function (value) {
  45548. _super.prototype._setPosition.call(this, value);
  45549. this._projectionTextureViewLightDirty = true;
  45550. };
  45551. /**
  45552. * 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.
  45553. * Returns the SpotLight.
  45554. */
  45555. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45556. var activeCamera = this.getScene().activeCamera;
  45557. if (!activeCamera) {
  45558. return;
  45559. }
  45560. this._shadowAngleScale = this._shadowAngleScale || 1;
  45561. var angle = this._shadowAngleScale * this._angle;
  45562. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45563. };
  45564. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45565. this._projectionTextureViewLightDirty = false;
  45566. this._projectionTextureDirty = true;
  45567. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45568. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45569. };
  45570. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45571. this._projectionTextureProjectionLightDirty = false;
  45572. this._projectionTextureDirty = true;
  45573. var light_far = this.projectionTextureLightFar;
  45574. var light_near = this.projectionTextureLightNear;
  45575. var P = light_far / (light_far - light_near);
  45576. var Q = -P * light_near;
  45577. var S = 1.0 / Math.tan(this._angle / 2.0);
  45578. var A = 1.0;
  45579. 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);
  45580. };
  45581. /**
  45582. * Main function for light texture projection matrix computing.
  45583. */
  45584. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45585. this._projectionTextureDirty = false;
  45586. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45587. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45588. };
  45589. SpotLight.prototype._buildUniformLayout = function () {
  45590. this._uniformBuffer.addUniform("vLightData", 4);
  45591. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45592. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45593. this._uniformBuffer.addUniform("vLightDirection", 3);
  45594. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45595. this._uniformBuffer.addUniform("depthValues", 2);
  45596. this._uniformBuffer.create();
  45597. };
  45598. /**
  45599. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45600. * @param effect The effect to update
  45601. * @param lightIndex The index of the light in the effect to update
  45602. * @returns The spot light
  45603. */
  45604. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45605. var normalizeDirection;
  45606. if (this.computeTransformedInformation()) {
  45607. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45608. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45609. }
  45610. else {
  45611. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45612. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45613. }
  45614. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45615. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45616. if (this._projectionTextureViewLightDirty) {
  45617. this._computeProjectionTextureViewLightMatrix();
  45618. }
  45619. if (this._projectionTextureProjectionLightDirty) {
  45620. this._computeProjectionTextureProjectionLightMatrix();
  45621. }
  45622. if (this._projectionTextureDirty) {
  45623. this._computeProjectionTextureMatrix();
  45624. }
  45625. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45626. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45627. }
  45628. return this;
  45629. };
  45630. /**
  45631. * Disposes the light and the associated resources.
  45632. */
  45633. SpotLight.prototype.dispose = function () {
  45634. _super.prototype.dispose.call(this);
  45635. if (this._projectionTexture) {
  45636. this._projectionTexture.dispose();
  45637. }
  45638. };
  45639. __decorate([
  45640. BABYLON.serialize()
  45641. ], SpotLight.prototype, "angle", null);
  45642. __decorate([
  45643. BABYLON.serialize()
  45644. ], SpotLight.prototype, "shadowAngleScale", null);
  45645. __decorate([
  45646. BABYLON.serialize()
  45647. ], SpotLight.prototype, "exponent", void 0);
  45648. __decorate([
  45649. BABYLON.serialize()
  45650. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45651. __decorate([
  45652. BABYLON.serialize()
  45653. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45654. __decorate([
  45655. BABYLON.serialize()
  45656. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45657. __decorate([
  45658. BABYLON.serializeAsTexture("projectedLightTexture")
  45659. ], SpotLight.prototype, "_projectionTexture", void 0);
  45660. return SpotLight;
  45661. }(BABYLON.ShadowLight));
  45662. BABYLON.SpotLight = SpotLight;
  45663. })(BABYLON || (BABYLON = {}));
  45664. //# sourceMappingURL=babylon.spotLight.js.map
  45665. var BABYLON;
  45666. (function (BABYLON) {
  45667. var AnimationRange = /** @class */ (function () {
  45668. function AnimationRange(name, from, to) {
  45669. this.name = name;
  45670. this.from = from;
  45671. this.to = to;
  45672. }
  45673. AnimationRange.prototype.clone = function () {
  45674. return new AnimationRange(this.name, this.from, this.to);
  45675. };
  45676. return AnimationRange;
  45677. }());
  45678. BABYLON.AnimationRange = AnimationRange;
  45679. /**
  45680. * Composed of a frame, and an action function
  45681. */
  45682. var AnimationEvent = /** @class */ (function () {
  45683. function AnimationEvent(frame, action, onlyOnce) {
  45684. this.frame = frame;
  45685. this.action = action;
  45686. this.onlyOnce = onlyOnce;
  45687. this.isDone = false;
  45688. }
  45689. return AnimationEvent;
  45690. }());
  45691. BABYLON.AnimationEvent = AnimationEvent;
  45692. var PathCursor = /** @class */ (function () {
  45693. function PathCursor(path) {
  45694. this.path = path;
  45695. this._onchange = new Array();
  45696. this.value = 0;
  45697. this.animations = new Array();
  45698. }
  45699. PathCursor.prototype.getPoint = function () {
  45700. var point = this.path.getPointAtLengthPosition(this.value);
  45701. return new BABYLON.Vector3(point.x, 0, point.y);
  45702. };
  45703. PathCursor.prototype.moveAhead = function (step) {
  45704. if (step === void 0) { step = 0.002; }
  45705. this.move(step);
  45706. return this;
  45707. };
  45708. PathCursor.prototype.moveBack = function (step) {
  45709. if (step === void 0) { step = 0.002; }
  45710. this.move(-step);
  45711. return this;
  45712. };
  45713. PathCursor.prototype.move = function (step) {
  45714. if (Math.abs(step) > 1) {
  45715. throw "step size should be less than 1.";
  45716. }
  45717. this.value += step;
  45718. this.ensureLimits();
  45719. this.raiseOnChange();
  45720. return this;
  45721. };
  45722. PathCursor.prototype.ensureLimits = function () {
  45723. while (this.value > 1) {
  45724. this.value -= 1;
  45725. }
  45726. while (this.value < 0) {
  45727. this.value += 1;
  45728. }
  45729. return this;
  45730. };
  45731. // used by animation engine
  45732. PathCursor.prototype.raiseOnChange = function () {
  45733. var _this = this;
  45734. this._onchange.forEach(function (f) { return f(_this); });
  45735. return this;
  45736. };
  45737. PathCursor.prototype.onchange = function (f) {
  45738. this._onchange.push(f);
  45739. return this;
  45740. };
  45741. return PathCursor;
  45742. }());
  45743. BABYLON.PathCursor = PathCursor;
  45744. var AnimationKeyInterpolation;
  45745. (function (AnimationKeyInterpolation) {
  45746. /**
  45747. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45748. */
  45749. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45750. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45751. var Animation = /** @class */ (function () {
  45752. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45753. this.name = name;
  45754. this.targetProperty = targetProperty;
  45755. this.framePerSecond = framePerSecond;
  45756. this.dataType = dataType;
  45757. this.loopMode = loopMode;
  45758. this.enableBlending = enableBlending;
  45759. this._runtimeAnimations = new Array();
  45760. // The set of event that will be linked to this animation
  45761. this._events = new Array();
  45762. this.blendingSpeed = 0.01;
  45763. this._ranges = {};
  45764. this.targetPropertyPath = targetProperty.split(".");
  45765. this.dataType = dataType;
  45766. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45767. }
  45768. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45769. var dataType = undefined;
  45770. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45771. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45772. }
  45773. else if (from instanceof BABYLON.Quaternion) {
  45774. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45775. }
  45776. else if (from instanceof BABYLON.Vector3) {
  45777. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45778. }
  45779. else if (from instanceof BABYLON.Vector2) {
  45780. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45781. }
  45782. else if (from instanceof BABYLON.Color3) {
  45783. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45784. }
  45785. else if (from instanceof BABYLON.Size) {
  45786. dataType = Animation.ANIMATIONTYPE_SIZE;
  45787. }
  45788. if (dataType == undefined) {
  45789. return null;
  45790. }
  45791. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45792. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45793. animation.setKeys(keys);
  45794. if (easingFunction !== undefined) {
  45795. animation.setEasingFunction(easingFunction);
  45796. }
  45797. return animation;
  45798. };
  45799. /**
  45800. * Sets up an animation.
  45801. * @param property the property to animate
  45802. * @param animationType the animation type to apply
  45803. * @param easingFunction the easing function used in the animation
  45804. * @returns The created animation
  45805. */
  45806. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45807. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45808. animation.setEasingFunction(easingFunction);
  45809. return animation;
  45810. };
  45811. /**
  45812. * Create and start an animation on a node
  45813. * @param {string} name defines the name of the global animation that will be run on all nodes
  45814. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45815. * @param {string} targetProperty defines property to animate
  45816. * @param {number} framePerSecond defines the number of frame per second yo use
  45817. * @param {number} totalFrame defines the number of frames in total
  45818. * @param {any} from defines the initial value
  45819. * @param {any} to defines the final value
  45820. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45821. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45822. * @param onAnimationEnd defines the callback to call when animation end
  45823. * @returns the animatable created for this animation
  45824. */
  45825. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45826. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45827. if (!animation) {
  45828. return null;
  45829. }
  45830. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45831. };
  45832. /**
  45833. * Create and start an animation on a node and its descendants
  45834. * @param {string} name defines the name of the global animation that will be run on all nodes
  45835. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45836. * @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.
  45837. * @param {string} targetProperty defines property to animate
  45838. * @param {number} framePerSecond defines the number of frame per second yo use
  45839. * @param {number} totalFrame defines the number of frames in total
  45840. * @param {any} from defines the initial value
  45841. * @param {any} to defines the final value
  45842. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45843. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45844. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45845. * @returns the list of animatables created for all nodes
  45846. * @example https://www.babylonjs-playground.com/#MH0VLI
  45847. */
  45848. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45849. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45850. if (!animation) {
  45851. return null;
  45852. }
  45853. var scene = node.getScene();
  45854. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45855. };
  45856. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45857. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45858. if (!animation) {
  45859. return null;
  45860. }
  45861. node.animations.push(animation);
  45862. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45863. };
  45864. /**
  45865. * Transition property of the Camera to the target Value.
  45866. * @param property The property to transition
  45867. * @param targetValue The target Value of the property
  45868. * @param host The object where the property to animate belongs
  45869. * @param scene Scene used to run the animation
  45870. * @param frameRate Framerate (in frame/s) to use
  45871. * @param transition The transition type we want to use
  45872. * @param duration The duration of the animation, in milliseconds
  45873. * @param onAnimationEnd Call back trigger at the end of the animation.
  45874. */
  45875. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45876. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45877. if (duration <= 0) {
  45878. host[property] = targetValue;
  45879. if (onAnimationEnd) {
  45880. onAnimationEnd();
  45881. }
  45882. return null;
  45883. }
  45884. var endFrame = frameRate * (duration / 1000);
  45885. transition.setKeys([{
  45886. frame: 0,
  45887. value: host[property].clone ? host[property].clone() : host[property]
  45888. },
  45889. {
  45890. frame: endFrame,
  45891. value: targetValue
  45892. }]);
  45893. if (!host.animations) {
  45894. host.animations = [];
  45895. }
  45896. host.animations.push(transition);
  45897. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45898. animation.onAnimationEnd = onAnimationEnd;
  45899. return animation;
  45900. };
  45901. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45902. /**
  45903. * Return the array of runtime animations currently using this animation
  45904. */
  45905. get: function () {
  45906. return this._runtimeAnimations;
  45907. },
  45908. enumerable: true,
  45909. configurable: true
  45910. });
  45911. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45912. get: function () {
  45913. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45914. var runtimeAnimation = _a[_i];
  45915. if (!runtimeAnimation.isStopped) {
  45916. return true;
  45917. }
  45918. }
  45919. return false;
  45920. },
  45921. enumerable: true,
  45922. configurable: true
  45923. });
  45924. // Methods
  45925. /**
  45926. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45927. */
  45928. Animation.prototype.toString = function (fullDetails) {
  45929. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45930. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45931. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45932. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45933. if (fullDetails) {
  45934. ret += ", Ranges: {";
  45935. var first = true;
  45936. for (var name in this._ranges) {
  45937. if (first) {
  45938. ret += ", ";
  45939. first = false;
  45940. }
  45941. ret += name;
  45942. }
  45943. ret += "}";
  45944. }
  45945. return ret;
  45946. };
  45947. /**
  45948. * Add an event to this animation.
  45949. */
  45950. Animation.prototype.addEvent = function (event) {
  45951. this._events.push(event);
  45952. };
  45953. /**
  45954. * Remove all events found at the given frame
  45955. * @param frame
  45956. */
  45957. Animation.prototype.removeEvents = function (frame) {
  45958. for (var index = 0; index < this._events.length; index++) {
  45959. if (this._events[index].frame === frame) {
  45960. this._events.splice(index, 1);
  45961. index--;
  45962. }
  45963. }
  45964. };
  45965. Animation.prototype.getEvents = function () {
  45966. return this._events;
  45967. };
  45968. Animation.prototype.createRange = function (name, from, to) {
  45969. // check name not already in use; could happen for bones after serialized
  45970. if (!this._ranges[name]) {
  45971. this._ranges[name] = new AnimationRange(name, from, to);
  45972. }
  45973. };
  45974. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45975. if (deleteFrames === void 0) { deleteFrames = true; }
  45976. var range = this._ranges[name];
  45977. if (!range) {
  45978. return;
  45979. }
  45980. if (deleteFrames) {
  45981. var from = range.from;
  45982. var to = range.to;
  45983. // this loop MUST go high to low for multiple splices to work
  45984. for (var key = this._keys.length - 1; key >= 0; key--) {
  45985. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45986. this._keys.splice(key, 1);
  45987. }
  45988. }
  45989. }
  45990. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  45991. };
  45992. Animation.prototype.getRange = function (name) {
  45993. return this._ranges[name];
  45994. };
  45995. Animation.prototype.getKeys = function () {
  45996. return this._keys;
  45997. };
  45998. Animation.prototype.getHighestFrame = function () {
  45999. var ret = 0;
  46000. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46001. if (ret < this._keys[key].frame) {
  46002. ret = this._keys[key].frame;
  46003. }
  46004. }
  46005. return ret;
  46006. };
  46007. Animation.prototype.getEasingFunction = function () {
  46008. return this._easingFunction;
  46009. };
  46010. Animation.prototype.setEasingFunction = function (easingFunction) {
  46011. this._easingFunction = easingFunction;
  46012. };
  46013. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46014. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46015. };
  46016. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46017. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46018. };
  46019. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46020. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46021. };
  46022. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46023. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46024. };
  46025. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46026. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46027. };
  46028. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46029. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46030. };
  46031. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46032. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46033. };
  46034. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46035. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46036. };
  46037. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46038. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46039. };
  46040. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46041. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46042. };
  46043. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46044. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46045. };
  46046. Animation.prototype.clone = function () {
  46047. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46048. clone.enableBlending = this.enableBlending;
  46049. clone.blendingSpeed = this.blendingSpeed;
  46050. if (this._keys) {
  46051. clone.setKeys(this._keys);
  46052. }
  46053. if (this._ranges) {
  46054. clone._ranges = {};
  46055. for (var name in this._ranges) {
  46056. var range = this._ranges[name];
  46057. if (!range) {
  46058. continue;
  46059. }
  46060. clone._ranges[name] = range.clone();
  46061. }
  46062. }
  46063. return clone;
  46064. };
  46065. Animation.prototype.setKeys = function (values) {
  46066. this._keys = values.slice(0);
  46067. };
  46068. Animation.prototype.serialize = function () {
  46069. var serializationObject = {};
  46070. serializationObject.name = this.name;
  46071. serializationObject.property = this.targetProperty;
  46072. serializationObject.framePerSecond = this.framePerSecond;
  46073. serializationObject.dataType = this.dataType;
  46074. serializationObject.loopBehavior = this.loopMode;
  46075. serializationObject.enableBlending = this.enableBlending;
  46076. serializationObject.blendingSpeed = this.blendingSpeed;
  46077. var dataType = this.dataType;
  46078. serializationObject.keys = [];
  46079. var keys = this.getKeys();
  46080. for (var index = 0; index < keys.length; index++) {
  46081. var animationKey = keys[index];
  46082. var key = {};
  46083. key.frame = animationKey.frame;
  46084. switch (dataType) {
  46085. case Animation.ANIMATIONTYPE_FLOAT:
  46086. key.values = [animationKey.value];
  46087. break;
  46088. case Animation.ANIMATIONTYPE_QUATERNION:
  46089. case Animation.ANIMATIONTYPE_MATRIX:
  46090. case Animation.ANIMATIONTYPE_VECTOR3:
  46091. case Animation.ANIMATIONTYPE_COLOR3:
  46092. key.values = animationKey.value.asArray();
  46093. break;
  46094. }
  46095. serializationObject.keys.push(key);
  46096. }
  46097. serializationObject.ranges = [];
  46098. for (var name in this._ranges) {
  46099. var source = this._ranges[name];
  46100. if (!source) {
  46101. continue;
  46102. }
  46103. var range = {};
  46104. range.name = name;
  46105. range.from = source.from;
  46106. range.to = source.to;
  46107. serializationObject.ranges.push(range);
  46108. }
  46109. return serializationObject;
  46110. };
  46111. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46112. get: function () {
  46113. return Animation._ANIMATIONTYPE_FLOAT;
  46114. },
  46115. enumerable: true,
  46116. configurable: true
  46117. });
  46118. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46119. get: function () {
  46120. return Animation._ANIMATIONTYPE_VECTOR3;
  46121. },
  46122. enumerable: true,
  46123. configurable: true
  46124. });
  46125. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46126. get: function () {
  46127. return Animation._ANIMATIONTYPE_VECTOR2;
  46128. },
  46129. enumerable: true,
  46130. configurable: true
  46131. });
  46132. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46133. get: function () {
  46134. return Animation._ANIMATIONTYPE_SIZE;
  46135. },
  46136. enumerable: true,
  46137. configurable: true
  46138. });
  46139. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46140. get: function () {
  46141. return Animation._ANIMATIONTYPE_QUATERNION;
  46142. },
  46143. enumerable: true,
  46144. configurable: true
  46145. });
  46146. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46147. get: function () {
  46148. return Animation._ANIMATIONTYPE_MATRIX;
  46149. },
  46150. enumerable: true,
  46151. configurable: true
  46152. });
  46153. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46154. get: function () {
  46155. return Animation._ANIMATIONTYPE_COLOR3;
  46156. },
  46157. enumerable: true,
  46158. configurable: true
  46159. });
  46160. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46161. get: function () {
  46162. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46163. },
  46164. enumerable: true,
  46165. configurable: true
  46166. });
  46167. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46168. get: function () {
  46169. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46170. },
  46171. enumerable: true,
  46172. configurable: true
  46173. });
  46174. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46175. get: function () {
  46176. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46177. },
  46178. enumerable: true,
  46179. configurable: true
  46180. });
  46181. Animation.Parse = function (parsedAnimation) {
  46182. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46183. var dataType = parsedAnimation.dataType;
  46184. var keys = [];
  46185. var data;
  46186. var index;
  46187. if (parsedAnimation.enableBlending) {
  46188. animation.enableBlending = parsedAnimation.enableBlending;
  46189. }
  46190. if (parsedAnimation.blendingSpeed) {
  46191. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46192. }
  46193. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46194. var key = parsedAnimation.keys[index];
  46195. var inTangent;
  46196. var outTangent;
  46197. switch (dataType) {
  46198. case Animation.ANIMATIONTYPE_FLOAT:
  46199. data = key.values[0];
  46200. if (key.values.length >= 1) {
  46201. inTangent = key.values[1];
  46202. }
  46203. if (key.values.length >= 2) {
  46204. outTangent = key.values[2];
  46205. }
  46206. break;
  46207. case Animation.ANIMATIONTYPE_QUATERNION:
  46208. data = BABYLON.Quaternion.FromArray(key.values);
  46209. if (key.values.length >= 8) {
  46210. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46211. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46212. inTangent = _inTangent;
  46213. }
  46214. }
  46215. if (key.values.length >= 12) {
  46216. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46217. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46218. outTangent = _outTangent;
  46219. }
  46220. }
  46221. break;
  46222. case Animation.ANIMATIONTYPE_MATRIX:
  46223. data = BABYLON.Matrix.FromArray(key.values);
  46224. break;
  46225. case Animation.ANIMATIONTYPE_COLOR3:
  46226. data = BABYLON.Color3.FromArray(key.values);
  46227. break;
  46228. case Animation.ANIMATIONTYPE_VECTOR3:
  46229. default:
  46230. data = BABYLON.Vector3.FromArray(key.values);
  46231. break;
  46232. }
  46233. var keyData = {};
  46234. keyData.frame = key.frame;
  46235. keyData.value = data;
  46236. if (inTangent != undefined) {
  46237. keyData.inTangent = inTangent;
  46238. }
  46239. if (outTangent != undefined) {
  46240. keyData.outTangent = outTangent;
  46241. }
  46242. keys.push(keyData);
  46243. }
  46244. animation.setKeys(keys);
  46245. if (parsedAnimation.ranges) {
  46246. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46247. data = parsedAnimation.ranges[index];
  46248. animation.createRange(data.name, data.from, data.to);
  46249. }
  46250. }
  46251. return animation;
  46252. };
  46253. Animation.AppendSerializedAnimations = function (source, destination) {
  46254. if (source.animations) {
  46255. destination.animations = [];
  46256. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46257. var animation = source.animations[animationIndex];
  46258. destination.animations.push(animation.serialize());
  46259. }
  46260. }
  46261. };
  46262. Animation.AllowMatricesInterpolation = false;
  46263. // Statics
  46264. Animation._ANIMATIONTYPE_FLOAT = 0;
  46265. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46266. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46267. Animation._ANIMATIONTYPE_MATRIX = 3;
  46268. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46269. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46270. Animation._ANIMATIONTYPE_SIZE = 6;
  46271. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46272. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46273. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46274. return Animation;
  46275. }());
  46276. BABYLON.Animation = Animation;
  46277. })(BABYLON || (BABYLON = {}));
  46278. //# sourceMappingURL=babylon.animation.js.map
  46279. var BABYLON;
  46280. (function (BABYLON) {
  46281. /**
  46282. * This class defines the direct association between an animation and a target
  46283. */
  46284. var TargetedAnimation = /** @class */ (function () {
  46285. function TargetedAnimation() {
  46286. }
  46287. return TargetedAnimation;
  46288. }());
  46289. BABYLON.TargetedAnimation = TargetedAnimation;
  46290. /**
  46291. * Use this class to create coordinated animations on multiple targets
  46292. */
  46293. var AnimationGroup = /** @class */ (function () {
  46294. function AnimationGroup(name, scene) {
  46295. if (scene === void 0) { scene = null; }
  46296. this.name = name;
  46297. this._targetedAnimations = new Array();
  46298. this._animatables = new Array();
  46299. this._from = Number.MAX_VALUE;
  46300. this._to = -Number.MAX_VALUE;
  46301. this._speedRatio = 1;
  46302. this.onAnimationEndObservable = new BABYLON.Observable();
  46303. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46304. this._scene.animationGroups.push(this);
  46305. }
  46306. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46307. /**
  46308. * Define if the animations are started
  46309. */
  46310. get: function () {
  46311. return this._isStarted;
  46312. },
  46313. enumerable: true,
  46314. configurable: true
  46315. });
  46316. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46317. /**
  46318. * Gets or sets the speed ratio to use for all animations
  46319. */
  46320. get: function () {
  46321. return this._speedRatio;
  46322. },
  46323. /**
  46324. * Gets or sets the speed ratio to use for all animations
  46325. */
  46326. set: function (value) {
  46327. if (this._speedRatio === value) {
  46328. return;
  46329. }
  46330. this._speedRatio = value;
  46331. for (var index = 0; index < this._animatables.length; index++) {
  46332. var animatable = this._animatables[index];
  46333. animatable.speedRatio = this._speedRatio;
  46334. }
  46335. },
  46336. enumerable: true,
  46337. configurable: true
  46338. });
  46339. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46340. /**
  46341. * Gets the targeted animations for this animation group
  46342. */
  46343. get: function () {
  46344. return this._targetedAnimations;
  46345. },
  46346. enumerable: true,
  46347. configurable: true
  46348. });
  46349. /**
  46350. * Add an animation (with its target) in the group
  46351. * @param animation defines the animation we want to add
  46352. * @param target defines the target of the animation
  46353. * @returns the {BABYLON.TargetedAnimation} object
  46354. */
  46355. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46356. var targetedAnimation = {
  46357. animation: animation,
  46358. target: target
  46359. };
  46360. var keys = animation.getKeys();
  46361. if (this._from > keys[0].frame) {
  46362. this._from = keys[0].frame;
  46363. }
  46364. if (this._to < keys[keys.length - 1].frame) {
  46365. this._to = keys[keys.length - 1].frame;
  46366. }
  46367. this._targetedAnimations.push(targetedAnimation);
  46368. return targetedAnimation;
  46369. };
  46370. /**
  46371. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46372. * It can add constant keys at begin or end
  46373. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46374. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46375. */
  46376. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46377. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46378. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46379. beginFrame = Math.max(beginFrame, this._from);
  46380. endFrame = Math.min(endFrame, this._to);
  46381. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46382. var targetedAnimation = this._targetedAnimations[index];
  46383. var keys = targetedAnimation.animation.getKeys();
  46384. var startKey = keys[0];
  46385. var endKey = keys[keys.length - 1];
  46386. if (startKey.frame > beginFrame) {
  46387. var newKey = {
  46388. frame: beginFrame,
  46389. value: startKey.value,
  46390. inTangent: startKey.inTangent,
  46391. outTangent: startKey.outTangent,
  46392. interpolation: startKey.interpolation
  46393. };
  46394. keys.splice(0, 0, newKey);
  46395. }
  46396. if (endKey.frame < endFrame) {
  46397. var newKey = {
  46398. frame: endFrame,
  46399. value: endKey.value,
  46400. inTangent: endKey.outTangent,
  46401. outTangent: endKey.outTangent,
  46402. interpolation: endKey.interpolation
  46403. };
  46404. keys.push(newKey);
  46405. }
  46406. }
  46407. return this;
  46408. };
  46409. /**
  46410. * Start all animations on given targets
  46411. * @param loop defines if animations must loop
  46412. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46413. */
  46414. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46415. var _this = this;
  46416. if (loop === void 0) { loop = false; }
  46417. if (speedRatio === void 0) { speedRatio = 1; }
  46418. if (this._isStarted || this._targetedAnimations.length === 0) {
  46419. return this;
  46420. }
  46421. var _loop_1 = function () {
  46422. var targetedAnimation = this_1._targetedAnimations[index];
  46423. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46424. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46425. }));
  46426. };
  46427. var this_1 = this;
  46428. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46429. _loop_1();
  46430. }
  46431. this._speedRatio = speedRatio;
  46432. this._isStarted = true;
  46433. return this;
  46434. };
  46435. /**
  46436. * Pause all animations
  46437. */
  46438. AnimationGroup.prototype.pause = function () {
  46439. if (!this._isStarted) {
  46440. return this;
  46441. }
  46442. for (var index = 0; index < this._animatables.length; index++) {
  46443. var animatable = this._animatables[index];
  46444. animatable.pause();
  46445. }
  46446. return this;
  46447. };
  46448. /**
  46449. * Play all animations to initial state
  46450. * This function will start() the animations if they were not started or will restart() them if they were paused
  46451. * @param loop defines if animations must loop
  46452. */
  46453. AnimationGroup.prototype.play = function (loop) {
  46454. if (this.isStarted) {
  46455. if (loop !== undefined) {
  46456. for (var index = 0; index < this._animatables.length; index++) {
  46457. var animatable = this._animatables[index];
  46458. animatable.loopAnimation = loop;
  46459. }
  46460. }
  46461. this.restart();
  46462. }
  46463. else {
  46464. this.start(loop, this._speedRatio);
  46465. }
  46466. return this;
  46467. };
  46468. /**
  46469. * Reset all animations to initial state
  46470. */
  46471. AnimationGroup.prototype.reset = function () {
  46472. if (!this._isStarted) {
  46473. return this;
  46474. }
  46475. for (var index = 0; index < this._animatables.length; index++) {
  46476. var animatable = this._animatables[index];
  46477. animatable.reset();
  46478. }
  46479. return this;
  46480. };
  46481. /**
  46482. * Restart animations from key 0
  46483. */
  46484. AnimationGroup.prototype.restart = function () {
  46485. if (!this._isStarted) {
  46486. return this;
  46487. }
  46488. for (var index = 0; index < this._animatables.length; index++) {
  46489. var animatable = this._animatables[index];
  46490. animatable.restart();
  46491. }
  46492. return this;
  46493. };
  46494. /**
  46495. * Stop all animations
  46496. */
  46497. AnimationGroup.prototype.stop = function () {
  46498. if (!this._isStarted) {
  46499. return this;
  46500. }
  46501. for (var index = 0; index < this._animatables.length; index++) {
  46502. var animatable = this._animatables[index];
  46503. animatable.stop();
  46504. }
  46505. this._isStarted = false;
  46506. return this;
  46507. };
  46508. /**
  46509. * Dispose all associated resources
  46510. */
  46511. AnimationGroup.prototype.dispose = function () {
  46512. this._targetedAnimations = [];
  46513. this._animatables = [];
  46514. var index = this._scene.animationGroups.indexOf(this);
  46515. if (index > -1) {
  46516. this._scene.animationGroups.splice(index, 1);
  46517. }
  46518. };
  46519. return AnimationGroup;
  46520. }());
  46521. BABYLON.AnimationGroup = AnimationGroup;
  46522. })(BABYLON || (BABYLON = {}));
  46523. //# sourceMappingURL=babylon.animationGroup.js.map
  46524. var BABYLON;
  46525. (function (BABYLON) {
  46526. var RuntimeAnimation = /** @class */ (function () {
  46527. function RuntimeAnimation(target, animation) {
  46528. this._offsetsCache = {};
  46529. this._highLimitsCache = {};
  46530. this._stopped = false;
  46531. this._blendingFactor = 0;
  46532. this._ratioOffset = 0;
  46533. this._animation = animation;
  46534. this._target = target;
  46535. animation._runtimeAnimations.push(this);
  46536. }
  46537. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46538. get: function () {
  46539. return this._animation;
  46540. },
  46541. enumerable: true,
  46542. configurable: true
  46543. });
  46544. RuntimeAnimation.prototype.reset = function () {
  46545. this._offsetsCache = {};
  46546. this._highLimitsCache = {};
  46547. this.currentFrame = 0;
  46548. this._blendingFactor = 0;
  46549. this._originalBlendValue = null;
  46550. };
  46551. RuntimeAnimation.prototype.isStopped = function () {
  46552. return this._stopped;
  46553. };
  46554. RuntimeAnimation.prototype.dispose = function () {
  46555. var index = this._animation.runtimeAnimations.indexOf(this);
  46556. if (index > -1) {
  46557. this._animation.runtimeAnimations.splice(index, 1);
  46558. }
  46559. };
  46560. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46561. if (typeof value === "function") {
  46562. return value();
  46563. }
  46564. return value;
  46565. };
  46566. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46567. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46568. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46569. }
  46570. this.currentFrame = currentFrame;
  46571. var keys = this._animation.getKeys();
  46572. // Try to get a hash to find the right key
  46573. 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));
  46574. if (keys[startKeyIndex].frame >= currentFrame) {
  46575. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46576. startKeyIndex--;
  46577. }
  46578. }
  46579. for (var key = startKeyIndex; key < keys.length; key++) {
  46580. var endKey = keys[key + 1];
  46581. if (endKey.frame >= currentFrame) {
  46582. var startKey = keys[key];
  46583. var startValue = this._getKeyValue(startKey.value);
  46584. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46585. return startValue;
  46586. }
  46587. var endValue = this._getKeyValue(endKey.value);
  46588. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46589. var frameDelta = endKey.frame - startKey.frame;
  46590. // gradient : percent of currentFrame between the frame inf and the frame sup
  46591. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46592. // check for easingFunction and correction of gradient
  46593. var easingFunction = this._animation.getEasingFunction();
  46594. if (easingFunction != null) {
  46595. gradient = easingFunction.ease(gradient);
  46596. }
  46597. switch (this._animation.dataType) {
  46598. // Float
  46599. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46600. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46601. switch (loopMode) {
  46602. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46603. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46604. return floatValue;
  46605. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46606. return offsetValue * repeatCount + floatValue;
  46607. }
  46608. break;
  46609. // Quaternion
  46610. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46611. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46612. switch (loopMode) {
  46613. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46614. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46615. return quatValue;
  46616. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46617. return quatValue.add(offsetValue.scale(repeatCount));
  46618. }
  46619. return quatValue;
  46620. // Vector3
  46621. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46622. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46623. switch (loopMode) {
  46624. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46625. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46626. return vec3Value;
  46627. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46628. return vec3Value.add(offsetValue.scale(repeatCount));
  46629. }
  46630. // Vector2
  46631. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46632. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46633. switch (loopMode) {
  46634. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46635. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46636. return vec2Value;
  46637. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46638. return vec2Value.add(offsetValue.scale(repeatCount));
  46639. }
  46640. // Size
  46641. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46642. switch (loopMode) {
  46643. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46644. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46645. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46646. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46647. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46648. }
  46649. // Color3
  46650. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46651. switch (loopMode) {
  46652. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46653. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46654. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46655. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46656. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46657. }
  46658. // Matrix
  46659. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46660. switch (loopMode) {
  46661. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46662. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46663. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46664. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46665. }
  46666. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46667. return startValue;
  46668. }
  46669. default:
  46670. break;
  46671. }
  46672. break;
  46673. }
  46674. }
  46675. return this._getKeyValue(keys[keys.length - 1].value);
  46676. };
  46677. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46678. if (blend === void 0) { blend = false; }
  46679. // Set value
  46680. var path;
  46681. var destination;
  46682. var targetPropertyPath = this._animation.targetPropertyPath;
  46683. if (targetPropertyPath.length > 1) {
  46684. var property = this._target[targetPropertyPath[0]];
  46685. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46686. property = property[targetPropertyPath[index]];
  46687. }
  46688. path = targetPropertyPath[targetPropertyPath.length - 1];
  46689. destination = property;
  46690. }
  46691. else {
  46692. path = targetPropertyPath[0];
  46693. destination = this._target;
  46694. }
  46695. // Blending
  46696. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46697. if (!this._originalBlendValue) {
  46698. if (destination[path].clone) {
  46699. this._originalBlendValue = destination[path].clone();
  46700. }
  46701. else {
  46702. this._originalBlendValue = destination[path];
  46703. }
  46704. }
  46705. if (this._originalBlendValue.prototype) {
  46706. if (this._originalBlendValue.prototype.Lerp) {
  46707. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46708. }
  46709. else {
  46710. destination[path] = currentValue;
  46711. }
  46712. }
  46713. else if (this._originalBlendValue.m) {
  46714. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46715. }
  46716. else {
  46717. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46718. }
  46719. this._blendingFactor += this._animation.blendingSpeed;
  46720. }
  46721. else {
  46722. destination[path] = currentValue;
  46723. }
  46724. if (this._target.markAsDirty) {
  46725. this._target.markAsDirty(this._animation.targetProperty);
  46726. }
  46727. };
  46728. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46729. var keys = this._animation.getKeys();
  46730. if (frame < keys[0].frame) {
  46731. frame = keys[0].frame;
  46732. }
  46733. else if (frame > keys[keys.length - 1].frame) {
  46734. frame = keys[keys.length - 1].frame;
  46735. }
  46736. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46737. this.setValue(currentValue);
  46738. };
  46739. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46740. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46741. this._ratioOffset = this._previousRatio - newRatio;
  46742. };
  46743. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46744. if (blend === void 0) { blend = false; }
  46745. var targetPropertyPath = this._animation.targetPropertyPath;
  46746. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46747. this._stopped = true;
  46748. return false;
  46749. }
  46750. var returnValue = true;
  46751. var keys = this._animation.getKeys();
  46752. // Adding a start key at frame 0 if missing
  46753. if (keys[0].frame !== 0) {
  46754. var newKey = { frame: 0, value: keys[0].value };
  46755. keys.splice(0, 0, newKey);
  46756. }
  46757. // Check limits
  46758. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46759. from = keys[0].frame;
  46760. }
  46761. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46762. to = keys[keys.length - 1].frame;
  46763. }
  46764. //to and from cannot be the same key
  46765. if (from === to) {
  46766. if (from > keys[0].frame) {
  46767. from--;
  46768. }
  46769. else if (to < keys[keys.length - 1].frame) {
  46770. to++;
  46771. }
  46772. }
  46773. // Compute ratio
  46774. var range = to - from;
  46775. var offsetValue;
  46776. // ratio represents the frame delta between from and to
  46777. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46778. var highLimitValue = 0;
  46779. this._previousDelay = delay;
  46780. this._previousRatio = ratio;
  46781. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46782. returnValue = false;
  46783. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46784. }
  46785. else {
  46786. // Get max value if required
  46787. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46788. var keyOffset = to.toString() + from.toString();
  46789. if (!this._offsetsCache[keyOffset]) {
  46790. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46791. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46792. switch (this._animation.dataType) {
  46793. // Float
  46794. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46795. this._offsetsCache[keyOffset] = toValue - fromValue;
  46796. break;
  46797. // Quaternion
  46798. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46799. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46800. break;
  46801. // Vector3
  46802. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46803. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46804. // Vector2
  46805. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46806. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46807. // Size
  46808. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46809. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46810. // Color3
  46811. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46812. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46813. default:
  46814. break;
  46815. }
  46816. this._highLimitsCache[keyOffset] = toValue;
  46817. }
  46818. highLimitValue = this._highLimitsCache[keyOffset];
  46819. offsetValue = this._offsetsCache[keyOffset];
  46820. }
  46821. }
  46822. if (offsetValue === undefined) {
  46823. switch (this._animation.dataType) {
  46824. // Float
  46825. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46826. offsetValue = 0;
  46827. break;
  46828. // Quaternion
  46829. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46830. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46831. break;
  46832. // Vector3
  46833. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46834. offsetValue = BABYLON.Vector3.Zero();
  46835. break;
  46836. // Vector2
  46837. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46838. offsetValue = BABYLON.Vector2.Zero();
  46839. break;
  46840. // Size
  46841. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46842. offsetValue = BABYLON.Size.Zero();
  46843. break;
  46844. // Color3
  46845. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46846. offsetValue = BABYLON.Color3.Black();
  46847. }
  46848. }
  46849. // Compute value
  46850. var repeatCount = (ratio / range) >> 0;
  46851. var currentFrame = returnValue ? from + ratio % range : to;
  46852. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46853. // Set value
  46854. this.setValue(currentValue);
  46855. // Check events
  46856. var events = this._animation.getEvents();
  46857. for (var index = 0; index < events.length; index++) {
  46858. // Make sure current frame has passed event frame and that event frame is within the current range
  46859. // Also, handle both forward and reverse animations
  46860. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46861. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46862. var event = events[index];
  46863. if (!event.isDone) {
  46864. // If event should be done only once, remove it.
  46865. if (event.onlyOnce) {
  46866. events.splice(index, 1);
  46867. index--;
  46868. }
  46869. event.isDone = true;
  46870. event.action();
  46871. } // Don't do anything if the event has already be done.
  46872. }
  46873. else if (events[index].isDone && !events[index].onlyOnce) {
  46874. // reset event, the animation is looping
  46875. events[index].isDone = false;
  46876. }
  46877. }
  46878. if (!returnValue) {
  46879. this._stopped = true;
  46880. }
  46881. return returnValue;
  46882. };
  46883. return RuntimeAnimation;
  46884. }());
  46885. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46886. })(BABYLON || (BABYLON = {}));
  46887. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46888. var BABYLON;
  46889. (function (BABYLON) {
  46890. var Animatable = /** @class */ (function () {
  46891. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46892. if (fromFrame === void 0) { fromFrame = 0; }
  46893. if (toFrame === void 0) { toFrame = 100; }
  46894. if (loopAnimation === void 0) { loopAnimation = false; }
  46895. if (speedRatio === void 0) { speedRatio = 1.0; }
  46896. this.target = target;
  46897. this.fromFrame = fromFrame;
  46898. this.toFrame = toFrame;
  46899. this.loopAnimation = loopAnimation;
  46900. this.onAnimationEnd = onAnimationEnd;
  46901. this._localDelayOffset = null;
  46902. this._pausedDelay = null;
  46903. this._runtimeAnimations = new Array();
  46904. this._paused = false;
  46905. this._speedRatio = 1;
  46906. this.animationStarted = false;
  46907. if (animations) {
  46908. this.appendAnimations(target, animations);
  46909. }
  46910. this._speedRatio = speedRatio;
  46911. this._scene = scene;
  46912. scene._activeAnimatables.push(this);
  46913. }
  46914. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46915. get: function () {
  46916. return this._speedRatio;
  46917. },
  46918. set: function (value) {
  46919. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46920. var animation = this._runtimeAnimations[index];
  46921. animation._prepareForSpeedRatioChange(value);
  46922. }
  46923. this._speedRatio = value;
  46924. },
  46925. enumerable: true,
  46926. configurable: true
  46927. });
  46928. // Methods
  46929. Animatable.prototype.getAnimations = function () {
  46930. return this._runtimeAnimations;
  46931. };
  46932. Animatable.prototype.appendAnimations = function (target, animations) {
  46933. for (var index = 0; index < animations.length; index++) {
  46934. var animation = animations[index];
  46935. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46936. }
  46937. };
  46938. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46939. var runtimeAnimations = this._runtimeAnimations;
  46940. for (var index = 0; index < runtimeAnimations.length; index++) {
  46941. if (runtimeAnimations[index].animation.targetProperty === property) {
  46942. return runtimeAnimations[index].animation;
  46943. }
  46944. }
  46945. return null;
  46946. };
  46947. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46948. var runtimeAnimations = this._runtimeAnimations;
  46949. for (var index = 0; index < runtimeAnimations.length; index++) {
  46950. if (runtimeAnimations[index].animation.targetProperty === property) {
  46951. return runtimeAnimations[index];
  46952. }
  46953. }
  46954. return null;
  46955. };
  46956. Animatable.prototype.reset = function () {
  46957. var runtimeAnimations = this._runtimeAnimations;
  46958. for (var index = 0; index < runtimeAnimations.length; index++) {
  46959. runtimeAnimations[index].reset();
  46960. }
  46961. // Reset to original value
  46962. for (index = 0; index < runtimeAnimations.length; index++) {
  46963. var animation = runtimeAnimations[index];
  46964. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46965. }
  46966. this._localDelayOffset = null;
  46967. this._pausedDelay = null;
  46968. };
  46969. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46970. var runtimeAnimations = this._runtimeAnimations;
  46971. for (var index = 0; index < runtimeAnimations.length; index++) {
  46972. runtimeAnimations[index].animation.enableBlending = true;
  46973. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46974. }
  46975. };
  46976. Animatable.prototype.disableBlending = function () {
  46977. var runtimeAnimations = this._runtimeAnimations;
  46978. for (var index = 0; index < runtimeAnimations.length; index++) {
  46979. runtimeAnimations[index].animation.enableBlending = false;
  46980. }
  46981. };
  46982. Animatable.prototype.goToFrame = function (frame) {
  46983. var runtimeAnimations = this._runtimeAnimations;
  46984. if (runtimeAnimations[0]) {
  46985. var fps = runtimeAnimations[0].animation.framePerSecond;
  46986. var currentFrame = runtimeAnimations[0].currentFrame;
  46987. var adjustTime = frame - currentFrame;
  46988. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  46989. if (this._localDelayOffset === null) {
  46990. this._localDelayOffset = 0;
  46991. }
  46992. this._localDelayOffset -= delay;
  46993. }
  46994. for (var index = 0; index < runtimeAnimations.length; index++) {
  46995. runtimeAnimations[index].goToFrame(frame);
  46996. }
  46997. };
  46998. Animatable.prototype.pause = function () {
  46999. if (this._paused) {
  47000. return;
  47001. }
  47002. this._paused = true;
  47003. };
  47004. Animatable.prototype.restart = function () {
  47005. this._paused = false;
  47006. };
  47007. Animatable.prototype.stop = function (animationName) {
  47008. if (animationName) {
  47009. var idx = this._scene._activeAnimatables.indexOf(this);
  47010. if (idx > -1) {
  47011. var runtimeAnimations = this._runtimeAnimations;
  47012. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47013. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47014. continue;
  47015. }
  47016. runtimeAnimations[index].dispose();
  47017. runtimeAnimations.splice(index, 1);
  47018. }
  47019. if (runtimeAnimations.length == 0) {
  47020. this._scene._activeAnimatables.splice(idx, 1);
  47021. if (this.onAnimationEnd) {
  47022. this.onAnimationEnd();
  47023. }
  47024. }
  47025. }
  47026. }
  47027. else {
  47028. var index = this._scene._activeAnimatables.indexOf(this);
  47029. if (index > -1) {
  47030. this._scene._activeAnimatables.splice(index, 1);
  47031. var runtimeAnimations = this._runtimeAnimations;
  47032. for (var index = 0; index < runtimeAnimations.length; index++) {
  47033. runtimeAnimations[index].dispose();
  47034. }
  47035. if (this.onAnimationEnd) {
  47036. this.onAnimationEnd();
  47037. }
  47038. }
  47039. }
  47040. };
  47041. Animatable.prototype._animate = function (delay) {
  47042. if (this._paused) {
  47043. this.animationStarted = false;
  47044. if (this._pausedDelay === null) {
  47045. this._pausedDelay = delay;
  47046. }
  47047. return true;
  47048. }
  47049. if (this._localDelayOffset === null) {
  47050. this._localDelayOffset = delay;
  47051. this._pausedDelay = null;
  47052. }
  47053. else if (this._pausedDelay !== null) {
  47054. this._localDelayOffset += delay - this._pausedDelay;
  47055. this._pausedDelay = null;
  47056. }
  47057. // Animating
  47058. var running = false;
  47059. var runtimeAnimations = this._runtimeAnimations;
  47060. var index;
  47061. for (index = 0; index < runtimeAnimations.length; index++) {
  47062. var animation = runtimeAnimations[index];
  47063. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47064. running = running || isRunning;
  47065. }
  47066. this.animationStarted = running;
  47067. if (!running) {
  47068. // Remove from active animatables
  47069. index = this._scene._activeAnimatables.indexOf(this);
  47070. this._scene._activeAnimatables.splice(index, 1);
  47071. // Dispose all runtime animations
  47072. for (index = 0; index < runtimeAnimations.length; index++) {
  47073. runtimeAnimations[index].dispose();
  47074. }
  47075. }
  47076. if (!running && this.onAnimationEnd) {
  47077. this.onAnimationEnd();
  47078. this.onAnimationEnd = null;
  47079. }
  47080. return running;
  47081. };
  47082. return Animatable;
  47083. }());
  47084. BABYLON.Animatable = Animatable;
  47085. })(BABYLON || (BABYLON = {}));
  47086. //# sourceMappingURL=babylon.animatable.js.map
  47087. var BABYLON;
  47088. (function (BABYLON) {
  47089. var EasingFunction = /** @class */ (function () {
  47090. function EasingFunction() {
  47091. // Properties
  47092. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47093. }
  47094. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47095. get: function () {
  47096. return EasingFunction._EASINGMODE_EASEIN;
  47097. },
  47098. enumerable: true,
  47099. configurable: true
  47100. });
  47101. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47102. get: function () {
  47103. return EasingFunction._EASINGMODE_EASEOUT;
  47104. },
  47105. enumerable: true,
  47106. configurable: true
  47107. });
  47108. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47109. get: function () {
  47110. return EasingFunction._EASINGMODE_EASEINOUT;
  47111. },
  47112. enumerable: true,
  47113. configurable: true
  47114. });
  47115. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47116. var n = Math.min(Math.max(easingMode, 0), 2);
  47117. this._easingMode = n;
  47118. };
  47119. EasingFunction.prototype.getEasingMode = function () {
  47120. return this._easingMode;
  47121. };
  47122. EasingFunction.prototype.easeInCore = function (gradient) {
  47123. throw new Error('You must implement this method');
  47124. };
  47125. EasingFunction.prototype.ease = function (gradient) {
  47126. switch (this._easingMode) {
  47127. case EasingFunction.EASINGMODE_EASEIN:
  47128. return this.easeInCore(gradient);
  47129. case EasingFunction.EASINGMODE_EASEOUT:
  47130. return (1 - this.easeInCore(1 - gradient));
  47131. }
  47132. if (gradient >= 0.5) {
  47133. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47134. }
  47135. return (this.easeInCore(gradient * 2) * 0.5);
  47136. };
  47137. //Statics
  47138. EasingFunction._EASINGMODE_EASEIN = 0;
  47139. EasingFunction._EASINGMODE_EASEOUT = 1;
  47140. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47141. return EasingFunction;
  47142. }());
  47143. BABYLON.EasingFunction = EasingFunction;
  47144. var CircleEase = /** @class */ (function (_super) {
  47145. __extends(CircleEase, _super);
  47146. function CircleEase() {
  47147. return _super !== null && _super.apply(this, arguments) || this;
  47148. }
  47149. CircleEase.prototype.easeInCore = function (gradient) {
  47150. gradient = Math.max(0, Math.min(1, gradient));
  47151. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47152. };
  47153. return CircleEase;
  47154. }(EasingFunction));
  47155. BABYLON.CircleEase = CircleEase;
  47156. var BackEase = /** @class */ (function (_super) {
  47157. __extends(BackEase, _super);
  47158. function BackEase(amplitude) {
  47159. if (amplitude === void 0) { amplitude = 1; }
  47160. var _this = _super.call(this) || this;
  47161. _this.amplitude = amplitude;
  47162. return _this;
  47163. }
  47164. BackEase.prototype.easeInCore = function (gradient) {
  47165. var num = Math.max(0, this.amplitude);
  47166. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47167. };
  47168. return BackEase;
  47169. }(EasingFunction));
  47170. BABYLON.BackEase = BackEase;
  47171. var BounceEase = /** @class */ (function (_super) {
  47172. __extends(BounceEase, _super);
  47173. function BounceEase(bounces, bounciness) {
  47174. if (bounces === void 0) { bounces = 3; }
  47175. if (bounciness === void 0) { bounciness = 2; }
  47176. var _this = _super.call(this) || this;
  47177. _this.bounces = bounces;
  47178. _this.bounciness = bounciness;
  47179. return _this;
  47180. }
  47181. BounceEase.prototype.easeInCore = function (gradient) {
  47182. var y = Math.max(0.0, this.bounces);
  47183. var bounciness = this.bounciness;
  47184. if (bounciness <= 1.0) {
  47185. bounciness = 1.001;
  47186. }
  47187. var num9 = Math.pow(bounciness, y);
  47188. var num5 = 1.0 - bounciness;
  47189. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47190. var num15 = gradient * num4;
  47191. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47192. var num3 = Math.floor(num65);
  47193. var num13 = num3 + 1.0;
  47194. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47195. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47196. var num7 = (num8 + num12) * 0.5;
  47197. var num6 = gradient - num7;
  47198. var num2 = num7 - num8;
  47199. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47200. };
  47201. return BounceEase;
  47202. }(EasingFunction));
  47203. BABYLON.BounceEase = BounceEase;
  47204. var CubicEase = /** @class */ (function (_super) {
  47205. __extends(CubicEase, _super);
  47206. function CubicEase() {
  47207. return _super !== null && _super.apply(this, arguments) || this;
  47208. }
  47209. CubicEase.prototype.easeInCore = function (gradient) {
  47210. return (gradient * gradient * gradient);
  47211. };
  47212. return CubicEase;
  47213. }(EasingFunction));
  47214. BABYLON.CubicEase = CubicEase;
  47215. var ElasticEase = /** @class */ (function (_super) {
  47216. __extends(ElasticEase, _super);
  47217. function ElasticEase(oscillations, springiness) {
  47218. if (oscillations === void 0) { oscillations = 3; }
  47219. if (springiness === void 0) { springiness = 3; }
  47220. var _this = _super.call(this) || this;
  47221. _this.oscillations = oscillations;
  47222. _this.springiness = springiness;
  47223. return _this;
  47224. }
  47225. ElasticEase.prototype.easeInCore = function (gradient) {
  47226. var num2;
  47227. var num3 = Math.max(0.0, this.oscillations);
  47228. var num = Math.max(0.0, this.springiness);
  47229. if (num == 0) {
  47230. num2 = gradient;
  47231. }
  47232. else {
  47233. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47234. }
  47235. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47236. };
  47237. return ElasticEase;
  47238. }(EasingFunction));
  47239. BABYLON.ElasticEase = ElasticEase;
  47240. var ExponentialEase = /** @class */ (function (_super) {
  47241. __extends(ExponentialEase, _super);
  47242. function ExponentialEase(exponent) {
  47243. if (exponent === void 0) { exponent = 2; }
  47244. var _this = _super.call(this) || this;
  47245. _this.exponent = exponent;
  47246. return _this;
  47247. }
  47248. ExponentialEase.prototype.easeInCore = function (gradient) {
  47249. if (this.exponent <= 0) {
  47250. return gradient;
  47251. }
  47252. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47253. };
  47254. return ExponentialEase;
  47255. }(EasingFunction));
  47256. BABYLON.ExponentialEase = ExponentialEase;
  47257. var PowerEase = /** @class */ (function (_super) {
  47258. __extends(PowerEase, _super);
  47259. function PowerEase(power) {
  47260. if (power === void 0) { power = 2; }
  47261. var _this = _super.call(this) || this;
  47262. _this.power = power;
  47263. return _this;
  47264. }
  47265. PowerEase.prototype.easeInCore = function (gradient) {
  47266. var y = Math.max(0.0, this.power);
  47267. return Math.pow(gradient, y);
  47268. };
  47269. return PowerEase;
  47270. }(EasingFunction));
  47271. BABYLON.PowerEase = PowerEase;
  47272. var QuadraticEase = /** @class */ (function (_super) {
  47273. __extends(QuadraticEase, _super);
  47274. function QuadraticEase() {
  47275. return _super !== null && _super.apply(this, arguments) || this;
  47276. }
  47277. QuadraticEase.prototype.easeInCore = function (gradient) {
  47278. return (gradient * gradient);
  47279. };
  47280. return QuadraticEase;
  47281. }(EasingFunction));
  47282. BABYLON.QuadraticEase = QuadraticEase;
  47283. var QuarticEase = /** @class */ (function (_super) {
  47284. __extends(QuarticEase, _super);
  47285. function QuarticEase() {
  47286. return _super !== null && _super.apply(this, arguments) || this;
  47287. }
  47288. QuarticEase.prototype.easeInCore = function (gradient) {
  47289. return (gradient * gradient * gradient * gradient);
  47290. };
  47291. return QuarticEase;
  47292. }(EasingFunction));
  47293. BABYLON.QuarticEase = QuarticEase;
  47294. var QuinticEase = /** @class */ (function (_super) {
  47295. __extends(QuinticEase, _super);
  47296. function QuinticEase() {
  47297. return _super !== null && _super.apply(this, arguments) || this;
  47298. }
  47299. QuinticEase.prototype.easeInCore = function (gradient) {
  47300. return (gradient * gradient * gradient * gradient * gradient);
  47301. };
  47302. return QuinticEase;
  47303. }(EasingFunction));
  47304. BABYLON.QuinticEase = QuinticEase;
  47305. var SineEase = /** @class */ (function (_super) {
  47306. __extends(SineEase, _super);
  47307. function SineEase() {
  47308. return _super !== null && _super.apply(this, arguments) || this;
  47309. }
  47310. SineEase.prototype.easeInCore = function (gradient) {
  47311. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47312. };
  47313. return SineEase;
  47314. }(EasingFunction));
  47315. BABYLON.SineEase = SineEase;
  47316. var BezierCurveEase = /** @class */ (function (_super) {
  47317. __extends(BezierCurveEase, _super);
  47318. function BezierCurveEase(x1, y1, x2, y2) {
  47319. if (x1 === void 0) { x1 = 0; }
  47320. if (y1 === void 0) { y1 = 0; }
  47321. if (x2 === void 0) { x2 = 1; }
  47322. if (y2 === void 0) { y2 = 1; }
  47323. var _this = _super.call(this) || this;
  47324. _this.x1 = x1;
  47325. _this.y1 = y1;
  47326. _this.x2 = x2;
  47327. _this.y2 = y2;
  47328. return _this;
  47329. }
  47330. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47331. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47332. };
  47333. return BezierCurveEase;
  47334. }(EasingFunction));
  47335. BABYLON.BezierCurveEase = BezierCurveEase;
  47336. })(BABYLON || (BABYLON = {}));
  47337. //# sourceMappingURL=babylon.easing.js.map
  47338. var BABYLON;
  47339. (function (BABYLON) {
  47340. var Condition = /** @class */ (function () {
  47341. function Condition(actionManager) {
  47342. this._actionManager = actionManager;
  47343. }
  47344. Condition.prototype.isValid = function () {
  47345. return true;
  47346. };
  47347. Condition.prototype._getProperty = function (propertyPath) {
  47348. return this._actionManager._getProperty(propertyPath);
  47349. };
  47350. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47351. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47352. };
  47353. Condition.prototype.serialize = function () {
  47354. };
  47355. Condition.prototype._serialize = function (serializedCondition) {
  47356. return {
  47357. type: 2,
  47358. children: [],
  47359. name: serializedCondition.name,
  47360. properties: serializedCondition.properties
  47361. };
  47362. };
  47363. return Condition;
  47364. }());
  47365. BABYLON.Condition = Condition;
  47366. var ValueCondition = /** @class */ (function (_super) {
  47367. __extends(ValueCondition, _super);
  47368. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47369. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47370. var _this = _super.call(this, actionManager) || this;
  47371. _this.propertyPath = propertyPath;
  47372. _this.value = value;
  47373. _this.operator = operator;
  47374. _this._target = target;
  47375. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47376. _this._property = _this._getProperty(_this.propertyPath);
  47377. return _this;
  47378. }
  47379. Object.defineProperty(ValueCondition, "IsEqual", {
  47380. get: function () {
  47381. return ValueCondition._IsEqual;
  47382. },
  47383. enumerable: true,
  47384. configurable: true
  47385. });
  47386. Object.defineProperty(ValueCondition, "IsDifferent", {
  47387. get: function () {
  47388. return ValueCondition._IsDifferent;
  47389. },
  47390. enumerable: true,
  47391. configurable: true
  47392. });
  47393. Object.defineProperty(ValueCondition, "IsGreater", {
  47394. get: function () {
  47395. return ValueCondition._IsGreater;
  47396. },
  47397. enumerable: true,
  47398. configurable: true
  47399. });
  47400. Object.defineProperty(ValueCondition, "IsLesser", {
  47401. get: function () {
  47402. return ValueCondition._IsLesser;
  47403. },
  47404. enumerable: true,
  47405. configurable: true
  47406. });
  47407. // Methods
  47408. ValueCondition.prototype.isValid = function () {
  47409. switch (this.operator) {
  47410. case ValueCondition.IsGreater:
  47411. return this._effectiveTarget[this._property] > this.value;
  47412. case ValueCondition.IsLesser:
  47413. return this._effectiveTarget[this._property] < this.value;
  47414. case ValueCondition.IsEqual:
  47415. case ValueCondition.IsDifferent:
  47416. var check;
  47417. if (this.value.equals) {
  47418. check = this.value.equals(this._effectiveTarget[this._property]);
  47419. }
  47420. else {
  47421. check = this.value === this._effectiveTarget[this._property];
  47422. }
  47423. return this.operator === ValueCondition.IsEqual ? check : !check;
  47424. }
  47425. return false;
  47426. };
  47427. ValueCondition.prototype.serialize = function () {
  47428. return this._serialize({
  47429. name: "ValueCondition",
  47430. properties: [
  47431. BABYLON.Action._GetTargetProperty(this._target),
  47432. { name: "propertyPath", value: this.propertyPath },
  47433. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47434. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47435. ]
  47436. });
  47437. };
  47438. ValueCondition.GetOperatorName = function (operator) {
  47439. switch (operator) {
  47440. case ValueCondition._IsEqual: return "IsEqual";
  47441. case ValueCondition._IsDifferent: return "IsDifferent";
  47442. case ValueCondition._IsGreater: return "IsGreater";
  47443. case ValueCondition._IsLesser: return "IsLesser";
  47444. default: return "";
  47445. }
  47446. };
  47447. // Statics
  47448. ValueCondition._IsEqual = 0;
  47449. ValueCondition._IsDifferent = 1;
  47450. ValueCondition._IsGreater = 2;
  47451. ValueCondition._IsLesser = 3;
  47452. return ValueCondition;
  47453. }(Condition));
  47454. BABYLON.ValueCondition = ValueCondition;
  47455. var PredicateCondition = /** @class */ (function (_super) {
  47456. __extends(PredicateCondition, _super);
  47457. function PredicateCondition(actionManager, predicate) {
  47458. var _this = _super.call(this, actionManager) || this;
  47459. _this.predicate = predicate;
  47460. return _this;
  47461. }
  47462. PredicateCondition.prototype.isValid = function () {
  47463. return this.predicate();
  47464. };
  47465. return PredicateCondition;
  47466. }(Condition));
  47467. BABYLON.PredicateCondition = PredicateCondition;
  47468. var StateCondition = /** @class */ (function (_super) {
  47469. __extends(StateCondition, _super);
  47470. function StateCondition(actionManager, target, value) {
  47471. var _this = _super.call(this, actionManager) || this;
  47472. _this.value = value;
  47473. _this._target = target;
  47474. return _this;
  47475. }
  47476. // Methods
  47477. StateCondition.prototype.isValid = function () {
  47478. return this._target.state === this.value;
  47479. };
  47480. StateCondition.prototype.serialize = function () {
  47481. return this._serialize({
  47482. name: "StateCondition",
  47483. properties: [
  47484. BABYLON.Action._GetTargetProperty(this._target),
  47485. { name: "value", value: this.value }
  47486. ]
  47487. });
  47488. };
  47489. return StateCondition;
  47490. }(Condition));
  47491. BABYLON.StateCondition = StateCondition;
  47492. })(BABYLON || (BABYLON = {}));
  47493. //# sourceMappingURL=babylon.condition.js.map
  47494. var BABYLON;
  47495. (function (BABYLON) {
  47496. var Action = /** @class */ (function () {
  47497. function Action(triggerOptions, condition) {
  47498. this.triggerOptions = triggerOptions;
  47499. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47500. if (triggerOptions.parameter) {
  47501. this.trigger = triggerOptions.trigger;
  47502. this._triggerParameter = triggerOptions.parameter;
  47503. }
  47504. else {
  47505. this.trigger = triggerOptions;
  47506. }
  47507. this._nextActiveAction = this;
  47508. this._condition = condition;
  47509. }
  47510. // Methods
  47511. Action.prototype._prepare = function () {
  47512. };
  47513. Action.prototype.getTriggerParameter = function () {
  47514. return this._triggerParameter;
  47515. };
  47516. Action.prototype._executeCurrent = function (evt) {
  47517. if (this._nextActiveAction._condition) {
  47518. var condition = this._nextActiveAction._condition;
  47519. var currentRenderId = this._actionManager.getScene().getRenderId();
  47520. // We cache the current evaluation for the current frame
  47521. if (condition._evaluationId === currentRenderId) {
  47522. if (!condition._currentResult) {
  47523. return;
  47524. }
  47525. }
  47526. else {
  47527. condition._evaluationId = currentRenderId;
  47528. if (!condition.isValid()) {
  47529. condition._currentResult = false;
  47530. return;
  47531. }
  47532. condition._currentResult = true;
  47533. }
  47534. }
  47535. this.onBeforeExecuteObservable.notifyObservers(this);
  47536. this._nextActiveAction.execute(evt);
  47537. this.skipToNextActiveAction();
  47538. };
  47539. Action.prototype.execute = function (evt) {
  47540. };
  47541. Action.prototype.skipToNextActiveAction = function () {
  47542. if (this._nextActiveAction._child) {
  47543. if (!this._nextActiveAction._child._actionManager) {
  47544. this._nextActiveAction._child._actionManager = this._actionManager;
  47545. }
  47546. this._nextActiveAction = this._nextActiveAction._child;
  47547. }
  47548. else {
  47549. this._nextActiveAction = this;
  47550. }
  47551. };
  47552. Action.prototype.then = function (action) {
  47553. this._child = action;
  47554. action._actionManager = this._actionManager;
  47555. action._prepare();
  47556. return action;
  47557. };
  47558. Action.prototype._getProperty = function (propertyPath) {
  47559. return this._actionManager._getProperty(propertyPath);
  47560. };
  47561. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47562. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47563. };
  47564. Action.prototype.serialize = function (parent) {
  47565. };
  47566. // Called by BABYLON.Action objects in serialize(...). Internal use
  47567. Action.prototype._serialize = function (serializedAction, parent) {
  47568. var serializationObject = {
  47569. type: 1,
  47570. children: [],
  47571. name: serializedAction.name,
  47572. properties: serializedAction.properties || []
  47573. };
  47574. // Serialize child
  47575. if (this._child) {
  47576. this._child.serialize(serializationObject);
  47577. }
  47578. // Check if "this" has a condition
  47579. if (this._condition) {
  47580. var serializedCondition = this._condition.serialize();
  47581. serializedCondition.children.push(serializationObject);
  47582. if (parent) {
  47583. parent.children.push(serializedCondition);
  47584. }
  47585. return serializedCondition;
  47586. }
  47587. if (parent) {
  47588. parent.children.push(serializationObject);
  47589. }
  47590. return serializationObject;
  47591. };
  47592. Action._SerializeValueAsString = function (value) {
  47593. if (typeof value === "number") {
  47594. return value.toString();
  47595. }
  47596. if (typeof value === "boolean") {
  47597. return value ? "true" : "false";
  47598. }
  47599. if (value instanceof BABYLON.Vector2) {
  47600. return value.x + ", " + value.y;
  47601. }
  47602. if (value instanceof BABYLON.Vector3) {
  47603. return value.x + ", " + value.y + ", " + value.z;
  47604. }
  47605. if (value instanceof BABYLON.Color3) {
  47606. return value.r + ", " + value.g + ", " + value.b;
  47607. }
  47608. if (value instanceof BABYLON.Color4) {
  47609. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47610. }
  47611. return value; // string
  47612. };
  47613. Action._GetTargetProperty = function (target) {
  47614. return {
  47615. name: "target",
  47616. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47617. : target instanceof BABYLON.Light ? "LightProperties"
  47618. : target instanceof BABYLON.Camera ? "CameraProperties"
  47619. : "SceneProperties",
  47620. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47621. };
  47622. };
  47623. return Action;
  47624. }());
  47625. BABYLON.Action = Action;
  47626. })(BABYLON || (BABYLON = {}));
  47627. //# sourceMappingURL=babylon.action.js.map
  47628. var BABYLON;
  47629. (function (BABYLON) {
  47630. /**
  47631. * ActionEvent is the event beint sent when an action is triggered.
  47632. */
  47633. var ActionEvent = /** @class */ (function () {
  47634. /**
  47635. * @param source The mesh or sprite that triggered the action.
  47636. * @param pointerX The X mouse cursor position at the time of the event
  47637. * @param pointerY The Y mouse cursor position at the time of the event
  47638. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47639. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47640. */
  47641. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47642. this.source = source;
  47643. this.pointerX = pointerX;
  47644. this.pointerY = pointerY;
  47645. this.meshUnderPointer = meshUnderPointer;
  47646. this.sourceEvent = sourceEvent;
  47647. this.additionalData = additionalData;
  47648. }
  47649. /**
  47650. * Helper function to auto-create an ActionEvent from a source mesh.
  47651. * @param source The source mesh that triggered the event
  47652. * @param evt {Event} The original (browser) event
  47653. */
  47654. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47655. var scene = source.getScene();
  47656. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47657. };
  47658. /**
  47659. * Helper function to auto-create an ActionEvent from a source mesh.
  47660. * @param source The source sprite that triggered the event
  47661. * @param scene Scene associated with the sprite
  47662. * @param evt {Event} The original (browser) event
  47663. */
  47664. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47665. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47666. };
  47667. /**
  47668. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47669. * @param scene the scene where the event occurred
  47670. * @param evt {Event} The original (browser) event
  47671. */
  47672. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47673. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47674. };
  47675. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47676. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47677. };
  47678. return ActionEvent;
  47679. }());
  47680. BABYLON.ActionEvent = ActionEvent;
  47681. /**
  47682. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47683. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47684. */
  47685. var ActionManager = /** @class */ (function () {
  47686. function ActionManager(scene) {
  47687. // Members
  47688. this.actions = new Array();
  47689. this.hoverCursor = '';
  47690. this._scene = scene;
  47691. scene._actionManagers.push(this);
  47692. }
  47693. Object.defineProperty(ActionManager, "NothingTrigger", {
  47694. get: function () {
  47695. return ActionManager._NothingTrigger;
  47696. },
  47697. enumerable: true,
  47698. configurable: true
  47699. });
  47700. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47701. get: function () {
  47702. return ActionManager._OnPickTrigger;
  47703. },
  47704. enumerable: true,
  47705. configurable: true
  47706. });
  47707. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47708. get: function () {
  47709. return ActionManager._OnLeftPickTrigger;
  47710. },
  47711. enumerable: true,
  47712. configurable: true
  47713. });
  47714. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47715. get: function () {
  47716. return ActionManager._OnRightPickTrigger;
  47717. },
  47718. enumerable: true,
  47719. configurable: true
  47720. });
  47721. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47722. get: function () {
  47723. return ActionManager._OnCenterPickTrigger;
  47724. },
  47725. enumerable: true,
  47726. configurable: true
  47727. });
  47728. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47729. get: function () {
  47730. return ActionManager._OnPickDownTrigger;
  47731. },
  47732. enumerable: true,
  47733. configurable: true
  47734. });
  47735. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47736. get: function () {
  47737. return ActionManager._OnDoublePickTrigger;
  47738. },
  47739. enumerable: true,
  47740. configurable: true
  47741. });
  47742. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47743. get: function () {
  47744. return ActionManager._OnPickUpTrigger;
  47745. },
  47746. enumerable: true,
  47747. configurable: true
  47748. });
  47749. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47750. /// This trigger will only be raised if you also declared a OnPickDown
  47751. get: function () {
  47752. return ActionManager._OnPickOutTrigger;
  47753. },
  47754. enumerable: true,
  47755. configurable: true
  47756. });
  47757. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47758. get: function () {
  47759. return ActionManager._OnLongPressTrigger;
  47760. },
  47761. enumerable: true,
  47762. configurable: true
  47763. });
  47764. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47765. get: function () {
  47766. return ActionManager._OnPointerOverTrigger;
  47767. },
  47768. enumerable: true,
  47769. configurable: true
  47770. });
  47771. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47772. get: function () {
  47773. return ActionManager._OnPointerOutTrigger;
  47774. },
  47775. enumerable: true,
  47776. configurable: true
  47777. });
  47778. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47779. get: function () {
  47780. return ActionManager._OnEveryFrameTrigger;
  47781. },
  47782. enumerable: true,
  47783. configurable: true
  47784. });
  47785. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47786. get: function () {
  47787. return ActionManager._OnIntersectionEnterTrigger;
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47793. get: function () {
  47794. return ActionManager._OnIntersectionExitTrigger;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47800. get: function () {
  47801. return ActionManager._OnKeyDownTrigger;
  47802. },
  47803. enumerable: true,
  47804. configurable: true
  47805. });
  47806. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47807. get: function () {
  47808. return ActionManager._OnKeyUpTrigger;
  47809. },
  47810. enumerable: true,
  47811. configurable: true
  47812. });
  47813. // Methods
  47814. ActionManager.prototype.dispose = function () {
  47815. var index = this._scene._actionManagers.indexOf(this);
  47816. for (var i = 0; i < this.actions.length; i++) {
  47817. var action = this.actions[i];
  47818. ActionManager.Triggers[action.trigger]--;
  47819. if (ActionManager.Triggers[action.trigger] === 0) {
  47820. delete ActionManager.Triggers[action.trigger];
  47821. }
  47822. }
  47823. if (index > -1) {
  47824. this._scene._actionManagers.splice(index, 1);
  47825. }
  47826. };
  47827. ActionManager.prototype.getScene = function () {
  47828. return this._scene;
  47829. };
  47830. /**
  47831. * Does this action manager handles actions of any of the given triggers
  47832. * @param {number[]} triggers - the triggers to be tested
  47833. * @return {boolean} whether one (or more) of the triggers is handeled
  47834. */
  47835. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47836. for (var index = 0; index < this.actions.length; index++) {
  47837. var action = this.actions[index];
  47838. if (triggers.indexOf(action.trigger) > -1) {
  47839. return true;
  47840. }
  47841. }
  47842. return false;
  47843. };
  47844. /**
  47845. * Does this action manager handles actions of a given trigger
  47846. * @param {number} trigger - the trigger to be tested
  47847. * @return {boolean} whether the trigger is handeled
  47848. */
  47849. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47850. for (var index = 0; index < this.actions.length; index++) {
  47851. var action = this.actions[index];
  47852. if (action.trigger === trigger) {
  47853. return true;
  47854. }
  47855. }
  47856. return false;
  47857. };
  47858. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47859. /**
  47860. * Does this action manager has pointer triggers
  47861. * @return {boolean} whether or not it has pointer triggers
  47862. */
  47863. get: function () {
  47864. for (var index = 0; index < this.actions.length; index++) {
  47865. var action = this.actions[index];
  47866. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47867. return true;
  47868. }
  47869. }
  47870. return false;
  47871. },
  47872. enumerable: true,
  47873. configurable: true
  47874. });
  47875. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47876. /**
  47877. * Does this action manager has pick triggers
  47878. * @return {boolean} whether or not it has pick triggers
  47879. */
  47880. get: function () {
  47881. for (var index = 0; index < this.actions.length; index++) {
  47882. var action = this.actions[index];
  47883. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47884. return true;
  47885. }
  47886. }
  47887. return false;
  47888. },
  47889. enumerable: true,
  47890. configurable: true
  47891. });
  47892. Object.defineProperty(ActionManager, "HasTriggers", {
  47893. /**
  47894. * Does exist one action manager with at least one trigger
  47895. * @return {boolean} whether or not it exists one action manager with one trigger
  47896. **/
  47897. get: function () {
  47898. for (var t in ActionManager.Triggers) {
  47899. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47900. return true;
  47901. }
  47902. }
  47903. return false;
  47904. },
  47905. enumerable: true,
  47906. configurable: true
  47907. });
  47908. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47909. /**
  47910. * Does exist one action manager with at least one pick trigger
  47911. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47912. **/
  47913. get: function () {
  47914. for (var t in ActionManager.Triggers) {
  47915. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47916. var t_int = parseInt(t);
  47917. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47918. return true;
  47919. }
  47920. }
  47921. }
  47922. return false;
  47923. },
  47924. enumerable: true,
  47925. configurable: true
  47926. });
  47927. /**
  47928. * Does exist one action manager that handles actions of a given trigger
  47929. * @param {number} trigger - the trigger to be tested
  47930. * @return {boolean} whether the trigger is handeled by at least one action manager
  47931. **/
  47932. ActionManager.HasSpecificTrigger = function (trigger) {
  47933. for (var t in ActionManager.Triggers) {
  47934. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47935. var t_int = parseInt(t);
  47936. if (t_int === trigger) {
  47937. return true;
  47938. }
  47939. }
  47940. }
  47941. return false;
  47942. };
  47943. /**
  47944. * Registers an action to this action manager
  47945. * @param {BABYLON.Action} action - the action to be registered
  47946. * @return {BABYLON.Action} the action amended (prepared) after registration
  47947. */
  47948. ActionManager.prototype.registerAction = function (action) {
  47949. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47950. if (this.getScene().actionManager !== this) {
  47951. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47952. return null;
  47953. }
  47954. }
  47955. this.actions.push(action);
  47956. if (ActionManager.Triggers[action.trigger]) {
  47957. ActionManager.Triggers[action.trigger]++;
  47958. }
  47959. else {
  47960. ActionManager.Triggers[action.trigger] = 1;
  47961. }
  47962. action._actionManager = this;
  47963. action._prepare();
  47964. return action;
  47965. };
  47966. /**
  47967. * Unregisters an action to this action manager
  47968. * @param action The action to be unregistered
  47969. * @return whether the action has been unregistered
  47970. */
  47971. ActionManager.prototype.unregisterAction = function (action) {
  47972. var index = this.actions.indexOf(action);
  47973. if (index !== -1) {
  47974. this.actions.splice(index, 1);
  47975. ActionManager.Triggers[action.trigger] -= 1;
  47976. if (ActionManager.Triggers[action.trigger] === 0) {
  47977. delete ActionManager.Triggers[action.trigger];
  47978. }
  47979. delete action._actionManager;
  47980. return true;
  47981. }
  47982. return false;
  47983. };
  47984. /**
  47985. * Process a specific trigger
  47986. * @param {number} trigger - the trigger to process
  47987. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47988. */
  47989. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47990. for (var index = 0; index < this.actions.length; index++) {
  47991. var action = this.actions[index];
  47992. if (action.trigger === trigger) {
  47993. if (evt) {
  47994. if (trigger === ActionManager.OnKeyUpTrigger
  47995. || trigger === ActionManager.OnKeyDownTrigger) {
  47996. var parameter = action.getTriggerParameter();
  47997. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  47998. if (!parameter.toLowerCase) {
  47999. continue;
  48000. }
  48001. var lowerCase = parameter.toLowerCase();
  48002. if (lowerCase !== evt.sourceEvent.key) {
  48003. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48004. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48005. if (actualkey !== lowerCase) {
  48006. continue;
  48007. }
  48008. }
  48009. }
  48010. }
  48011. }
  48012. action._executeCurrent(evt);
  48013. }
  48014. }
  48015. };
  48016. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48017. var properties = propertyPath.split(".");
  48018. for (var index = 0; index < properties.length - 1; index++) {
  48019. target = target[properties[index]];
  48020. }
  48021. return target;
  48022. };
  48023. ActionManager.prototype._getProperty = function (propertyPath) {
  48024. var properties = propertyPath.split(".");
  48025. return properties[properties.length - 1];
  48026. };
  48027. ActionManager.prototype.serialize = function (name) {
  48028. var root = {
  48029. children: new Array(),
  48030. name: name,
  48031. type: 3,
  48032. properties: new Array() // Empty for root but required
  48033. };
  48034. for (var i = 0; i < this.actions.length; i++) {
  48035. var triggerObject = {
  48036. type: 0,
  48037. children: new Array(),
  48038. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48039. properties: new Array()
  48040. };
  48041. var triggerOptions = this.actions[i].triggerOptions;
  48042. if (triggerOptions && typeof triggerOptions !== "number") {
  48043. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48044. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48045. }
  48046. else {
  48047. var parameter = {};
  48048. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48049. if (triggerOptions.parameter.mesh) {
  48050. parameter._meshId = triggerOptions.parameter.mesh.id;
  48051. }
  48052. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48053. }
  48054. }
  48055. // Serialize child action, recursively
  48056. this.actions[i].serialize(triggerObject);
  48057. // Add serialized trigger
  48058. root.children.push(triggerObject);
  48059. }
  48060. return root;
  48061. };
  48062. ActionManager.Parse = function (parsedActions, object, scene) {
  48063. var actionManager = new ActionManager(scene);
  48064. if (object === null)
  48065. scene.actionManager = actionManager;
  48066. else
  48067. object.actionManager = actionManager;
  48068. // instanciate a new object
  48069. var instanciate = function (name, params) {
  48070. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48071. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48072. newInstance.constructor.apply(newInstance, params);
  48073. return newInstance;
  48074. };
  48075. var parseParameter = function (name, value, target, propertyPath) {
  48076. if (propertyPath === null) {
  48077. // String, boolean or float
  48078. var floatValue = parseFloat(value);
  48079. if (value === "true" || value === "false")
  48080. return value === "true";
  48081. else
  48082. return isNaN(floatValue) ? value : floatValue;
  48083. }
  48084. var effectiveTarget = propertyPath.split(".");
  48085. var values = value.split(",");
  48086. // Get effective Target
  48087. for (var i = 0; i < effectiveTarget.length; i++) {
  48088. target = target[effectiveTarget[i]];
  48089. }
  48090. // Return appropriate value with its type
  48091. if (typeof (target) === "boolean")
  48092. return values[0] === "true";
  48093. if (typeof (target) === "string")
  48094. return values[0];
  48095. // Parameters with multiple values such as Vector3 etc.
  48096. var split = new Array();
  48097. for (var i = 0; i < values.length; i++)
  48098. split.push(parseFloat(values[i]));
  48099. if (target instanceof BABYLON.Vector3)
  48100. return BABYLON.Vector3.FromArray(split);
  48101. if (target instanceof BABYLON.Vector4)
  48102. return BABYLON.Vector4.FromArray(split);
  48103. if (target instanceof BABYLON.Color3)
  48104. return BABYLON.Color3.FromArray(split);
  48105. if (target instanceof BABYLON.Color4)
  48106. return BABYLON.Color4.FromArray(split);
  48107. return parseFloat(values[0]);
  48108. };
  48109. // traverse graph per trigger
  48110. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48111. if (combineArray === void 0) { combineArray = null; }
  48112. if (parsedAction.detached)
  48113. return;
  48114. var parameters = new Array();
  48115. var target = null;
  48116. var propertyPath = null;
  48117. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48118. // Parameters
  48119. if (parsedAction.type === 2)
  48120. parameters.push(actionManager);
  48121. else
  48122. parameters.push(trigger);
  48123. if (combine) {
  48124. var actions = new Array();
  48125. for (var j = 0; j < parsedAction.combine.length; j++) {
  48126. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48127. }
  48128. parameters.push(actions);
  48129. }
  48130. else {
  48131. for (var i = 0; i < parsedAction.properties.length; i++) {
  48132. var value = parsedAction.properties[i].value;
  48133. var name = parsedAction.properties[i].name;
  48134. var targetType = parsedAction.properties[i].targetType;
  48135. if (name === "target")
  48136. if (targetType !== null && targetType === "SceneProperties")
  48137. value = target = scene;
  48138. else
  48139. value = target = scene.getNodeByName(value);
  48140. else if (name === "parent")
  48141. value = scene.getNodeByName(value);
  48142. else if (name === "sound")
  48143. value = scene.getSoundByName(value);
  48144. else if (name !== "propertyPath") {
  48145. if (parsedAction.type === 2 && name === "operator")
  48146. value = BABYLON.ValueCondition[value];
  48147. else
  48148. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48149. }
  48150. else {
  48151. propertyPath = value;
  48152. }
  48153. parameters.push(value);
  48154. }
  48155. }
  48156. if (combineArray === null) {
  48157. parameters.push(condition);
  48158. }
  48159. else {
  48160. parameters.push(null);
  48161. }
  48162. // If interpolate value action
  48163. if (parsedAction.name === "InterpolateValueAction") {
  48164. var param = parameters[parameters.length - 2];
  48165. parameters[parameters.length - 1] = param;
  48166. parameters[parameters.length - 2] = condition;
  48167. }
  48168. // Action or condition(s) and not CombineAction
  48169. var newAction = instanciate(parsedAction.name, parameters);
  48170. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48171. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48172. if (action)
  48173. action.then(nothing);
  48174. else
  48175. actionManager.registerAction(nothing);
  48176. action = nothing;
  48177. }
  48178. if (combineArray === null) {
  48179. if (newAction instanceof BABYLON.Condition) {
  48180. condition = newAction;
  48181. newAction = action;
  48182. }
  48183. else {
  48184. condition = null;
  48185. if (action)
  48186. action.then(newAction);
  48187. else
  48188. actionManager.registerAction(newAction);
  48189. }
  48190. }
  48191. else {
  48192. combineArray.push(newAction);
  48193. }
  48194. for (var i = 0; i < parsedAction.children.length; i++)
  48195. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48196. };
  48197. // triggers
  48198. for (var i = 0; i < parsedActions.children.length; i++) {
  48199. var triggerParams;
  48200. var trigger = parsedActions.children[i];
  48201. if (trigger.properties.length > 0) {
  48202. var param = trigger.properties[0].value;
  48203. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48204. if (value._meshId) {
  48205. value.mesh = scene.getMeshByID(value._meshId);
  48206. }
  48207. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48208. }
  48209. else
  48210. triggerParams = ActionManager[trigger.name];
  48211. for (var j = 0; j < trigger.children.length; j++) {
  48212. if (!trigger.detached)
  48213. traverse(trigger.children[j], triggerParams, null, null);
  48214. }
  48215. }
  48216. };
  48217. ActionManager.GetTriggerName = function (trigger) {
  48218. switch (trigger) {
  48219. case 0: return "NothingTrigger";
  48220. case 1: return "OnPickTrigger";
  48221. case 2: return "OnLeftPickTrigger";
  48222. case 3: return "OnRightPickTrigger";
  48223. case 4: return "OnCenterPickTrigger";
  48224. case 5: return "OnPickDownTrigger";
  48225. case 6: return "OnPickUpTrigger";
  48226. case 7: return "OnLongPressTrigger";
  48227. case 8: return "OnPointerOverTrigger";
  48228. case 9: return "OnPointerOutTrigger";
  48229. case 10: return "OnEveryFrameTrigger";
  48230. case 11: return "OnIntersectionEnterTrigger";
  48231. case 12: return "OnIntersectionExitTrigger";
  48232. case 13: return "OnKeyDownTrigger";
  48233. case 14: return "OnKeyUpTrigger";
  48234. case 15: return "OnPickOutTrigger";
  48235. default: return "";
  48236. }
  48237. };
  48238. // Statics
  48239. ActionManager._NothingTrigger = 0;
  48240. ActionManager._OnPickTrigger = 1;
  48241. ActionManager._OnLeftPickTrigger = 2;
  48242. ActionManager._OnRightPickTrigger = 3;
  48243. ActionManager._OnCenterPickTrigger = 4;
  48244. ActionManager._OnPickDownTrigger = 5;
  48245. ActionManager._OnDoublePickTrigger = 6;
  48246. ActionManager._OnPickUpTrigger = 7;
  48247. ActionManager._OnLongPressTrigger = 8;
  48248. ActionManager._OnPointerOverTrigger = 9;
  48249. ActionManager._OnPointerOutTrigger = 10;
  48250. ActionManager._OnEveryFrameTrigger = 11;
  48251. ActionManager._OnIntersectionEnterTrigger = 12;
  48252. ActionManager._OnIntersectionExitTrigger = 13;
  48253. ActionManager._OnKeyDownTrigger = 14;
  48254. ActionManager._OnKeyUpTrigger = 15;
  48255. ActionManager._OnPickOutTrigger = 16;
  48256. ActionManager.Triggers = {};
  48257. return ActionManager;
  48258. }());
  48259. BABYLON.ActionManager = ActionManager;
  48260. })(BABYLON || (BABYLON = {}));
  48261. //# sourceMappingURL=babylon.actionManager.js.map
  48262. var BABYLON;
  48263. (function (BABYLON) {
  48264. var InterpolateValueAction = /** @class */ (function (_super) {
  48265. __extends(InterpolateValueAction, _super);
  48266. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48267. if (duration === void 0) { duration = 1000; }
  48268. var _this = _super.call(this, triggerOptions, condition) || this;
  48269. _this.propertyPath = propertyPath;
  48270. _this.value = value;
  48271. _this.duration = duration;
  48272. _this.stopOtherAnimations = stopOtherAnimations;
  48273. _this.onInterpolationDone = onInterpolationDone;
  48274. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48275. _this._target = _this._effectiveTarget = target;
  48276. return _this;
  48277. }
  48278. InterpolateValueAction.prototype._prepare = function () {
  48279. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48280. this._property = this._getProperty(this.propertyPath);
  48281. };
  48282. InterpolateValueAction.prototype.execute = function () {
  48283. var _this = this;
  48284. var scene = this._actionManager.getScene();
  48285. var keys = [
  48286. {
  48287. frame: 0,
  48288. value: this._effectiveTarget[this._property]
  48289. }, {
  48290. frame: 100,
  48291. value: this.value
  48292. }
  48293. ];
  48294. var dataType;
  48295. if (typeof this.value === "number") {
  48296. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48297. }
  48298. else if (this.value instanceof BABYLON.Color3) {
  48299. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48300. }
  48301. else if (this.value instanceof BABYLON.Vector3) {
  48302. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48303. }
  48304. else if (this.value instanceof BABYLON.Matrix) {
  48305. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48306. }
  48307. else if (this.value instanceof BABYLON.Quaternion) {
  48308. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48309. }
  48310. else {
  48311. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48312. return;
  48313. }
  48314. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48315. animation.setKeys(keys);
  48316. if (this.stopOtherAnimations) {
  48317. scene.stopAnimation(this._effectiveTarget);
  48318. }
  48319. var wrapper = function () {
  48320. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48321. if (_this.onInterpolationDone) {
  48322. _this.onInterpolationDone();
  48323. }
  48324. };
  48325. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48326. };
  48327. InterpolateValueAction.prototype.serialize = function (parent) {
  48328. return _super.prototype._serialize.call(this, {
  48329. name: "InterpolateValueAction",
  48330. properties: [
  48331. BABYLON.Action._GetTargetProperty(this._target),
  48332. { name: "propertyPath", value: this.propertyPath },
  48333. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48334. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48335. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48336. ]
  48337. }, parent);
  48338. };
  48339. return InterpolateValueAction;
  48340. }(BABYLON.Action));
  48341. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48342. })(BABYLON || (BABYLON = {}));
  48343. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48344. var BABYLON;
  48345. (function (BABYLON) {
  48346. var SwitchBooleanAction = /** @class */ (function (_super) {
  48347. __extends(SwitchBooleanAction, _super);
  48348. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48349. var _this = _super.call(this, triggerOptions, condition) || this;
  48350. _this.propertyPath = propertyPath;
  48351. _this._target = _this._effectiveTarget = target;
  48352. return _this;
  48353. }
  48354. SwitchBooleanAction.prototype._prepare = function () {
  48355. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48356. this._property = this._getProperty(this.propertyPath);
  48357. };
  48358. SwitchBooleanAction.prototype.execute = function () {
  48359. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48360. };
  48361. SwitchBooleanAction.prototype.serialize = function (parent) {
  48362. return _super.prototype._serialize.call(this, {
  48363. name: "SwitchBooleanAction",
  48364. properties: [
  48365. BABYLON.Action._GetTargetProperty(this._target),
  48366. { name: "propertyPath", value: this.propertyPath }
  48367. ]
  48368. }, parent);
  48369. };
  48370. return SwitchBooleanAction;
  48371. }(BABYLON.Action));
  48372. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48373. var SetStateAction = /** @class */ (function (_super) {
  48374. __extends(SetStateAction, _super);
  48375. function SetStateAction(triggerOptions, target, value, condition) {
  48376. var _this = _super.call(this, triggerOptions, condition) || this;
  48377. _this.value = value;
  48378. _this._target = target;
  48379. return _this;
  48380. }
  48381. SetStateAction.prototype.execute = function () {
  48382. this._target.state = this.value;
  48383. };
  48384. SetStateAction.prototype.serialize = function (parent) {
  48385. return _super.prototype._serialize.call(this, {
  48386. name: "SetStateAction",
  48387. properties: [
  48388. BABYLON.Action._GetTargetProperty(this._target),
  48389. { name: "value", value: this.value }
  48390. ]
  48391. }, parent);
  48392. };
  48393. return SetStateAction;
  48394. }(BABYLON.Action));
  48395. BABYLON.SetStateAction = SetStateAction;
  48396. var SetValueAction = /** @class */ (function (_super) {
  48397. __extends(SetValueAction, _super);
  48398. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48399. var _this = _super.call(this, triggerOptions, condition) || this;
  48400. _this.propertyPath = propertyPath;
  48401. _this.value = value;
  48402. _this._target = _this._effectiveTarget = target;
  48403. return _this;
  48404. }
  48405. SetValueAction.prototype._prepare = function () {
  48406. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48407. this._property = this._getProperty(this.propertyPath);
  48408. };
  48409. SetValueAction.prototype.execute = function () {
  48410. this._effectiveTarget[this._property] = this.value;
  48411. if (this._target.markAsDirty) {
  48412. this._target.markAsDirty(this._property);
  48413. }
  48414. };
  48415. SetValueAction.prototype.serialize = function (parent) {
  48416. return _super.prototype._serialize.call(this, {
  48417. name: "SetValueAction",
  48418. properties: [
  48419. BABYLON.Action._GetTargetProperty(this._target),
  48420. { name: "propertyPath", value: this.propertyPath },
  48421. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48422. ]
  48423. }, parent);
  48424. };
  48425. return SetValueAction;
  48426. }(BABYLON.Action));
  48427. BABYLON.SetValueAction = SetValueAction;
  48428. var IncrementValueAction = /** @class */ (function (_super) {
  48429. __extends(IncrementValueAction, _super);
  48430. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48431. var _this = _super.call(this, triggerOptions, condition) || this;
  48432. _this.propertyPath = propertyPath;
  48433. _this.value = value;
  48434. _this._target = _this._effectiveTarget = target;
  48435. return _this;
  48436. }
  48437. IncrementValueAction.prototype._prepare = function () {
  48438. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48439. this._property = this._getProperty(this.propertyPath);
  48440. if (typeof this._effectiveTarget[this._property] !== "number") {
  48441. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48442. }
  48443. };
  48444. IncrementValueAction.prototype.execute = function () {
  48445. this._effectiveTarget[this._property] += this.value;
  48446. if (this._target.markAsDirty) {
  48447. this._target.markAsDirty(this._property);
  48448. }
  48449. };
  48450. IncrementValueAction.prototype.serialize = function (parent) {
  48451. return _super.prototype._serialize.call(this, {
  48452. name: "IncrementValueAction",
  48453. properties: [
  48454. BABYLON.Action._GetTargetProperty(this._target),
  48455. { name: "propertyPath", value: this.propertyPath },
  48456. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48457. ]
  48458. }, parent);
  48459. };
  48460. return IncrementValueAction;
  48461. }(BABYLON.Action));
  48462. BABYLON.IncrementValueAction = IncrementValueAction;
  48463. var PlayAnimationAction = /** @class */ (function (_super) {
  48464. __extends(PlayAnimationAction, _super);
  48465. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48466. var _this = _super.call(this, triggerOptions, condition) || this;
  48467. _this.from = from;
  48468. _this.to = to;
  48469. _this.loop = loop;
  48470. _this._target = target;
  48471. return _this;
  48472. }
  48473. PlayAnimationAction.prototype._prepare = function () {
  48474. };
  48475. PlayAnimationAction.prototype.execute = function () {
  48476. var scene = this._actionManager.getScene();
  48477. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48478. };
  48479. PlayAnimationAction.prototype.serialize = function (parent) {
  48480. return _super.prototype._serialize.call(this, {
  48481. name: "PlayAnimationAction",
  48482. properties: [
  48483. BABYLON.Action._GetTargetProperty(this._target),
  48484. { name: "from", value: String(this.from) },
  48485. { name: "to", value: String(this.to) },
  48486. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48487. ]
  48488. }, parent);
  48489. };
  48490. return PlayAnimationAction;
  48491. }(BABYLON.Action));
  48492. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48493. var StopAnimationAction = /** @class */ (function (_super) {
  48494. __extends(StopAnimationAction, _super);
  48495. function StopAnimationAction(triggerOptions, target, condition) {
  48496. var _this = _super.call(this, triggerOptions, condition) || this;
  48497. _this._target = target;
  48498. return _this;
  48499. }
  48500. StopAnimationAction.prototype._prepare = function () {
  48501. };
  48502. StopAnimationAction.prototype.execute = function () {
  48503. var scene = this._actionManager.getScene();
  48504. scene.stopAnimation(this._target);
  48505. };
  48506. StopAnimationAction.prototype.serialize = function (parent) {
  48507. return _super.prototype._serialize.call(this, {
  48508. name: "StopAnimationAction",
  48509. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48510. }, parent);
  48511. };
  48512. return StopAnimationAction;
  48513. }(BABYLON.Action));
  48514. BABYLON.StopAnimationAction = StopAnimationAction;
  48515. var DoNothingAction = /** @class */ (function (_super) {
  48516. __extends(DoNothingAction, _super);
  48517. function DoNothingAction(triggerOptions, condition) {
  48518. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48519. return _super.call(this, triggerOptions, condition) || this;
  48520. }
  48521. DoNothingAction.prototype.execute = function () {
  48522. };
  48523. DoNothingAction.prototype.serialize = function (parent) {
  48524. return _super.prototype._serialize.call(this, {
  48525. name: "DoNothingAction",
  48526. properties: []
  48527. }, parent);
  48528. };
  48529. return DoNothingAction;
  48530. }(BABYLON.Action));
  48531. BABYLON.DoNothingAction = DoNothingAction;
  48532. var CombineAction = /** @class */ (function (_super) {
  48533. __extends(CombineAction, _super);
  48534. function CombineAction(triggerOptions, children, condition) {
  48535. var _this = _super.call(this, triggerOptions, condition) || this;
  48536. _this.children = children;
  48537. return _this;
  48538. }
  48539. CombineAction.prototype._prepare = function () {
  48540. for (var index = 0; index < this.children.length; index++) {
  48541. this.children[index]._actionManager = this._actionManager;
  48542. this.children[index]._prepare();
  48543. }
  48544. };
  48545. CombineAction.prototype.execute = function (evt) {
  48546. for (var index = 0; index < this.children.length; index++) {
  48547. this.children[index].execute(evt);
  48548. }
  48549. };
  48550. CombineAction.prototype.serialize = function (parent) {
  48551. var serializationObject = _super.prototype._serialize.call(this, {
  48552. name: "CombineAction",
  48553. properties: [],
  48554. combine: []
  48555. }, parent);
  48556. for (var i = 0; i < this.children.length; i++) {
  48557. serializationObject.combine.push(this.children[i].serialize(null));
  48558. }
  48559. return serializationObject;
  48560. };
  48561. return CombineAction;
  48562. }(BABYLON.Action));
  48563. BABYLON.CombineAction = CombineAction;
  48564. var ExecuteCodeAction = /** @class */ (function (_super) {
  48565. __extends(ExecuteCodeAction, _super);
  48566. function ExecuteCodeAction(triggerOptions, func, condition) {
  48567. var _this = _super.call(this, triggerOptions, condition) || this;
  48568. _this.func = func;
  48569. return _this;
  48570. }
  48571. ExecuteCodeAction.prototype.execute = function (evt) {
  48572. this.func(evt);
  48573. };
  48574. return ExecuteCodeAction;
  48575. }(BABYLON.Action));
  48576. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48577. var SetParentAction = /** @class */ (function (_super) {
  48578. __extends(SetParentAction, _super);
  48579. function SetParentAction(triggerOptions, target, parent, condition) {
  48580. var _this = _super.call(this, triggerOptions, condition) || this;
  48581. _this._target = target;
  48582. _this._parent = parent;
  48583. return _this;
  48584. }
  48585. SetParentAction.prototype._prepare = function () {
  48586. };
  48587. SetParentAction.prototype.execute = function () {
  48588. if (this._target.parent === this._parent) {
  48589. return;
  48590. }
  48591. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48592. invertParentWorldMatrix.invert();
  48593. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48594. this._target.parent = this._parent;
  48595. };
  48596. SetParentAction.prototype.serialize = function (parent) {
  48597. return _super.prototype._serialize.call(this, {
  48598. name: "SetParentAction",
  48599. properties: [
  48600. BABYLON.Action._GetTargetProperty(this._target),
  48601. BABYLON.Action._GetTargetProperty(this._parent),
  48602. ]
  48603. }, parent);
  48604. };
  48605. return SetParentAction;
  48606. }(BABYLON.Action));
  48607. BABYLON.SetParentAction = SetParentAction;
  48608. var PlaySoundAction = /** @class */ (function (_super) {
  48609. __extends(PlaySoundAction, _super);
  48610. function PlaySoundAction(triggerOptions, sound, condition) {
  48611. var _this = _super.call(this, triggerOptions, condition) || this;
  48612. _this._sound = sound;
  48613. return _this;
  48614. }
  48615. PlaySoundAction.prototype._prepare = function () {
  48616. };
  48617. PlaySoundAction.prototype.execute = function () {
  48618. if (this._sound !== undefined)
  48619. this._sound.play();
  48620. };
  48621. PlaySoundAction.prototype.serialize = function (parent) {
  48622. return _super.prototype._serialize.call(this, {
  48623. name: "PlaySoundAction",
  48624. properties: [{ name: "sound", value: this._sound.name }]
  48625. }, parent);
  48626. };
  48627. return PlaySoundAction;
  48628. }(BABYLON.Action));
  48629. BABYLON.PlaySoundAction = PlaySoundAction;
  48630. var StopSoundAction = /** @class */ (function (_super) {
  48631. __extends(StopSoundAction, _super);
  48632. function StopSoundAction(triggerOptions, sound, condition) {
  48633. var _this = _super.call(this, triggerOptions, condition) || this;
  48634. _this._sound = sound;
  48635. return _this;
  48636. }
  48637. StopSoundAction.prototype._prepare = function () {
  48638. };
  48639. StopSoundAction.prototype.execute = function () {
  48640. if (this._sound !== undefined)
  48641. this._sound.stop();
  48642. };
  48643. StopSoundAction.prototype.serialize = function (parent) {
  48644. return _super.prototype._serialize.call(this, {
  48645. name: "StopSoundAction",
  48646. properties: [{ name: "sound", value: this._sound.name }]
  48647. }, parent);
  48648. };
  48649. return StopSoundAction;
  48650. }(BABYLON.Action));
  48651. BABYLON.StopSoundAction = StopSoundAction;
  48652. })(BABYLON || (BABYLON = {}));
  48653. //# sourceMappingURL=babylon.directActions.js.map
  48654. var BABYLON;
  48655. (function (BABYLON) {
  48656. var SpriteManager = /** @class */ (function () {
  48657. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48658. if (epsilon === void 0) { epsilon = 0.01; }
  48659. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48660. this.name = name;
  48661. this.sprites = new Array();
  48662. this.renderingGroupId = 0;
  48663. this.layerMask = 0x0FFFFFFF;
  48664. this.fogEnabled = true;
  48665. this.isPickable = false;
  48666. /**
  48667. * An event triggered when the manager is disposed.
  48668. * @type {BABYLON.Observable}
  48669. */
  48670. this.onDisposeObservable = new BABYLON.Observable();
  48671. this._vertexBuffers = {};
  48672. this._capacity = capacity;
  48673. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48674. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48675. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48676. if (cellSize.width && cellSize.height) {
  48677. this.cellWidth = cellSize.width;
  48678. this.cellHeight = cellSize.height;
  48679. }
  48680. else if (cellSize !== undefined) {
  48681. this.cellWidth = cellSize;
  48682. this.cellHeight = cellSize;
  48683. }
  48684. else {
  48685. return;
  48686. }
  48687. this._epsilon = epsilon;
  48688. this._scene = scene;
  48689. this._scene.spriteManagers.push(this);
  48690. var indices = [];
  48691. var index = 0;
  48692. for (var count = 0; count < capacity; count++) {
  48693. indices.push(index);
  48694. indices.push(index + 1);
  48695. indices.push(index + 2);
  48696. indices.push(index);
  48697. indices.push(index + 2);
  48698. indices.push(index + 3);
  48699. index += 4;
  48700. }
  48701. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48702. // VBO
  48703. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48704. this._vertexData = new Float32Array(capacity * 16 * 4);
  48705. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48706. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48707. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48708. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48709. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48710. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48711. this._vertexBuffers["options"] = options;
  48712. this._vertexBuffers["cellInfo"] = cellInfo;
  48713. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48714. // Effects
  48715. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48716. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48717. }
  48718. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48719. set: function (callback) {
  48720. if (this._onDisposeObserver) {
  48721. this.onDisposeObservable.remove(this._onDisposeObserver);
  48722. }
  48723. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48724. },
  48725. enumerable: true,
  48726. configurable: true
  48727. });
  48728. Object.defineProperty(SpriteManager.prototype, "texture", {
  48729. get: function () {
  48730. return this._spriteTexture;
  48731. },
  48732. set: function (value) {
  48733. this._spriteTexture = value;
  48734. },
  48735. enumerable: true,
  48736. configurable: true
  48737. });
  48738. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48739. var arrayOffset = index * 16;
  48740. if (offsetX === 0)
  48741. offsetX = this._epsilon;
  48742. else if (offsetX === 1)
  48743. offsetX = 1 - this._epsilon;
  48744. if (offsetY === 0)
  48745. offsetY = this._epsilon;
  48746. else if (offsetY === 1)
  48747. offsetY = 1 - this._epsilon;
  48748. this._vertexData[arrayOffset] = sprite.position.x;
  48749. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48750. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48751. this._vertexData[arrayOffset + 3] = sprite.angle;
  48752. this._vertexData[arrayOffset + 4] = sprite.width;
  48753. this._vertexData[arrayOffset + 5] = sprite.height;
  48754. this._vertexData[arrayOffset + 6] = offsetX;
  48755. this._vertexData[arrayOffset + 7] = offsetY;
  48756. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48757. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48758. var offset = (sprite.cellIndex / rowSize) >> 0;
  48759. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48760. this._vertexData[arrayOffset + 11] = offset;
  48761. // Color
  48762. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48763. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48764. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48765. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48766. };
  48767. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48768. var count = Math.min(this._capacity, this.sprites.length);
  48769. var min = BABYLON.Vector3.Zero();
  48770. var max = BABYLON.Vector3.Zero();
  48771. var distance = Number.MAX_VALUE;
  48772. var currentSprite = null;
  48773. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48774. var cameraView = camera.getViewMatrix();
  48775. for (var index = 0; index < count; index++) {
  48776. var sprite = this.sprites[index];
  48777. if (!sprite) {
  48778. continue;
  48779. }
  48780. if (predicate) {
  48781. if (!predicate(sprite)) {
  48782. continue;
  48783. }
  48784. }
  48785. else if (!sprite.isPickable) {
  48786. continue;
  48787. }
  48788. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48789. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48790. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48791. if (ray.intersectsBoxMinMax(min, max)) {
  48792. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48793. if (distance > currentDistance) {
  48794. distance = currentDistance;
  48795. currentSprite = sprite;
  48796. if (fastCheck) {
  48797. break;
  48798. }
  48799. }
  48800. }
  48801. }
  48802. if (currentSprite) {
  48803. var result = new BABYLON.PickingInfo();
  48804. result.hit = true;
  48805. result.pickedSprite = currentSprite;
  48806. result.distance = distance;
  48807. return result;
  48808. }
  48809. return null;
  48810. };
  48811. SpriteManager.prototype.render = function () {
  48812. // Check
  48813. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48814. return;
  48815. var engine = this._scene.getEngine();
  48816. var baseSize = this._spriteTexture.getBaseSize();
  48817. // Sprites
  48818. var deltaTime = engine.getDeltaTime();
  48819. var max = Math.min(this._capacity, this.sprites.length);
  48820. var rowSize = baseSize.width / this.cellWidth;
  48821. var offset = 0;
  48822. for (var index = 0; index < max; index++) {
  48823. var sprite = this.sprites[index];
  48824. if (!sprite) {
  48825. continue;
  48826. }
  48827. sprite._animate(deltaTime);
  48828. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48829. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48830. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48831. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48832. }
  48833. this._buffer.update(this._vertexData);
  48834. // Render
  48835. var effect = this._effectBase;
  48836. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48837. effect = this._effectFog;
  48838. }
  48839. engine.enableEffect(effect);
  48840. var viewMatrix = this._scene.getViewMatrix();
  48841. effect.setTexture("diffuseSampler", this._spriteTexture);
  48842. effect.setMatrix("view", viewMatrix);
  48843. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48844. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48845. // Fog
  48846. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48847. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48848. effect.setColor3("vFogColor", this._scene.fogColor);
  48849. }
  48850. // VBOs
  48851. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48852. // Draw order
  48853. engine.setDepthFunctionToLessOrEqual();
  48854. effect.setBool("alphaTest", true);
  48855. engine.setColorWrite(false);
  48856. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48857. engine.setColorWrite(true);
  48858. effect.setBool("alphaTest", false);
  48859. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48860. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48861. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48862. };
  48863. SpriteManager.prototype.dispose = function () {
  48864. if (this._buffer) {
  48865. this._buffer.dispose();
  48866. this._buffer = null;
  48867. }
  48868. if (this._indexBuffer) {
  48869. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48870. this._indexBuffer = null;
  48871. }
  48872. if (this._spriteTexture) {
  48873. this._spriteTexture.dispose();
  48874. this._spriteTexture = null;
  48875. }
  48876. // Remove from scene
  48877. var index = this._scene.spriteManagers.indexOf(this);
  48878. this._scene.spriteManagers.splice(index, 1);
  48879. // Callback
  48880. this.onDisposeObservable.notifyObservers(this);
  48881. this.onDisposeObservable.clear();
  48882. };
  48883. return SpriteManager;
  48884. }());
  48885. BABYLON.SpriteManager = SpriteManager;
  48886. })(BABYLON || (BABYLON = {}));
  48887. //# sourceMappingURL=babylon.spriteManager.js.map
  48888. var BABYLON;
  48889. (function (BABYLON) {
  48890. var Sprite = /** @class */ (function () {
  48891. function Sprite(name, manager) {
  48892. this.name = name;
  48893. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48894. this.width = 1.0;
  48895. this.height = 1.0;
  48896. this.angle = 0;
  48897. this.cellIndex = 0;
  48898. this.invertU = 0;
  48899. this.invertV = 0;
  48900. this.animations = new Array();
  48901. this.isPickable = false;
  48902. this._animationStarted = false;
  48903. this._loopAnimation = false;
  48904. this._fromIndex = 0;
  48905. this._toIndex = 0;
  48906. this._delay = 0;
  48907. this._direction = 1;
  48908. this._time = 0;
  48909. this._manager = manager;
  48910. this._manager.sprites.push(this);
  48911. this.position = BABYLON.Vector3.Zero();
  48912. }
  48913. Object.defineProperty(Sprite.prototype, "size", {
  48914. get: function () {
  48915. return this.width;
  48916. },
  48917. set: function (value) {
  48918. this.width = value;
  48919. this.height = value;
  48920. },
  48921. enumerable: true,
  48922. configurable: true
  48923. });
  48924. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48925. this._fromIndex = from;
  48926. this._toIndex = to;
  48927. this._loopAnimation = loop;
  48928. this._delay = delay;
  48929. this._animationStarted = true;
  48930. this._direction = from < to ? 1 : -1;
  48931. this.cellIndex = from;
  48932. this._time = 0;
  48933. this._onAnimationEnd = onAnimationEnd;
  48934. };
  48935. Sprite.prototype.stopAnimation = function () {
  48936. this._animationStarted = false;
  48937. };
  48938. Sprite.prototype._animate = function (deltaTime) {
  48939. if (!this._animationStarted)
  48940. return;
  48941. this._time += deltaTime;
  48942. if (this._time > this._delay) {
  48943. this._time = this._time % this._delay;
  48944. this.cellIndex += this._direction;
  48945. if (this.cellIndex > this._toIndex) {
  48946. if (this._loopAnimation) {
  48947. this.cellIndex = this._fromIndex;
  48948. }
  48949. else {
  48950. this.cellIndex = this._toIndex;
  48951. this._animationStarted = false;
  48952. if (this._onAnimationEnd) {
  48953. this._onAnimationEnd();
  48954. }
  48955. if (this.disposeWhenFinishedAnimating) {
  48956. this.dispose();
  48957. }
  48958. }
  48959. }
  48960. }
  48961. };
  48962. Sprite.prototype.dispose = function () {
  48963. for (var i = 0; i < this._manager.sprites.length; i++) {
  48964. if (this._manager.sprites[i] == this) {
  48965. this._manager.sprites.splice(i, 1);
  48966. }
  48967. }
  48968. };
  48969. return Sprite;
  48970. }());
  48971. BABYLON.Sprite = Sprite;
  48972. })(BABYLON || (BABYLON = {}));
  48973. //# sourceMappingURL=babylon.sprite.js.map
  48974. var BABYLON;
  48975. (function (BABYLON) {
  48976. var IntersectionInfo = /** @class */ (function () {
  48977. function IntersectionInfo(bu, bv, distance) {
  48978. this.bu = bu;
  48979. this.bv = bv;
  48980. this.distance = distance;
  48981. this.faceId = 0;
  48982. this.subMeshId = 0;
  48983. }
  48984. return IntersectionInfo;
  48985. }());
  48986. BABYLON.IntersectionInfo = IntersectionInfo;
  48987. var PickingInfo = /** @class */ (function () {
  48988. function PickingInfo() {
  48989. this.hit = false;
  48990. this.distance = 0;
  48991. this.pickedPoint = null;
  48992. this.pickedMesh = null;
  48993. this.bu = 0;
  48994. this.bv = 0;
  48995. this.faceId = -1;
  48996. this.subMeshId = 0;
  48997. this.pickedSprite = null;
  48998. }
  48999. // Methods
  49000. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49001. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49002. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49003. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49004. return null;
  49005. }
  49006. var indices = this.pickedMesh.getIndices();
  49007. if (!indices) {
  49008. return null;
  49009. }
  49010. var result;
  49011. if (useVerticesNormals) {
  49012. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49013. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49014. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49015. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49016. normal0 = normal0.scale(this.bu);
  49017. normal1 = normal1.scale(this.bv);
  49018. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49019. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49020. }
  49021. else {
  49022. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49023. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49024. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49025. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49026. var p1p2 = vertex1.subtract(vertex2);
  49027. var p3p2 = vertex3.subtract(vertex2);
  49028. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49029. }
  49030. if (useWorldCoordinates) {
  49031. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49032. }
  49033. return BABYLON.Vector3.Normalize(result);
  49034. };
  49035. PickingInfo.prototype.getTextureCoordinates = function () {
  49036. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49037. return null;
  49038. }
  49039. var indices = this.pickedMesh.getIndices();
  49040. if (!indices) {
  49041. return null;
  49042. }
  49043. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49044. if (!uvs) {
  49045. return null;
  49046. }
  49047. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49048. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49049. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49050. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49051. uv1 = uv1.scale(this.bu);
  49052. uv2 = uv2.scale(this.bv);
  49053. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49054. };
  49055. return PickingInfo;
  49056. }());
  49057. BABYLON.PickingInfo = PickingInfo;
  49058. })(BABYLON || (BABYLON = {}));
  49059. //# sourceMappingURL=babylon.pickingInfo.js.map
  49060. var BABYLON;
  49061. (function (BABYLON) {
  49062. var Ray = /** @class */ (function () {
  49063. function Ray(origin, direction, length) {
  49064. if (length === void 0) { length = Number.MAX_VALUE; }
  49065. this.origin = origin;
  49066. this.direction = direction;
  49067. this.length = length;
  49068. }
  49069. // Methods
  49070. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49071. var d = 0.0;
  49072. var maxValue = Number.MAX_VALUE;
  49073. var inv;
  49074. var min;
  49075. var max;
  49076. var temp;
  49077. if (Math.abs(this.direction.x) < 0.0000001) {
  49078. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49079. return false;
  49080. }
  49081. }
  49082. else {
  49083. inv = 1.0 / this.direction.x;
  49084. min = (minimum.x - this.origin.x) * inv;
  49085. max = (maximum.x - this.origin.x) * inv;
  49086. if (max === -Infinity) {
  49087. max = Infinity;
  49088. }
  49089. if (min > max) {
  49090. temp = min;
  49091. min = max;
  49092. max = temp;
  49093. }
  49094. d = Math.max(min, d);
  49095. maxValue = Math.min(max, maxValue);
  49096. if (d > maxValue) {
  49097. return false;
  49098. }
  49099. }
  49100. if (Math.abs(this.direction.y) < 0.0000001) {
  49101. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49102. return false;
  49103. }
  49104. }
  49105. else {
  49106. inv = 1.0 / this.direction.y;
  49107. min = (minimum.y - this.origin.y) * inv;
  49108. max = (maximum.y - this.origin.y) * inv;
  49109. if (max === -Infinity) {
  49110. max = Infinity;
  49111. }
  49112. if (min > max) {
  49113. temp = min;
  49114. min = max;
  49115. max = temp;
  49116. }
  49117. d = Math.max(min, d);
  49118. maxValue = Math.min(max, maxValue);
  49119. if (d > maxValue) {
  49120. return false;
  49121. }
  49122. }
  49123. if (Math.abs(this.direction.z) < 0.0000001) {
  49124. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49125. return false;
  49126. }
  49127. }
  49128. else {
  49129. inv = 1.0 / this.direction.z;
  49130. min = (minimum.z - this.origin.z) * inv;
  49131. max = (maximum.z - this.origin.z) * inv;
  49132. if (max === -Infinity) {
  49133. max = Infinity;
  49134. }
  49135. if (min > max) {
  49136. temp = min;
  49137. min = max;
  49138. max = temp;
  49139. }
  49140. d = Math.max(min, d);
  49141. maxValue = Math.min(max, maxValue);
  49142. if (d > maxValue) {
  49143. return false;
  49144. }
  49145. }
  49146. return true;
  49147. };
  49148. Ray.prototype.intersectsBox = function (box) {
  49149. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49150. };
  49151. Ray.prototype.intersectsSphere = function (sphere) {
  49152. var x = sphere.center.x - this.origin.x;
  49153. var y = sphere.center.y - this.origin.y;
  49154. var z = sphere.center.z - this.origin.z;
  49155. var pyth = (x * x) + (y * y) + (z * z);
  49156. var rr = sphere.radius * sphere.radius;
  49157. if (pyth <= rr) {
  49158. return true;
  49159. }
  49160. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49161. if (dot < 0.0) {
  49162. return false;
  49163. }
  49164. var temp = pyth - (dot * dot);
  49165. return temp <= rr;
  49166. };
  49167. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49168. if (!this._edge1) {
  49169. this._edge1 = BABYLON.Vector3.Zero();
  49170. this._edge2 = BABYLON.Vector3.Zero();
  49171. this._pvec = BABYLON.Vector3.Zero();
  49172. this._tvec = BABYLON.Vector3.Zero();
  49173. this._qvec = BABYLON.Vector3.Zero();
  49174. }
  49175. vertex1.subtractToRef(vertex0, this._edge1);
  49176. vertex2.subtractToRef(vertex0, this._edge2);
  49177. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49178. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49179. if (det === 0) {
  49180. return null;
  49181. }
  49182. var invdet = 1 / det;
  49183. this.origin.subtractToRef(vertex0, this._tvec);
  49184. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49185. if (bu < 0 || bu > 1.0) {
  49186. return null;
  49187. }
  49188. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49189. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49190. if (bv < 0 || bu + bv > 1.0) {
  49191. return null;
  49192. }
  49193. //check if the distance is longer than the predefined length.
  49194. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49195. if (distance > this.length) {
  49196. return null;
  49197. }
  49198. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49199. };
  49200. Ray.prototype.intersectsPlane = function (plane) {
  49201. var distance;
  49202. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49203. if (Math.abs(result1) < 9.99999997475243E-07) {
  49204. return null;
  49205. }
  49206. else {
  49207. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49208. distance = (-plane.d - result2) / result1;
  49209. if (distance < 0.0) {
  49210. if (distance < -9.99999997475243E-07) {
  49211. return null;
  49212. }
  49213. else {
  49214. return 0;
  49215. }
  49216. }
  49217. return distance;
  49218. }
  49219. };
  49220. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49221. var tm = BABYLON.Tmp.Matrix[0];
  49222. mesh.getWorldMatrix().invertToRef(tm);
  49223. if (this._tmpRay) {
  49224. Ray.TransformToRef(this, tm, this._tmpRay);
  49225. }
  49226. else {
  49227. this._tmpRay = Ray.Transform(this, tm);
  49228. }
  49229. return mesh.intersects(this._tmpRay, fastCheck);
  49230. };
  49231. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49232. if (results) {
  49233. results.length = 0;
  49234. }
  49235. else {
  49236. results = [];
  49237. }
  49238. for (var i = 0; i < meshes.length; i++) {
  49239. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49240. if (pickInfo.hit) {
  49241. results.push(pickInfo);
  49242. }
  49243. }
  49244. results.sort(this._comparePickingInfo);
  49245. return results;
  49246. };
  49247. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49248. if (pickingInfoA.distance < pickingInfoB.distance) {
  49249. return -1;
  49250. }
  49251. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49252. return 1;
  49253. }
  49254. else {
  49255. return 0;
  49256. }
  49257. };
  49258. /**
  49259. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49260. * @param sega the first point of the segment to test the intersection against
  49261. * @param segb the second point of the segment to test the intersection against
  49262. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49263. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49264. */
  49265. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49266. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49267. var u = segb.subtract(sega);
  49268. var v = rsegb.subtract(this.origin);
  49269. var w = sega.subtract(this.origin);
  49270. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49271. var b = BABYLON.Vector3.Dot(u, v);
  49272. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49273. var d = BABYLON.Vector3.Dot(u, w);
  49274. var e = BABYLON.Vector3.Dot(v, w);
  49275. var D = a * c - b * b; // always >= 0
  49276. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49277. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49278. // compute the line parameters of the two closest points
  49279. if (D < Ray.smallnum) {
  49280. sN = 0.0; // force using point P0 on segment S1
  49281. sD = 1.0; // to prevent possible division by 0.0 later
  49282. tN = e;
  49283. tD = c;
  49284. }
  49285. else {
  49286. sN = (b * e - c * d);
  49287. tN = (a * e - b * d);
  49288. if (sN < 0.0) {
  49289. sN = 0.0;
  49290. tN = e;
  49291. tD = c;
  49292. }
  49293. else if (sN > sD) {
  49294. sN = sD;
  49295. tN = e + b;
  49296. tD = c;
  49297. }
  49298. }
  49299. if (tN < 0.0) {
  49300. tN = 0.0;
  49301. // recompute sc for this edge
  49302. if (-d < 0.0) {
  49303. sN = 0.0;
  49304. }
  49305. else if (-d > a)
  49306. sN = sD;
  49307. else {
  49308. sN = -d;
  49309. sD = a;
  49310. }
  49311. }
  49312. else if (tN > tD) {
  49313. tN = tD;
  49314. // recompute sc for this edge
  49315. if ((-d + b) < 0.0) {
  49316. sN = 0;
  49317. }
  49318. else if ((-d + b) > a) {
  49319. sN = sD;
  49320. }
  49321. else {
  49322. sN = (-d + b);
  49323. sD = a;
  49324. }
  49325. }
  49326. // finally do the division to get sc and tc
  49327. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49328. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49329. // get the difference of the two closest points
  49330. var qtc = v.multiplyByFloats(tc, tc, tc);
  49331. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49332. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49333. if (isIntersected) {
  49334. return qtc.length();
  49335. }
  49336. return -1;
  49337. };
  49338. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49339. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49340. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49341. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49342. this.direction.normalize();
  49343. return this;
  49344. };
  49345. // Statics
  49346. Ray.Zero = function () {
  49347. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49348. };
  49349. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49350. var result = Ray.Zero();
  49351. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49352. };
  49353. /**
  49354. * 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
  49355. * transformed to the given world matrix.
  49356. * @param origin The origin point
  49357. * @param end The end point
  49358. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49359. */
  49360. Ray.CreateNewFromTo = function (origin, end, world) {
  49361. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49362. var direction = end.subtract(origin);
  49363. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49364. direction.normalize();
  49365. return Ray.Transform(new Ray(origin, direction, length), world);
  49366. };
  49367. Ray.Transform = function (ray, matrix) {
  49368. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49369. Ray.TransformToRef(ray, matrix, result);
  49370. return result;
  49371. };
  49372. Ray.TransformToRef = function (ray, matrix, result) {
  49373. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49374. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49375. result.length = ray.length;
  49376. var dir = result.direction;
  49377. var len = dir.length();
  49378. if (!(len === 0 || len === 1)) {
  49379. var num = 1.0 / len;
  49380. dir.x *= num;
  49381. dir.y *= num;
  49382. dir.z *= num;
  49383. result.length *= len;
  49384. }
  49385. };
  49386. Ray.smallnum = 0.00000001;
  49387. Ray.rayl = 10e8;
  49388. return Ray;
  49389. }());
  49390. BABYLON.Ray = Ray;
  49391. })(BABYLON || (BABYLON = {}));
  49392. //# sourceMappingURL=babylon.ray.js.map
  49393. var BABYLON;
  49394. (function (BABYLON) {
  49395. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49396. if (boxMin.x > sphereCenter.x + sphereRadius)
  49397. return false;
  49398. if (sphereCenter.x - sphereRadius > boxMax.x)
  49399. return false;
  49400. if (boxMin.y > sphereCenter.y + sphereRadius)
  49401. return false;
  49402. if (sphereCenter.y - sphereRadius > boxMax.y)
  49403. return false;
  49404. if (boxMin.z > sphereCenter.z + sphereRadius)
  49405. return false;
  49406. if (sphereCenter.z - sphereRadius > boxMax.z)
  49407. return false;
  49408. return true;
  49409. };
  49410. var getLowestRoot = (function () {
  49411. var result = { root: 0, found: false };
  49412. return function (a, b, c, maxR) {
  49413. result.root = 0;
  49414. result.found = false;
  49415. var determinant = b * b - 4.0 * a * c;
  49416. if (determinant < 0)
  49417. return result;
  49418. var sqrtD = Math.sqrt(determinant);
  49419. var r1 = (-b - sqrtD) / (2.0 * a);
  49420. var r2 = (-b + sqrtD) / (2.0 * a);
  49421. if (r1 > r2) {
  49422. var temp = r2;
  49423. r2 = r1;
  49424. r1 = temp;
  49425. }
  49426. if (r1 > 0 && r1 < maxR) {
  49427. result.root = r1;
  49428. result.found = true;
  49429. return result;
  49430. }
  49431. if (r2 > 0 && r2 < maxR) {
  49432. result.root = r2;
  49433. result.found = true;
  49434. return result;
  49435. }
  49436. return result;
  49437. };
  49438. })();
  49439. var Collider = /** @class */ (function () {
  49440. function Collider() {
  49441. this._collisionPoint = BABYLON.Vector3.Zero();
  49442. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49443. this._tempVector = BABYLON.Vector3.Zero();
  49444. this._tempVector2 = BABYLON.Vector3.Zero();
  49445. this._tempVector3 = BABYLON.Vector3.Zero();
  49446. this._tempVector4 = BABYLON.Vector3.Zero();
  49447. this._edge = BABYLON.Vector3.Zero();
  49448. this._baseToVertex = BABYLON.Vector3.Zero();
  49449. this._destinationPoint = BABYLON.Vector3.Zero();
  49450. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49451. this._displacementVector = BABYLON.Vector3.Zero();
  49452. this._radius = BABYLON.Vector3.One();
  49453. this._retry = 0;
  49454. this._basePointWorld = BABYLON.Vector3.Zero();
  49455. this._velocityWorld = BABYLON.Vector3.Zero();
  49456. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49457. this._collisionMask = -1;
  49458. }
  49459. Object.defineProperty(Collider.prototype, "collisionMask", {
  49460. get: function () {
  49461. return this._collisionMask;
  49462. },
  49463. set: function (mask) {
  49464. this._collisionMask = !isNaN(mask) ? mask : -1;
  49465. },
  49466. enumerable: true,
  49467. configurable: true
  49468. });
  49469. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49470. /**
  49471. * Gets the plane normal used to compute the sliding response (in local space)
  49472. */
  49473. get: function () {
  49474. return this._slidePlaneNormal;
  49475. },
  49476. enumerable: true,
  49477. configurable: true
  49478. });
  49479. // Methods
  49480. Collider.prototype._initialize = function (source, dir, e) {
  49481. this._velocity = dir;
  49482. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49483. this._basePoint = source;
  49484. source.multiplyToRef(this._radius, this._basePointWorld);
  49485. dir.multiplyToRef(this._radius, this._velocityWorld);
  49486. this._velocityWorldLength = this._velocityWorld.length();
  49487. this._epsilon = e;
  49488. this.collisionFound = false;
  49489. };
  49490. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49491. pa.subtractToRef(point, this._tempVector);
  49492. pb.subtractToRef(point, this._tempVector2);
  49493. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49494. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49495. if (d < 0)
  49496. return false;
  49497. pc.subtractToRef(point, this._tempVector3);
  49498. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49499. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49500. if (d < 0)
  49501. return false;
  49502. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49503. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49504. return d >= 0;
  49505. };
  49506. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49507. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49508. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49509. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49510. return false;
  49511. }
  49512. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49513. return false;
  49514. return true;
  49515. };
  49516. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49517. var t0;
  49518. var embeddedInPlane = false;
  49519. //defensive programming, actually not needed.
  49520. if (!trianglePlaneArray) {
  49521. trianglePlaneArray = [];
  49522. }
  49523. if (!trianglePlaneArray[faceIndex]) {
  49524. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49525. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49526. }
  49527. var trianglePlane = trianglePlaneArray[faceIndex];
  49528. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49529. return;
  49530. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49531. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49532. if (normalDotVelocity == 0) {
  49533. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49534. return;
  49535. embeddedInPlane = true;
  49536. t0 = 0;
  49537. }
  49538. else {
  49539. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49540. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49541. if (t0 > t1) {
  49542. var temp = t1;
  49543. t1 = t0;
  49544. t0 = temp;
  49545. }
  49546. if (t0 > 1.0 || t1 < 0.0)
  49547. return;
  49548. if (t0 < 0)
  49549. t0 = 0;
  49550. if (t0 > 1.0)
  49551. t0 = 1.0;
  49552. }
  49553. this._collisionPoint.copyFromFloats(0, 0, 0);
  49554. var found = false;
  49555. var t = 1.0;
  49556. if (!embeddedInPlane) {
  49557. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49558. this._velocity.scaleToRef(t0, this._tempVector);
  49559. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49560. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49561. found = true;
  49562. t = t0;
  49563. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49564. }
  49565. }
  49566. if (!found) {
  49567. var velocitySquaredLength = this._velocity.lengthSquared();
  49568. var a = velocitySquaredLength;
  49569. this._basePoint.subtractToRef(p1, this._tempVector);
  49570. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49571. var c = this._tempVector.lengthSquared() - 1.0;
  49572. var lowestRoot = getLowestRoot(a, b, c, t);
  49573. if (lowestRoot.found) {
  49574. t = lowestRoot.root;
  49575. found = true;
  49576. this._collisionPoint.copyFrom(p1);
  49577. }
  49578. this._basePoint.subtractToRef(p2, this._tempVector);
  49579. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49580. c = this._tempVector.lengthSquared() - 1.0;
  49581. lowestRoot = getLowestRoot(a, b, c, t);
  49582. if (lowestRoot.found) {
  49583. t = lowestRoot.root;
  49584. found = true;
  49585. this._collisionPoint.copyFrom(p2);
  49586. }
  49587. this._basePoint.subtractToRef(p3, this._tempVector);
  49588. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49589. c = this._tempVector.lengthSquared() - 1.0;
  49590. lowestRoot = getLowestRoot(a, b, c, t);
  49591. if (lowestRoot.found) {
  49592. t = lowestRoot.root;
  49593. found = true;
  49594. this._collisionPoint.copyFrom(p3);
  49595. }
  49596. p2.subtractToRef(p1, this._edge);
  49597. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49598. var edgeSquaredLength = this._edge.lengthSquared();
  49599. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49600. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49601. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49602. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49603. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49604. lowestRoot = getLowestRoot(a, b, c, t);
  49605. if (lowestRoot.found) {
  49606. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49607. if (f >= 0.0 && f <= 1.0) {
  49608. t = lowestRoot.root;
  49609. found = true;
  49610. this._edge.scaleInPlace(f);
  49611. p1.addToRef(this._edge, this._collisionPoint);
  49612. }
  49613. }
  49614. p3.subtractToRef(p2, this._edge);
  49615. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49616. edgeSquaredLength = this._edge.lengthSquared();
  49617. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49618. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49619. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49620. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49621. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49622. lowestRoot = getLowestRoot(a, b, c, t);
  49623. if (lowestRoot.found) {
  49624. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49625. if (f >= 0.0 && f <= 1.0) {
  49626. t = lowestRoot.root;
  49627. found = true;
  49628. this._edge.scaleInPlace(f);
  49629. p2.addToRef(this._edge, this._collisionPoint);
  49630. }
  49631. }
  49632. p1.subtractToRef(p3, this._edge);
  49633. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49634. edgeSquaredLength = this._edge.lengthSquared();
  49635. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49636. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49637. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49638. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49639. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49640. lowestRoot = getLowestRoot(a, b, c, t);
  49641. if (lowestRoot.found) {
  49642. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49643. if (f >= 0.0 && f <= 1.0) {
  49644. t = lowestRoot.root;
  49645. found = true;
  49646. this._edge.scaleInPlace(f);
  49647. p3.addToRef(this._edge, this._collisionPoint);
  49648. }
  49649. }
  49650. }
  49651. if (found) {
  49652. var distToCollision = t * this._velocity.length();
  49653. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49654. if (!this.intersectionPoint) {
  49655. this.intersectionPoint = this._collisionPoint.clone();
  49656. }
  49657. else {
  49658. this.intersectionPoint.copyFrom(this._collisionPoint);
  49659. }
  49660. this._nearestDistance = distToCollision;
  49661. this.collisionFound = true;
  49662. }
  49663. }
  49664. };
  49665. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49666. for (var i = indexStart; i < indexEnd; i += 3) {
  49667. var p1 = pts[indices[i] - decal];
  49668. var p2 = pts[indices[i + 1] - decal];
  49669. var p3 = pts[indices[i + 2] - decal];
  49670. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49671. }
  49672. };
  49673. Collider.prototype._getResponse = function (pos, vel) {
  49674. pos.addToRef(vel, this._destinationPoint);
  49675. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49676. this._basePoint.addToRef(vel, pos);
  49677. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49678. this._slidePlaneNormal.normalize();
  49679. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49680. pos.addInPlace(this._displacementVector);
  49681. this.intersectionPoint.addInPlace(this._displacementVector);
  49682. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49683. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49684. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49685. };
  49686. return Collider;
  49687. }());
  49688. BABYLON.Collider = Collider;
  49689. })(BABYLON || (BABYLON = {}));
  49690. //# sourceMappingURL=babylon.collider.js.map
  49691. var BABYLON;
  49692. (function (BABYLON) {
  49693. //WebWorker code will be inserted to this variable.
  49694. BABYLON.CollisionWorker = "";
  49695. var WorkerTaskType;
  49696. (function (WorkerTaskType) {
  49697. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49698. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49699. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49700. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49701. var WorkerReplyType;
  49702. (function (WorkerReplyType) {
  49703. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49704. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49705. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49706. var CollisionCoordinatorWorker = /** @class */ (function () {
  49707. function CollisionCoordinatorWorker() {
  49708. var _this = this;
  49709. this._scaledPosition = BABYLON.Vector3.Zero();
  49710. this._scaledVelocity = BABYLON.Vector3.Zero();
  49711. this.onMeshUpdated = function (transformNode) {
  49712. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49713. };
  49714. this.onGeometryUpdated = function (geometry) {
  49715. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49716. };
  49717. this._afterRender = function () {
  49718. if (!_this._init)
  49719. return;
  49720. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49721. return;
  49722. }
  49723. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49724. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49725. if (_this._runningUpdated > 4) {
  49726. return;
  49727. }
  49728. ++_this._runningUpdated;
  49729. var payload = {
  49730. updatedMeshes: _this._addUpdateMeshesList,
  49731. updatedGeometries: _this._addUpdateGeometriesList,
  49732. removedGeometries: _this._toRemoveGeometryArray,
  49733. removedMeshes: _this._toRemoveMeshesArray
  49734. };
  49735. var message = {
  49736. payload: payload,
  49737. taskType: WorkerTaskType.UPDATE
  49738. };
  49739. var serializable = [];
  49740. for (var id in payload.updatedGeometries) {
  49741. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49742. //prepare transferables
  49743. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49744. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49745. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49746. }
  49747. }
  49748. _this._worker.postMessage(message, serializable);
  49749. _this._addUpdateMeshesList = {};
  49750. _this._addUpdateGeometriesList = {};
  49751. _this._toRemoveGeometryArray = [];
  49752. _this._toRemoveMeshesArray = [];
  49753. };
  49754. this._onMessageFromWorker = function (e) {
  49755. var returnData = e.data;
  49756. if (returnData.error != WorkerReplyType.SUCCESS) {
  49757. //TODO what errors can be returned from the worker?
  49758. BABYLON.Tools.Warn("error returned from worker!");
  49759. return;
  49760. }
  49761. switch (returnData.taskType) {
  49762. case WorkerTaskType.INIT:
  49763. _this._init = true;
  49764. //Update the worked with ALL of the scene's current state
  49765. _this._scene.meshes.forEach(function (mesh) {
  49766. _this.onMeshAdded(mesh);
  49767. });
  49768. _this._scene.getGeometries().forEach(function (geometry) {
  49769. _this.onGeometryAdded(geometry);
  49770. });
  49771. break;
  49772. case WorkerTaskType.UPDATE:
  49773. _this._runningUpdated--;
  49774. break;
  49775. case WorkerTaskType.COLLIDE:
  49776. var returnPayload = returnData.payload;
  49777. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49778. return;
  49779. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49780. if (callback) {
  49781. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49782. if (mesh) {
  49783. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49784. }
  49785. }
  49786. //cleanup
  49787. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49788. break;
  49789. }
  49790. };
  49791. this._collisionsCallbackArray = [];
  49792. this._init = false;
  49793. this._runningUpdated = 0;
  49794. this._addUpdateMeshesList = {};
  49795. this._addUpdateGeometriesList = {};
  49796. this._toRemoveGeometryArray = [];
  49797. this._toRemoveMeshesArray = [];
  49798. }
  49799. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49800. if (!this._init)
  49801. return;
  49802. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49803. return;
  49804. position.divideToRef(collider._radius, this._scaledPosition);
  49805. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49806. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49807. var payload = {
  49808. collider: {
  49809. position: this._scaledPosition.asArray(),
  49810. velocity: this._scaledVelocity.asArray(),
  49811. radius: collider._radius.asArray()
  49812. },
  49813. collisionId: collisionIndex,
  49814. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49815. maximumRetry: maximumRetry
  49816. };
  49817. var message = {
  49818. payload: payload,
  49819. taskType: WorkerTaskType.COLLIDE
  49820. };
  49821. this._worker.postMessage(message);
  49822. };
  49823. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49824. this._scene = scene;
  49825. this._scene.registerAfterRender(this._afterRender);
  49826. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49827. this._worker = new Worker(workerUrl);
  49828. this._worker.onmessage = this._onMessageFromWorker;
  49829. var message = {
  49830. payload: {},
  49831. taskType: WorkerTaskType.INIT
  49832. };
  49833. this._worker.postMessage(message);
  49834. };
  49835. CollisionCoordinatorWorker.prototype.destroy = function () {
  49836. this._scene.unregisterAfterRender(this._afterRender);
  49837. this._worker.terminate();
  49838. };
  49839. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49840. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49841. this.onMeshUpdated(mesh);
  49842. };
  49843. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49844. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49845. };
  49846. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49847. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49848. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49849. this.onGeometryUpdated(geometry);
  49850. };
  49851. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49852. this._toRemoveGeometryArray.push(geometry.id);
  49853. };
  49854. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49855. var submeshes = [];
  49856. if (mesh.subMeshes) {
  49857. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49858. var boundingInfo = sm.getBoundingInfo();
  49859. return {
  49860. position: idx,
  49861. verticesStart: sm.verticesStart,
  49862. verticesCount: sm.verticesCount,
  49863. indexStart: sm.indexStart,
  49864. indexCount: sm.indexCount,
  49865. hasMaterial: !!sm.getMaterial(),
  49866. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49867. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49868. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49869. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49870. };
  49871. });
  49872. }
  49873. var geometryId = null;
  49874. if (mesh instanceof BABYLON.Mesh) {
  49875. var geometry = mesh.geometry;
  49876. geometryId = geometry ? geometry.id : null;
  49877. }
  49878. else if (mesh instanceof BABYLON.InstancedMesh) {
  49879. var geometry = mesh.sourceMesh.geometry;
  49880. geometryId = geometry ? geometry.id : null;
  49881. }
  49882. var boundingInfo = mesh.getBoundingInfo();
  49883. return {
  49884. uniqueId: mesh.uniqueId,
  49885. id: mesh.id,
  49886. name: mesh.name,
  49887. geometryId: geometryId,
  49888. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49889. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49890. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49891. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49892. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49893. subMeshes: submeshes,
  49894. checkCollisions: mesh.checkCollisions
  49895. };
  49896. };
  49897. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49898. return {
  49899. id: geometry.id,
  49900. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49901. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49902. indices: new Uint32Array(geometry.getIndices() || []),
  49903. };
  49904. };
  49905. return CollisionCoordinatorWorker;
  49906. }());
  49907. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49908. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49909. function CollisionCoordinatorLegacy() {
  49910. this._scaledPosition = BABYLON.Vector3.Zero();
  49911. this._scaledVelocity = BABYLON.Vector3.Zero();
  49912. this._finalPosition = BABYLON.Vector3.Zero();
  49913. }
  49914. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49915. position.divideToRef(collider._radius, this._scaledPosition);
  49916. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49917. collider.collidedMesh = null;
  49918. collider._retry = 0;
  49919. collider._initialVelocity = this._scaledVelocity;
  49920. collider._initialPosition = this._scaledPosition;
  49921. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49922. this._finalPosition.multiplyInPlace(collider._radius);
  49923. //run the callback
  49924. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49925. };
  49926. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49927. this._scene = scene;
  49928. };
  49929. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49930. //Legacy need no destruction method.
  49931. };
  49932. //No update in legacy mode
  49933. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49934. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49935. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49936. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49937. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49938. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49939. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49940. if (excludedMesh === void 0) { excludedMesh = null; }
  49941. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49942. if (collider._retry >= maximumRetry) {
  49943. finalPosition.copyFrom(position);
  49944. return;
  49945. }
  49946. // Check if this is a mesh else camera or -1
  49947. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49948. collider._initialize(position, velocity, closeDistance);
  49949. // Check all meshes
  49950. for (var index = 0; index < this._scene.meshes.length; index++) {
  49951. var mesh = this._scene.meshes[index];
  49952. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49953. mesh._checkCollision(collider);
  49954. }
  49955. }
  49956. if (!collider.collisionFound) {
  49957. position.addToRef(velocity, finalPosition);
  49958. return;
  49959. }
  49960. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49961. collider._getResponse(position, velocity);
  49962. }
  49963. if (velocity.length() <= closeDistance) {
  49964. finalPosition.copyFrom(position);
  49965. return;
  49966. }
  49967. collider._retry++;
  49968. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49969. };
  49970. return CollisionCoordinatorLegacy;
  49971. }());
  49972. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49973. })(BABYLON || (BABYLON = {}));
  49974. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49975. var BABYLON;
  49976. (function (BABYLON) {
  49977. /**
  49978. * A particle represents one of the element emitted by a particle system.
  49979. * This is mainly define by its coordinates, direction, velocity and age.
  49980. */
  49981. var Particle = /** @class */ (function () {
  49982. /**
  49983. * Creates a new instance of @see Particle
  49984. * @param particleSystem the particle system the particle belongs to
  49985. */
  49986. function Particle(particleSystem) {
  49987. this.particleSystem = particleSystem;
  49988. /**
  49989. * The world position of the particle in the scene.
  49990. */
  49991. this.position = BABYLON.Vector3.Zero();
  49992. /**
  49993. * The world direction of the particle in the scene.
  49994. */
  49995. this.direction = BABYLON.Vector3.Zero();
  49996. /**
  49997. * The color of the particle.
  49998. */
  49999. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50000. /**
  50001. * The color change of the particle per step.
  50002. */
  50003. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50004. /**
  50005. * Defines how long will the life of the particle be.
  50006. */
  50007. this.lifeTime = 1.0;
  50008. /**
  50009. * The current age of the particle.
  50010. */
  50011. this.age = 0;
  50012. /**
  50013. * The current size of the particle.
  50014. */
  50015. this.size = 0;
  50016. /**
  50017. * The current angle of the particle.
  50018. */
  50019. this.angle = 0;
  50020. /**
  50021. * Defines how fast is the angle changing.
  50022. */
  50023. this.angularSpeed = 0;
  50024. /**
  50025. * Defines the cell index used by the particle to be rendered from a sprite.
  50026. */
  50027. this.cellIndex = 0;
  50028. this._currentFrameCounter = 0;
  50029. if (!this.particleSystem.isAnimationSheetEnabled) {
  50030. return;
  50031. }
  50032. this.cellIndex = this.particleSystem.startSpriteCellID;
  50033. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50034. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50035. }
  50036. else {
  50037. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50038. }
  50039. }
  50040. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50041. // (ageOffset / scaledUpdateSpeed) / available cells
  50042. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50043. this._currentFrameCounter += scaledUpdateSpeed;
  50044. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50045. this._currentFrameCounter = 0;
  50046. this.cellIndex++;
  50047. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50048. this.cellIndex = this.particleSystem.endSpriteCellID;
  50049. }
  50050. }
  50051. };
  50052. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50053. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50054. this.cellIndex++;
  50055. this._currentFrameCounter = 0;
  50056. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50057. if (this.particleSystem.spriteCellLoop) {
  50058. this.cellIndex = this.particleSystem.startSpriteCellID;
  50059. }
  50060. else {
  50061. this.cellIndex = this.particleSystem.endSpriteCellID;
  50062. }
  50063. }
  50064. }
  50065. else {
  50066. this._currentFrameCounter++;
  50067. }
  50068. };
  50069. /**
  50070. * Copy the properties of particle to another one.
  50071. * @param other the particle to copy the information to.
  50072. */
  50073. Particle.prototype.copyTo = function (other) {
  50074. other.position.copyFrom(this.position);
  50075. other.direction.copyFrom(this.direction);
  50076. other.color.copyFrom(this.color);
  50077. other.colorStep.copyFrom(this.colorStep);
  50078. other.lifeTime = this.lifeTime;
  50079. other.age = this.age;
  50080. other.size = this.size;
  50081. other.angle = this.angle;
  50082. other.angularSpeed = this.angularSpeed;
  50083. other.particleSystem = this.particleSystem;
  50084. other.cellIndex = this.cellIndex;
  50085. };
  50086. return Particle;
  50087. }());
  50088. BABYLON.Particle = Particle;
  50089. })(BABYLON || (BABYLON = {}));
  50090. //# sourceMappingURL=babylon.particle.js.map
  50091. var BABYLON;
  50092. (function (BABYLON) {
  50093. /**
  50094. * This represents a particle system in Babylon.
  50095. * 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.
  50096. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50097. * @example https://doc.babylonjs.com/babylon101/particles
  50098. */
  50099. var ParticleSystem = /** @class */ (function () {
  50100. /**
  50101. * Instantiates a particle system.
  50102. * 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.
  50103. * @param name The name of the particle system
  50104. * @param capacity The max number of particles alive at the same time
  50105. * @param scene The scene the particle system belongs to
  50106. * @param customEffect a custom effect used to change the way particles are rendered by default
  50107. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50108. * @param epsilon Offset used to render the particles
  50109. */
  50110. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50111. if (customEffect === void 0) { customEffect = null; }
  50112. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50113. if (epsilon === void 0) { epsilon = 0.01; }
  50114. var _this = this;
  50115. /**
  50116. * List of animations used by the particle system.
  50117. */
  50118. this.animations = [];
  50119. /**
  50120. * The rendering group used by the Particle system to chose when to render.
  50121. */
  50122. this.renderingGroupId = 0;
  50123. /**
  50124. * The emitter represents the Mesh or position we are attaching the particle system to.
  50125. */
  50126. this.emitter = null;
  50127. /**
  50128. * The maximum number of particles to emit per frame
  50129. */
  50130. this.emitRate = 10;
  50131. /**
  50132. * If you want to launch only a few particles at once, that can be done, as well.
  50133. */
  50134. this.manualEmitCount = -1;
  50135. /**
  50136. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50137. */
  50138. this.updateSpeed = 0.01;
  50139. /**
  50140. * The amount of time the particle system is running (depends of the overall speed above).
  50141. */
  50142. this.targetStopDuration = 0;
  50143. /**
  50144. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50145. */
  50146. this.disposeOnStop = false;
  50147. /**
  50148. * Minimum power of emitting particles.
  50149. */
  50150. this.minEmitPower = 1;
  50151. /**
  50152. * Maximum power of emitting particles.
  50153. */
  50154. this.maxEmitPower = 1;
  50155. /**
  50156. * Minimum life time of emitting particles.
  50157. */
  50158. this.minLifeTime = 1;
  50159. /**
  50160. * Maximum life time of emitting particles.
  50161. */
  50162. this.maxLifeTime = 1;
  50163. /**
  50164. * Minimum Size of emitting particles.
  50165. */
  50166. this.minSize = 1;
  50167. /**
  50168. * Maximum Size of emitting particles.
  50169. */
  50170. this.maxSize = 1;
  50171. /**
  50172. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50173. */
  50174. this.minAngularSpeed = 0;
  50175. /**
  50176. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50177. */
  50178. this.maxAngularSpeed = 0;
  50179. /**
  50180. * The layer mask we are rendering the particles through.
  50181. */
  50182. this.layerMask = 0x0FFFFFFF;
  50183. /**
  50184. * This can help using your own shader to render the particle system.
  50185. * The according effect will be created
  50186. */
  50187. this.customShader = null;
  50188. /**
  50189. * By default particle system starts as soon as they are created. This prevents the
  50190. * automatic start to happen and let you decide when to start emitting particles.
  50191. */
  50192. this.preventAutoStart = false;
  50193. /**
  50194. * Callback triggered when the particle animation is ending.
  50195. */
  50196. this.onAnimationEnd = null;
  50197. /**
  50198. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50199. */
  50200. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50201. /**
  50202. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50203. * to override the particles.
  50204. */
  50205. this.forceDepthWrite = false;
  50206. /**
  50207. * You can use gravity if you want to give an orientation to your particles.
  50208. */
  50209. this.gravity = BABYLON.Vector3.Zero();
  50210. /**
  50211. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50212. */
  50213. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50214. /**
  50215. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50216. */
  50217. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50218. /**
  50219. * Color the particle will have at the end of its lifetime.
  50220. */
  50221. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50222. /**
  50223. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50224. */
  50225. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50226. /**
  50227. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50228. */
  50229. this.spriteCellLoop = true;
  50230. /**
  50231. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50232. */
  50233. this.spriteCellChangeSpeed = 0;
  50234. /**
  50235. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50236. */
  50237. this.startSpriteCellID = 0;
  50238. /**
  50239. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50240. */
  50241. this.endSpriteCellID = 0;
  50242. /**
  50243. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50244. */
  50245. this.spriteCellWidth = 0;
  50246. /**
  50247. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50248. */
  50249. this.spriteCellHeight = 0;
  50250. /**
  50251. * An event triggered when the system is disposed.
  50252. */
  50253. this.onDisposeObservable = new BABYLON.Observable();
  50254. this._particles = new Array();
  50255. this._stockParticles = new Array();
  50256. this._newPartsExcess = 0;
  50257. this._vertexBuffers = {};
  50258. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50259. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50260. this._scaledDirection = BABYLON.Vector3.Zero();
  50261. this._scaledGravity = BABYLON.Vector3.Zero();
  50262. this._currentRenderId = -1;
  50263. this._started = false;
  50264. this._stopped = false;
  50265. this._actualFrame = 0;
  50266. this._vertexBufferSize = 11;
  50267. this._appendParticleVertexes = null;
  50268. this.id = name;
  50269. this.name = name;
  50270. this._capacity = capacity;
  50271. this._epsilon = epsilon;
  50272. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50273. if (isAnimationSheetEnabled) {
  50274. this._vertexBufferSize = 12;
  50275. }
  50276. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50277. this._customEffect = customEffect;
  50278. scene.particleSystems.push(this);
  50279. this._createIndexBuffer();
  50280. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50281. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50282. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50283. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50284. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50285. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50286. if (this._isAnimationSheetEnabled) {
  50287. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50288. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50289. }
  50290. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50291. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50292. this._vertexBuffers["options"] = options;
  50293. // Default emitter type
  50294. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50295. this.updateFunction = function (particles) {
  50296. for (var index = 0; index < particles.length; index++) {
  50297. var particle = particles[index];
  50298. particle.age += _this._scaledUpdateSpeed;
  50299. if (particle.age >= particle.lifeTime) {
  50300. _this.recycleParticle(particle);
  50301. index--;
  50302. continue;
  50303. }
  50304. else {
  50305. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50306. particle.color.addInPlace(_this._scaledColorStep);
  50307. if (particle.color.a < 0)
  50308. particle.color.a = 0;
  50309. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50310. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50311. particle.position.addInPlace(_this._scaledDirection);
  50312. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50313. particle.direction.addInPlace(_this._scaledGravity);
  50314. if (_this._isAnimationSheetEnabled) {
  50315. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50316. }
  50317. }
  50318. }
  50319. };
  50320. }
  50321. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50322. /**
  50323. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50324. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50325. */
  50326. get: function () {
  50327. if (this.particleEmitterType.direction1) {
  50328. return this.particleEmitterType.direction1;
  50329. }
  50330. return BABYLON.Vector3.Zero();
  50331. },
  50332. set: function (value) {
  50333. if (this.particleEmitterType.direction1) {
  50334. this.particleEmitterType.direction1 = value;
  50335. }
  50336. },
  50337. enumerable: true,
  50338. configurable: true
  50339. });
  50340. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50341. /**
  50342. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50343. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50344. */
  50345. get: function () {
  50346. if (this.particleEmitterType.direction2) {
  50347. return this.particleEmitterType.direction2;
  50348. }
  50349. return BABYLON.Vector3.Zero();
  50350. },
  50351. set: function (value) {
  50352. if (this.particleEmitterType.direction2) {
  50353. this.particleEmitterType.direction2 = value;
  50354. }
  50355. },
  50356. enumerable: true,
  50357. configurable: true
  50358. });
  50359. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50360. /**
  50361. * 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.
  50362. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50363. */
  50364. get: function () {
  50365. if (this.particleEmitterType.minEmitBox) {
  50366. return this.particleEmitterType.minEmitBox;
  50367. }
  50368. return BABYLON.Vector3.Zero();
  50369. },
  50370. set: function (value) {
  50371. if (this.particleEmitterType.minEmitBox) {
  50372. this.particleEmitterType.minEmitBox = value;
  50373. }
  50374. },
  50375. enumerable: true,
  50376. configurable: true
  50377. });
  50378. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50379. /**
  50380. * 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.
  50381. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50382. */
  50383. get: function () {
  50384. if (this.particleEmitterType.maxEmitBox) {
  50385. return this.particleEmitterType.maxEmitBox;
  50386. }
  50387. return BABYLON.Vector3.Zero();
  50388. },
  50389. set: function (value) {
  50390. if (this.particleEmitterType.maxEmitBox) {
  50391. this.particleEmitterType.maxEmitBox = value;
  50392. }
  50393. },
  50394. enumerable: true,
  50395. configurable: true
  50396. });
  50397. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50398. /**
  50399. * Sets a callback that will be triggered when the system is disposed.
  50400. */
  50401. set: function (callback) {
  50402. if (this._onDisposeObserver) {
  50403. this.onDisposeObservable.remove(this._onDisposeObserver);
  50404. }
  50405. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50406. },
  50407. enumerable: true,
  50408. configurable: true
  50409. });
  50410. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50411. /**
  50412. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50413. */
  50414. get: function () {
  50415. return this._isAnimationSheetEnabled;
  50416. },
  50417. enumerable: true,
  50418. configurable: true
  50419. });
  50420. ParticleSystem.prototype._createIndexBuffer = function () {
  50421. var indices = [];
  50422. var index = 0;
  50423. for (var count = 0; count < this._capacity; count++) {
  50424. indices.push(index);
  50425. indices.push(index + 1);
  50426. indices.push(index + 2);
  50427. indices.push(index);
  50428. indices.push(index + 2);
  50429. indices.push(index + 3);
  50430. index += 4;
  50431. }
  50432. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50433. };
  50434. /**
  50435. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50436. * Its lifetime will start back at 0.
  50437. * @param particle The particle to recycle
  50438. */
  50439. ParticleSystem.prototype.recycleParticle = function (particle) {
  50440. var lastParticle = this._particles.pop();
  50441. if (lastParticle !== particle) {
  50442. lastParticle.copyTo(particle);
  50443. this._stockParticles.push(lastParticle);
  50444. }
  50445. };
  50446. /**
  50447. * Gets the maximum number of particles active at the same time.
  50448. * @returns The max number of active particles.
  50449. */
  50450. ParticleSystem.prototype.getCapacity = function () {
  50451. return this._capacity;
  50452. };
  50453. /**
  50454. * Gets Wether there are still active particles in the system.
  50455. * @returns True if it is alive, otherwise false.
  50456. */
  50457. ParticleSystem.prototype.isAlive = function () {
  50458. return this._alive;
  50459. };
  50460. /**
  50461. * Gets Wether the system has been started.
  50462. * @returns True if it has been started, otherwise false.
  50463. */
  50464. ParticleSystem.prototype.isStarted = function () {
  50465. return this._started;
  50466. };
  50467. /**
  50468. * Starts the particle system and begins to emit.
  50469. */
  50470. ParticleSystem.prototype.start = function () {
  50471. this._started = true;
  50472. this._stopped = false;
  50473. this._actualFrame = 0;
  50474. };
  50475. /**
  50476. * Stops the particle system.
  50477. */
  50478. ParticleSystem.prototype.stop = function () {
  50479. this._stopped = true;
  50480. };
  50481. /**
  50482. * Remove all active particles
  50483. */
  50484. ParticleSystem.prototype.reset = function () {
  50485. this._stockParticles = [];
  50486. this._particles = [];
  50487. };
  50488. /**
  50489. * @ignore (for internal use only)
  50490. */
  50491. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50492. var offset = index * this._vertexBufferSize;
  50493. this._vertexData[offset] = particle.position.x;
  50494. this._vertexData[offset + 1] = particle.position.y;
  50495. this._vertexData[offset + 2] = particle.position.z;
  50496. this._vertexData[offset + 3] = particle.color.r;
  50497. this._vertexData[offset + 4] = particle.color.g;
  50498. this._vertexData[offset + 5] = particle.color.b;
  50499. this._vertexData[offset + 6] = particle.color.a;
  50500. this._vertexData[offset + 7] = particle.angle;
  50501. this._vertexData[offset + 8] = particle.size;
  50502. this._vertexData[offset + 9] = offsetX;
  50503. this._vertexData[offset + 10] = offsetY;
  50504. };
  50505. /**
  50506. * @ignore (for internal use only)
  50507. */
  50508. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50509. if (offsetX === 0)
  50510. offsetX = this._epsilon;
  50511. else if (offsetX === 1)
  50512. offsetX = 1 - this._epsilon;
  50513. if (offsetY === 0)
  50514. offsetY = this._epsilon;
  50515. else if (offsetY === 1)
  50516. offsetY = 1 - this._epsilon;
  50517. var offset = index * this._vertexBufferSize;
  50518. this._vertexData[offset] = particle.position.x;
  50519. this._vertexData[offset + 1] = particle.position.y;
  50520. this._vertexData[offset + 2] = particle.position.z;
  50521. this._vertexData[offset + 3] = particle.color.r;
  50522. this._vertexData[offset + 4] = particle.color.g;
  50523. this._vertexData[offset + 5] = particle.color.b;
  50524. this._vertexData[offset + 6] = particle.color.a;
  50525. this._vertexData[offset + 7] = particle.angle;
  50526. this._vertexData[offset + 8] = particle.size;
  50527. this._vertexData[offset + 9] = offsetX;
  50528. this._vertexData[offset + 10] = offsetY;
  50529. this._vertexData[offset + 11] = particle.cellIndex;
  50530. };
  50531. ParticleSystem.prototype._update = function (newParticles) {
  50532. // Update current
  50533. this._alive = this._particles.length > 0;
  50534. this.updateFunction(this._particles);
  50535. // Add new ones
  50536. var worldMatrix;
  50537. if (this.emitter.position) {
  50538. var emitterMesh = this.emitter;
  50539. worldMatrix = emitterMesh.getWorldMatrix();
  50540. }
  50541. else {
  50542. var emitterPosition = this.emitter;
  50543. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50544. }
  50545. var particle;
  50546. for (var index = 0; index < newParticles; index++) {
  50547. if (this._particles.length === this._capacity) {
  50548. break;
  50549. }
  50550. if (this._stockParticles.length !== 0) {
  50551. particle = this._stockParticles.pop();
  50552. particle.age = 0;
  50553. particle.cellIndex = this.startSpriteCellID;
  50554. }
  50555. else {
  50556. particle = new BABYLON.Particle(this);
  50557. }
  50558. this._particles.push(particle);
  50559. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50560. if (this.startPositionFunction) {
  50561. this.startPositionFunction(worldMatrix, particle.position, particle);
  50562. }
  50563. else {
  50564. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50565. }
  50566. if (this.startDirectionFunction) {
  50567. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50568. }
  50569. else {
  50570. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50571. }
  50572. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50573. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50574. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50575. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50576. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50577. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50578. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50579. }
  50580. };
  50581. ParticleSystem.prototype._getEffect = function () {
  50582. if (this._customEffect) {
  50583. return this._customEffect;
  50584. }
  50585. ;
  50586. var defines = [];
  50587. if (this._scene.clipPlane) {
  50588. defines.push("#define CLIPPLANE");
  50589. }
  50590. if (this._isAnimationSheetEnabled) {
  50591. defines.push("#define ANIMATESHEET");
  50592. }
  50593. // Effect
  50594. var join = defines.join("\n");
  50595. if (this._cachedDefines !== join) {
  50596. this._cachedDefines = join;
  50597. var attributesNamesOrOptions;
  50598. var effectCreationOption;
  50599. if (this._isAnimationSheetEnabled) {
  50600. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50601. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50602. }
  50603. else {
  50604. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50605. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50606. }
  50607. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50608. }
  50609. return this._effect;
  50610. };
  50611. /**
  50612. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50613. */
  50614. ParticleSystem.prototype.animate = function () {
  50615. if (!this._started)
  50616. return;
  50617. var effect = this._getEffect();
  50618. // Check
  50619. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50620. return;
  50621. if (this._currentRenderId === this._scene.getRenderId()) {
  50622. return;
  50623. }
  50624. this._currentRenderId = this._scene.getRenderId();
  50625. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50626. // determine the number of particles we need to create
  50627. var newParticles;
  50628. if (this.manualEmitCount > -1) {
  50629. newParticles = this.manualEmitCount;
  50630. this._newPartsExcess = 0;
  50631. this.manualEmitCount = 0;
  50632. }
  50633. else {
  50634. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50635. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50636. }
  50637. if (this._newPartsExcess > 1.0) {
  50638. newParticles += this._newPartsExcess >> 0;
  50639. this._newPartsExcess -= this._newPartsExcess >> 0;
  50640. }
  50641. this._alive = false;
  50642. if (!this._stopped) {
  50643. this._actualFrame += this._scaledUpdateSpeed;
  50644. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50645. this.stop();
  50646. }
  50647. else {
  50648. newParticles = 0;
  50649. }
  50650. this._update(newParticles);
  50651. // Stopped?
  50652. if (this._stopped) {
  50653. if (!this._alive) {
  50654. this._started = false;
  50655. if (this.onAnimationEnd) {
  50656. this.onAnimationEnd();
  50657. }
  50658. if (this.disposeOnStop) {
  50659. this._scene._toBeDisposed.push(this);
  50660. }
  50661. }
  50662. }
  50663. // Animation sheet
  50664. if (this._isAnimationSheetEnabled) {
  50665. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50666. }
  50667. else {
  50668. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50669. }
  50670. // Update VBO
  50671. var offset = 0;
  50672. for (var index = 0; index < this._particles.length; index++) {
  50673. var particle = this._particles[index];
  50674. this._appendParticleVertexes(offset, particle);
  50675. offset += 4;
  50676. }
  50677. if (this._vertexBuffer) {
  50678. this._vertexBuffer.update(this._vertexData);
  50679. }
  50680. };
  50681. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50682. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50683. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50684. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50685. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50686. };
  50687. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50688. this._appendParticleVertex(offset++, particle, 0, 0);
  50689. this._appendParticleVertex(offset++, particle, 1, 0);
  50690. this._appendParticleVertex(offset++, particle, 1, 1);
  50691. this._appendParticleVertex(offset++, particle, 0, 1);
  50692. };
  50693. /**
  50694. * Rebuilds the particle system.
  50695. */
  50696. ParticleSystem.prototype.rebuild = function () {
  50697. this._createIndexBuffer();
  50698. if (this._vertexBuffer) {
  50699. this._vertexBuffer._rebuild();
  50700. }
  50701. };
  50702. /**
  50703. * Renders the particle system in its current state.
  50704. * @returns the current number of particles
  50705. */
  50706. ParticleSystem.prototype.render = function () {
  50707. var effect = this._getEffect();
  50708. // Check
  50709. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  50710. return 0;
  50711. }
  50712. var engine = this._scene.getEngine();
  50713. // Render
  50714. engine.enableEffect(effect);
  50715. engine.setState(false);
  50716. var viewMatrix = this._scene.getViewMatrix();
  50717. effect.setTexture("diffuseSampler", this.particleTexture);
  50718. effect.setMatrix("view", viewMatrix);
  50719. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50720. if (this._isAnimationSheetEnabled) {
  50721. var baseSize = this.particleTexture.getBaseSize();
  50722. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50723. }
  50724. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50725. if (this._scene.clipPlane) {
  50726. var clipPlane = this._scene.clipPlane;
  50727. var invView = viewMatrix.clone();
  50728. invView.invert();
  50729. effect.setMatrix("invView", invView);
  50730. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50731. }
  50732. // VBOs
  50733. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50734. // Draw order
  50735. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50736. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50737. }
  50738. else {
  50739. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50740. }
  50741. if (this.forceDepthWrite) {
  50742. engine.setDepthWrite(true);
  50743. }
  50744. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50745. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50746. return this._particles.length;
  50747. };
  50748. /**
  50749. * Disposes the particle system and free the associated resources.
  50750. */
  50751. ParticleSystem.prototype.dispose = function () {
  50752. if (this._vertexBuffer) {
  50753. this._vertexBuffer.dispose();
  50754. this._vertexBuffer = null;
  50755. }
  50756. if (this._indexBuffer) {
  50757. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50758. this._indexBuffer = null;
  50759. }
  50760. if (this.particleTexture) {
  50761. this.particleTexture.dispose();
  50762. this.particleTexture = null;
  50763. }
  50764. // Remove from scene
  50765. var index = this._scene.particleSystems.indexOf(this);
  50766. if (index > -1) {
  50767. this._scene.particleSystems.splice(index, 1);
  50768. }
  50769. // Callback
  50770. this.onDisposeObservable.notifyObservers(this);
  50771. this.onDisposeObservable.clear();
  50772. };
  50773. /**
  50774. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50775. * @param radius The radius of the sphere to emit from
  50776. * @returns the emitter
  50777. */
  50778. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50779. if (radius === void 0) { radius = 1; }
  50780. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50781. this.particleEmitterType = particleEmitter;
  50782. return particleEmitter;
  50783. };
  50784. /**
  50785. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50786. * @param radius The radius of the sphere to emit from
  50787. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50788. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50789. * @returns the emitter
  50790. */
  50791. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50792. if (radius === void 0) { radius = 1; }
  50793. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50794. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50795. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50796. this.particleEmitterType = particleEmitter;
  50797. return particleEmitter;
  50798. };
  50799. /**
  50800. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50801. * @param radius The radius of the cone to emit from
  50802. * @param angle The base angle of the cone
  50803. * @returns the emitter
  50804. */
  50805. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50806. if (radius === void 0) { radius = 1; }
  50807. if (angle === void 0) { angle = Math.PI / 4; }
  50808. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50809. this.particleEmitterType = particleEmitter;
  50810. return particleEmitter;
  50811. };
  50812. // 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.
  50813. /**
  50814. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50815. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50816. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50817. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50818. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50819. * @returns the emitter
  50820. */
  50821. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50822. var particleEmitter = new BABYLON.BoxParticleEmitter();
  50823. this.direction1 = direction1;
  50824. this.direction2 = direction2;
  50825. this.minEmitBox = minEmitBox;
  50826. this.maxEmitBox = maxEmitBox;
  50827. this.particleEmitterType = particleEmitter;
  50828. return particleEmitter;
  50829. };
  50830. /**
  50831. * Clones the particle system.
  50832. * @param name The name of the cloned object
  50833. * @param newEmitter The new emitter to use
  50834. * @returns the cloned particle system
  50835. */
  50836. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50837. var custom = null;
  50838. var program = null;
  50839. if (this.customShader != null) {
  50840. program = this.customShader;
  50841. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50842. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50843. }
  50844. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50845. result.customShader = program;
  50846. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50847. if (newEmitter === undefined) {
  50848. newEmitter = this.emitter;
  50849. }
  50850. result.emitter = newEmitter;
  50851. if (this.particleTexture) {
  50852. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50853. }
  50854. if (!this.preventAutoStart) {
  50855. result.start();
  50856. }
  50857. return result;
  50858. };
  50859. /**
  50860. * Serializes the particle system to a JSON object.
  50861. * @returns the JSON object
  50862. */
  50863. ParticleSystem.prototype.serialize = function () {
  50864. var serializationObject = {};
  50865. serializationObject.name = this.name;
  50866. serializationObject.id = this.id;
  50867. // Emitter
  50868. if (this.emitter.position) {
  50869. var emitterMesh = this.emitter;
  50870. serializationObject.emitterId = emitterMesh.id;
  50871. }
  50872. else {
  50873. var emitterPosition = this.emitter;
  50874. serializationObject.emitter = emitterPosition.asArray();
  50875. }
  50876. serializationObject.capacity = this.getCapacity();
  50877. if (this.particleTexture) {
  50878. serializationObject.textureName = this.particleTexture.name;
  50879. }
  50880. // Animations
  50881. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50882. // Particle system
  50883. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50884. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50885. serializationObject.minSize = this.minSize;
  50886. serializationObject.maxSize = this.maxSize;
  50887. serializationObject.minEmitPower = this.minEmitPower;
  50888. serializationObject.maxEmitPower = this.maxEmitPower;
  50889. serializationObject.minLifeTime = this.minLifeTime;
  50890. serializationObject.maxLifeTime = this.maxLifeTime;
  50891. serializationObject.emitRate = this.emitRate;
  50892. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50893. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50894. serializationObject.gravity = this.gravity.asArray();
  50895. serializationObject.direction1 = this.direction1.asArray();
  50896. serializationObject.direction2 = this.direction2.asArray();
  50897. serializationObject.color1 = this.color1.asArray();
  50898. serializationObject.color2 = this.color2.asArray();
  50899. serializationObject.colorDead = this.colorDead.asArray();
  50900. serializationObject.updateSpeed = this.updateSpeed;
  50901. serializationObject.targetStopDuration = this.targetStopDuration;
  50902. serializationObject.textureMask = this.textureMask.asArray();
  50903. serializationObject.blendMode = this.blendMode;
  50904. serializationObject.customShader = this.customShader;
  50905. serializationObject.preventAutoStart = this.preventAutoStart;
  50906. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50907. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50908. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50909. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50910. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50911. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50912. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50913. return serializationObject;
  50914. };
  50915. /**
  50916. * Parses a JSON object to create a particle system.
  50917. * @param parsedParticleSystem The JSON object to parse
  50918. * @param scene The scene to create the particle system in
  50919. * @param rootUrl The root url to use to load external dependencies like texture
  50920. * @returns the Parsed particle system
  50921. */
  50922. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50923. var name = parsedParticleSystem.name;
  50924. var custom = null;
  50925. var program = null;
  50926. if (parsedParticleSystem.customShader) {
  50927. program = parsedParticleSystem.customShader;
  50928. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50929. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50930. }
  50931. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50932. particleSystem.customShader = program;
  50933. if (parsedParticleSystem.id) {
  50934. particleSystem.id = parsedParticleSystem.id;
  50935. }
  50936. // Auto start
  50937. if (parsedParticleSystem.preventAutoStart) {
  50938. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50939. }
  50940. // Texture
  50941. if (parsedParticleSystem.textureName) {
  50942. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50943. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50944. }
  50945. // Emitter
  50946. if (parsedParticleSystem.emitterId) {
  50947. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50948. }
  50949. else {
  50950. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50951. }
  50952. // Animations
  50953. if (parsedParticleSystem.animations) {
  50954. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50955. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50956. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50957. }
  50958. }
  50959. if (parsedParticleSystem.autoAnimate) {
  50960. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50961. }
  50962. // Particle system
  50963. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50964. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50965. particleSystem.minSize = parsedParticleSystem.minSize;
  50966. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50967. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50968. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50969. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50970. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50971. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50972. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50973. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50974. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50975. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50976. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50977. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50978. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50979. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  50980. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  50981. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  50982. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  50983. particleSystem.blendMode = parsedParticleSystem.blendMode;
  50984. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  50985. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  50986. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  50987. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  50988. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  50989. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  50990. if (!particleSystem.preventAutoStart) {
  50991. particleSystem.start();
  50992. }
  50993. return particleSystem;
  50994. };
  50995. /**
  50996. * Source color is added to the destination color without alpha affecting the result.
  50997. */
  50998. ParticleSystem.BLENDMODE_ONEONE = 0;
  50999. /**
  51000. * Blend current color and particle color using particle’s alpha.
  51001. */
  51002. ParticleSystem.BLENDMODE_STANDARD = 1;
  51003. return ParticleSystem;
  51004. }());
  51005. BABYLON.ParticleSystem = ParticleSystem;
  51006. })(BABYLON || (BABYLON = {}));
  51007. //# sourceMappingURL=babylon.particleSystem.js.map
  51008. var BABYLON;
  51009. (function (BABYLON) {
  51010. /**
  51011. * Particle emitter emitting particles from the inside of a box.
  51012. * It emits the particles randomly between 2 given directions.
  51013. */
  51014. var BoxParticleEmitter = /** @class */ (function () {
  51015. // to be updated like the rest of emitters when breaking changes.
  51016. // all property should be come public variables and passed through constructor.
  51017. /**
  51018. * Creates a new instance of @see BoxParticleEmitter
  51019. */
  51020. function BoxParticleEmitter() {
  51021. /**
  51022. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51023. */
  51024. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51025. /**
  51026. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51027. */
  51028. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51029. /**
  51030. * 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.
  51031. */
  51032. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51033. /**
  51034. * 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.
  51035. */
  51036. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51037. }
  51038. /**
  51039. * Called by the particle System when the direction is computed for the created particle.
  51040. * @param emitPower is the power of the particle (speed)
  51041. * @param worldMatrix is the world matrix of the particle system
  51042. * @param directionToUpdate is the direction vector to update with the result
  51043. * @param particle is the particle we are computed the direction for
  51044. */
  51045. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51046. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51047. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51048. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51049. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51050. };
  51051. /**
  51052. * Called by the particle System when the position is computed for the created particle.
  51053. * @param worldMatrix is the world matrix of the particle system
  51054. * @param positionToUpdate is the position vector to update with the result
  51055. * @param particle is the particle we are computed the position for
  51056. */
  51057. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51058. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51059. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51060. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51061. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51062. };
  51063. /**
  51064. * Clones the current emitter and returns a copy of it
  51065. * @returns the new emitter
  51066. */
  51067. BoxParticleEmitter.prototype.clone = function () {
  51068. var newOne = new BoxParticleEmitter();
  51069. BABYLON.Tools.DeepCopy(this, newOne);
  51070. return newOne;
  51071. };
  51072. /**
  51073. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51074. * @param effect defines the update shader
  51075. */
  51076. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51077. };
  51078. return BoxParticleEmitter;
  51079. }());
  51080. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51081. })(BABYLON || (BABYLON = {}));
  51082. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51083. var BABYLON;
  51084. (function (BABYLON) {
  51085. /**
  51086. * Particle emitter emitting particles from the inside of a cone.
  51087. * It emits the particles alongside the cone volume from the base to the particle.
  51088. * The emission direction might be randomized.
  51089. */
  51090. var ConeParticleEmitter = /** @class */ (function () {
  51091. /**
  51092. * Creates a new instance of @see ConeParticleEmitter
  51093. * @param radius the radius of the emission cone
  51094. * @param angles the cone base angle
  51095. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51096. */
  51097. function ConeParticleEmitter(radius,
  51098. /**
  51099. * The radius of the emission cone.
  51100. */
  51101. angle,
  51102. /**
  51103. * The cone base angle.
  51104. */
  51105. directionRandomizer) {
  51106. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51107. this.angle = angle;
  51108. this.directionRandomizer = directionRandomizer;
  51109. this.radius = radius;
  51110. }
  51111. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51112. /**
  51113. * Gets the radius of the emission cone.
  51114. */
  51115. get: function () {
  51116. return this._radius;
  51117. },
  51118. /**
  51119. * Sets the radius of the emission cone.
  51120. */
  51121. set: function (value) {
  51122. this._radius = value;
  51123. if (this.angle !== 0) {
  51124. this._height = value / Math.tan(this.angle / 2);
  51125. }
  51126. else {
  51127. this._height = 1;
  51128. }
  51129. },
  51130. enumerable: true,
  51131. configurable: true
  51132. });
  51133. /**
  51134. * Called by the particle System when the direction is computed for the created particle.
  51135. * @param emitPower is the power of the particle (speed)
  51136. * @param worldMatrix is the world matrix of the particle system
  51137. * @param directionToUpdate is the direction vector to update with the result
  51138. * @param particle is the particle we are computed the direction for
  51139. */
  51140. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51141. if (this.angle === 0) {
  51142. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51143. }
  51144. else {
  51145. // measure the direction Vector from the emitter to the particle.
  51146. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51147. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51148. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51149. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51150. direction.x += randX;
  51151. direction.y += randY;
  51152. direction.z += randZ;
  51153. direction.normalize();
  51154. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51155. }
  51156. };
  51157. /**
  51158. * Called by the particle System when the position is computed for the created particle.
  51159. * @param worldMatrix is the world matrix of the particle system
  51160. * @param positionToUpdate is the position vector to update with the result
  51161. * @param particle is the particle we are computed the position for
  51162. */
  51163. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51164. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51165. var h = BABYLON.Scalar.RandomRange(0, 1);
  51166. // Better distribution in a cone at normal angles.
  51167. h = 1 - h * h;
  51168. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51169. radius = radius * h / this._height;
  51170. var randX = radius * Math.sin(s);
  51171. var randZ = radius * Math.cos(s);
  51172. var randY = h;
  51173. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51174. };
  51175. /**
  51176. * Clones the current emitter and returns a copy of it
  51177. * @returns the new emitter
  51178. */
  51179. ConeParticleEmitter.prototype.clone = function () {
  51180. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51181. BABYLON.Tools.DeepCopy(this, newOne);
  51182. return newOne;
  51183. };
  51184. /**
  51185. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51186. * @param effect defines the update shader
  51187. */
  51188. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51189. };
  51190. return ConeParticleEmitter;
  51191. }());
  51192. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51193. })(BABYLON || (BABYLON = {}));
  51194. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51195. var BABYLON;
  51196. (function (BABYLON) {
  51197. /**
  51198. * Particle emitter emitting particles from the inside of a sphere.
  51199. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51200. */
  51201. var SphereParticleEmitter = /** @class */ (function () {
  51202. /**
  51203. * Creates a new instance of @see SphereParticleEmitter
  51204. * @param radius the radius of the emission sphere
  51205. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51206. */
  51207. function SphereParticleEmitter(
  51208. /**
  51209. * The radius of the emission sphere.
  51210. */
  51211. radius,
  51212. /**
  51213. * How much to randomize the particle direction [0-1].
  51214. */
  51215. directionRandomizer) {
  51216. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51217. this.radius = radius;
  51218. this.directionRandomizer = directionRandomizer;
  51219. }
  51220. /**
  51221. * Called by the particle System when the direction is computed for the created particle.
  51222. * @param emitPower is the power of the particle (speed)
  51223. * @param worldMatrix is the world matrix of the particle system
  51224. * @param directionToUpdate is the direction vector to update with the result
  51225. * @param particle is the particle we are computed the direction for
  51226. */
  51227. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51228. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51229. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51230. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51231. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51232. direction.x += randX;
  51233. direction.y += randY;
  51234. direction.z += randZ;
  51235. direction.normalize();
  51236. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51237. };
  51238. /**
  51239. * Called by the particle System when the position is computed for the created particle.
  51240. * @param worldMatrix is the world matrix of the particle system
  51241. * @param positionToUpdate is the position vector to update with the result
  51242. * @param particle is the particle we are computed the position for
  51243. */
  51244. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51245. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51246. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51247. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  51248. var randY = this.radius * Math.cos(theta);
  51249. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  51250. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51251. };
  51252. /**
  51253. * Clones the current emitter and returns a copy of it
  51254. * @returns the new emitter
  51255. */
  51256. SphereParticleEmitter.prototype.clone = function () {
  51257. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51258. BABYLON.Tools.DeepCopy(this, newOne);
  51259. return newOne;
  51260. };
  51261. /**
  51262. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51263. * @param effect defines the update shader
  51264. */
  51265. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51266. };
  51267. return SphereParticleEmitter;
  51268. }());
  51269. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51270. /**
  51271. * Particle emitter emitting particles from the inside of a sphere.
  51272. * It emits the particles randomly between two vectors.
  51273. */
  51274. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51275. __extends(SphereDirectedParticleEmitter, _super);
  51276. /**
  51277. * Creates a new instance of @see SphereDirectedParticleEmitter
  51278. * @param radius the radius of the emission sphere
  51279. * @param direction1 the min limit of the emission direction
  51280. * @param direction2 the max limit of the emission direction
  51281. */
  51282. function SphereDirectedParticleEmitter(radius,
  51283. /**
  51284. * The min limit of the emission direction.
  51285. */
  51286. direction1,
  51287. /**
  51288. * The max limit of the emission direction.
  51289. */
  51290. direction2) {
  51291. var _this = _super.call(this, radius) || this;
  51292. _this.direction1 = direction1;
  51293. _this.direction2 = direction2;
  51294. return _this;
  51295. }
  51296. /**
  51297. * Called by the particle System when the direction is computed for the created particle.
  51298. * @param emitPower is the power of the particle (speed)
  51299. * @param worldMatrix is the world matrix of the particle system
  51300. * @param directionToUpdate is the direction vector to update with the result
  51301. * @param particle is the particle we are computed the direction for
  51302. */
  51303. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51304. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51305. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51306. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51307. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51308. };
  51309. /**
  51310. * Clones the current emitter and returns a copy of it
  51311. * @returns the new emitter
  51312. */
  51313. SphereDirectedParticleEmitter.prototype.clone = function () {
  51314. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51315. BABYLON.Tools.DeepCopy(this, newOne);
  51316. return newOne;
  51317. };
  51318. /**
  51319. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51320. * @param effect defines the update shader
  51321. */
  51322. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51323. };
  51324. return SphereDirectedParticleEmitter;
  51325. }(SphereParticleEmitter));
  51326. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51327. })(BABYLON || (BABYLON = {}));
  51328. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51329. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51330. var BABYLON;
  51331. (function (BABYLON) {
  51332. /**
  51333. * Represents one particle of a solid particle system.
  51334. * @see SolidParticleSystem
  51335. */
  51336. var SolidParticle = /** @class */ (function () {
  51337. /**
  51338. * Creates a Solid Particle object.
  51339. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51340. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51341. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51342. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51343. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51344. * @param shapeId (integer) is the model shape identifier in the SPS.
  51345. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51346. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51347. */
  51348. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51349. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51350. /**
  51351. * particle global index
  51352. */
  51353. this.idx = 0;
  51354. /**
  51355. * The color of the particle
  51356. */
  51357. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51358. /**
  51359. * The world space position of the particle.
  51360. */
  51361. this.position = BABYLON.Vector3.Zero();
  51362. /**
  51363. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51364. */
  51365. this.rotation = BABYLON.Vector3.Zero();
  51366. /**
  51367. * The scaling of the particle.
  51368. */
  51369. this.scaling = BABYLON.Vector3.One();
  51370. /**
  51371. * The uvs of the particle.
  51372. */
  51373. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51374. /**
  51375. * The current speed of the particle.
  51376. */
  51377. this.velocity = BABYLON.Vector3.Zero();
  51378. /**
  51379. * The pivot point in the particle local space.
  51380. */
  51381. this.pivot = BABYLON.Vector3.Zero();
  51382. /**
  51383. * Must the particle be translated from its pivot point in its local space ?
  51384. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51385. * Default : false
  51386. */
  51387. this.translateFromPivot = false;
  51388. /**
  51389. * Is the particle active or not ?
  51390. */
  51391. this.alive = true;
  51392. /**
  51393. * Is the particle visible or not ?
  51394. */
  51395. this.isVisible = true;
  51396. /**
  51397. * Index of this particle in the global "positions" array (Internal use)
  51398. */
  51399. this._pos = 0;
  51400. /**
  51401. * Index of this particle in the global "indices" array (Internal use)
  51402. */
  51403. this._ind = 0;
  51404. /**
  51405. * ModelShape id of this particle
  51406. */
  51407. this.shapeId = 0;
  51408. /**
  51409. * Index of the particle in its shape id (Internal use)
  51410. */
  51411. this.idxInShape = 0;
  51412. /**
  51413. * Still set as invisible in order to skip useless computations (Internal use)
  51414. */
  51415. this._stillInvisible = false;
  51416. /**
  51417. * Last computed particle rotation matrix
  51418. */
  51419. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51420. /**
  51421. * Parent particle Id, if any.
  51422. * Default null.
  51423. */
  51424. this.parentId = null;
  51425. /**
  51426. * Internal global position in the SPS.
  51427. */
  51428. this._globalPosition = BABYLON.Vector3.Zero();
  51429. this.idx = particleIndex;
  51430. this._pos = positionIndex;
  51431. this._ind = indiceIndex;
  51432. this._model = model;
  51433. this.shapeId = shapeId;
  51434. this.idxInShape = idxInShape;
  51435. this._sps = sps;
  51436. if (modelBoundingInfo) {
  51437. this._modelBoundingInfo = modelBoundingInfo;
  51438. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51439. }
  51440. }
  51441. Object.defineProperty(SolidParticle.prototype, "scale", {
  51442. /**
  51443. * Legacy support, changed scale to scaling
  51444. */
  51445. get: function () {
  51446. return this.scaling;
  51447. },
  51448. /**
  51449. * Legacy support, changed scale to scaling
  51450. */
  51451. set: function (scale) {
  51452. this.scaling = scale;
  51453. },
  51454. enumerable: true,
  51455. configurable: true
  51456. });
  51457. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51458. /**
  51459. * Legacy support, changed quaternion to rotationQuaternion
  51460. */
  51461. get: function () {
  51462. return this.rotationQuaternion;
  51463. },
  51464. /**
  51465. * Legacy support, changed quaternion to rotationQuaternion
  51466. */
  51467. set: function (q) {
  51468. this.rotationQuaternion = q;
  51469. },
  51470. enumerable: true,
  51471. configurable: true
  51472. });
  51473. /**
  51474. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51475. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51476. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51477. * @returns true if it intersects
  51478. */
  51479. SolidParticle.prototype.intersectsMesh = function (target) {
  51480. if (!this._boundingInfo || !target._boundingInfo) {
  51481. return false;
  51482. }
  51483. if (this._sps._bSphereOnly) {
  51484. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51485. }
  51486. return this._boundingInfo.intersects(target._boundingInfo, false);
  51487. };
  51488. return SolidParticle;
  51489. }());
  51490. BABYLON.SolidParticle = SolidParticle;
  51491. /**
  51492. * Represents the shape of the model used by one particle of a solid particle system.
  51493. * SPS internal tool, don't use it manually.
  51494. * @see SolidParticleSystem
  51495. */
  51496. var ModelShape = /** @class */ (function () {
  51497. /**
  51498. * 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.
  51499. * SPS internal tool, don't use it manually.
  51500. * @ignore
  51501. */
  51502. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51503. /**
  51504. * length of the shape in the model indices array (internal use)
  51505. */
  51506. this._indicesLength = 0;
  51507. this.shapeID = id;
  51508. this._shape = shape;
  51509. this._indicesLength = indicesLength;
  51510. this._shapeUV = shapeUV;
  51511. this._positionFunction = posFunction;
  51512. this._vertexFunction = vtxFunction;
  51513. }
  51514. return ModelShape;
  51515. }());
  51516. BABYLON.ModelShape = ModelShape;
  51517. /**
  51518. * Represents a Depth Sorted Particle in the solid particle system.
  51519. * @see SolidParticleSystem
  51520. */
  51521. var DepthSortedParticle = /** @class */ (function () {
  51522. function DepthSortedParticle() {
  51523. /**
  51524. * Index of the particle in the "indices" array
  51525. */
  51526. this.ind = 0;
  51527. /**
  51528. * Length of the particle shape in the "indices" array
  51529. */
  51530. this.indicesLength = 0;
  51531. /**
  51532. * Squared distance from the particle to the camera
  51533. */
  51534. this.sqDistance = 0.0;
  51535. }
  51536. return DepthSortedParticle;
  51537. }());
  51538. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51539. })(BABYLON || (BABYLON = {}));
  51540. //# sourceMappingURL=babylon.solidParticle.js.map
  51541. var BABYLON;
  51542. (function (BABYLON) {
  51543. /**
  51544. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51545. *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.
  51546. * The SPS is also a particle system. It provides some methods to manage the particles.
  51547. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51548. *
  51549. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51550. */
  51551. var SolidParticleSystem = /** @class */ (function () {
  51552. /**
  51553. * Creates a SPS (Solid Particle System) object.
  51554. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51555. * @param scene (Scene) is the scene in which the SPS is added.
  51556. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51557. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51558. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51559. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51560. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51561. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51562. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51563. */
  51564. function SolidParticleSystem(name, scene, options) {
  51565. /**
  51566. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51567. * Example : var p = SPS.particles[i];
  51568. */
  51569. this.particles = new Array();
  51570. /**
  51571. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51572. */
  51573. this.nbParticles = 0;
  51574. /**
  51575. * If the particles must ever face the camera (default false). Useful for planar particles.
  51576. */
  51577. this.billboard = false;
  51578. /**
  51579. * Recompute normals when adding a shape
  51580. */
  51581. this.recomputeNormals = true;
  51582. /**
  51583. * This a counter ofr your own usage. It's not set by any SPS functions.
  51584. */
  51585. this.counter = 0;
  51586. /**
  51587. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  51588. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  51589. */
  51590. this.vars = {};
  51591. /**
  51592. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  51593. */
  51594. this._bSphereOnly = false;
  51595. /**
  51596. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  51597. */
  51598. this._bSphereRadiusFactor = 1.0;
  51599. this._positions = new Array();
  51600. this._indices = new Array();
  51601. this._normals = new Array();
  51602. this._colors = new Array();
  51603. this._uvs = new Array();
  51604. this._index = 0; // indices index
  51605. this._updatable = true;
  51606. this._pickable = false;
  51607. this._isVisibilityBoxLocked = false;
  51608. this._alwaysVisible = false;
  51609. this._depthSort = false;
  51610. this._shapeCounter = 0;
  51611. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  51612. this._color = new BABYLON.Color4(0, 0, 0, 0);
  51613. this._computeParticleColor = true;
  51614. this._computeParticleTexture = true;
  51615. this._computeParticleRotation = true;
  51616. this._computeParticleVertex = false;
  51617. this._computeBoundingBox = false;
  51618. this._depthSortParticles = true;
  51619. this._cam_axisZ = BABYLON.Vector3.Zero();
  51620. this._cam_axisY = BABYLON.Vector3.Zero();
  51621. this._cam_axisX = BABYLON.Vector3.Zero();
  51622. this._axisZ = BABYLON.Axis.Z;
  51623. this._camDir = BABYLON.Vector3.Zero();
  51624. this._camInvertedPosition = BABYLON.Vector3.Zero();
  51625. this._rotMatrix = new BABYLON.Matrix();
  51626. this._invertMatrix = new BABYLON.Matrix();
  51627. this._rotated = BABYLON.Vector3.Zero();
  51628. this._quaternion = new BABYLON.Quaternion();
  51629. this._vertex = BABYLON.Vector3.Zero();
  51630. this._normal = BABYLON.Vector3.Zero();
  51631. this._yaw = 0.0;
  51632. this._pitch = 0.0;
  51633. this._roll = 0.0;
  51634. this._halfroll = 0.0;
  51635. this._halfpitch = 0.0;
  51636. this._halfyaw = 0.0;
  51637. this._sinRoll = 0.0;
  51638. this._cosRoll = 0.0;
  51639. this._sinPitch = 0.0;
  51640. this._cosPitch = 0.0;
  51641. this._sinYaw = 0.0;
  51642. this._cosYaw = 0.0;
  51643. this._mustUnrotateFixedNormals = false;
  51644. this._minimum = BABYLON.Vector3.Zero();
  51645. this._maximum = BABYLON.Vector3.Zero();
  51646. this._minBbox = BABYLON.Vector3.Zero();
  51647. this._maxBbox = BABYLON.Vector3.Zero();
  51648. this._particlesIntersect = false;
  51649. this._depthSortFunction = function (p1, p2) {
  51650. return (p2.sqDistance - p1.sqDistance);
  51651. };
  51652. this._needs32Bits = false;
  51653. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  51654. this._scaledPivot = BABYLON.Vector3.Zero();
  51655. this._particleHasParent = false;
  51656. this.name = name;
  51657. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51658. this._camera = scene.activeCamera;
  51659. this._pickable = options ? options.isPickable : false;
  51660. this._depthSort = options ? options.enableDepthSort : false;
  51661. this._particlesIntersect = options ? options.particleIntersection : false;
  51662. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  51663. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  51664. if (options && options.updatable) {
  51665. this._updatable = options.updatable;
  51666. }
  51667. else {
  51668. this._updatable = true;
  51669. }
  51670. if (this._pickable) {
  51671. this.pickedParticles = [];
  51672. }
  51673. if (this._depthSort) {
  51674. this.depthSortedParticles = [];
  51675. }
  51676. }
  51677. /**
  51678. * Builds the SPS underlying mesh. Returns a standard Mesh.
  51679. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  51680. * @returns the created mesh
  51681. */
  51682. SolidParticleSystem.prototype.buildMesh = function () {
  51683. if (this.nbParticles === 0) {
  51684. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  51685. this.addShape(triangle, 1);
  51686. triangle.dispose();
  51687. }
  51688. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  51689. this._positions32 = new Float32Array(this._positions);
  51690. this._uvs32 = new Float32Array(this._uvs);
  51691. this._colors32 = new Float32Array(this._colors);
  51692. if (this.recomputeNormals) {
  51693. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  51694. }
  51695. this._normals32 = new Float32Array(this._normals);
  51696. this._fixedNormal32 = new Float32Array(this._normals);
  51697. if (this._mustUnrotateFixedNormals) {
  51698. this._unrotateFixedNormals();
  51699. }
  51700. var vertexData = new BABYLON.VertexData();
  51701. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  51702. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  51703. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  51704. if (this._uvs32) {
  51705. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  51706. ;
  51707. }
  51708. if (this._colors32) {
  51709. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  51710. }
  51711. var mesh = new BABYLON.Mesh(this.name, this._scene);
  51712. vertexData.applyToMesh(mesh, this._updatable);
  51713. this.mesh = mesh;
  51714. this.mesh.isPickable = this._pickable;
  51715. // free memory
  51716. if (!this._depthSort) {
  51717. this._indices = null;
  51718. }
  51719. this._positions = null;
  51720. this._normals = null;
  51721. this._uvs = null;
  51722. this._colors = null;
  51723. if (!this._updatable) {
  51724. this.particles.length = 0;
  51725. }
  51726. return mesh;
  51727. };
  51728. /**
  51729. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  51730. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  51731. * Thus the particles generated from `digest()` have their property `position` set yet.
  51732. * @param mesh ( Mesh ) is the mesh to be digested
  51733. * @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
  51734. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  51735. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  51736. * @returns the current SPS
  51737. */
  51738. SolidParticleSystem.prototype.digest = function (mesh, options) {
  51739. var size = (options && options.facetNb) || 1;
  51740. var number = (options && options.number) || 0;
  51741. var delta = (options && options.delta) || 0;
  51742. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51743. var meshInd = mesh.getIndices();
  51744. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51745. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  51746. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  51747. var f = 0; // facet counter
  51748. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  51749. // compute size from number
  51750. if (number) {
  51751. number = (number > totalFacets) ? totalFacets : number;
  51752. size = Math.round(totalFacets / number);
  51753. delta = 0;
  51754. }
  51755. else {
  51756. size = (size > totalFacets) ? totalFacets : size;
  51757. }
  51758. var facetPos = []; // submesh positions
  51759. var facetInd = []; // submesh indices
  51760. var facetUV = []; // submesh UV
  51761. var facetCol = []; // submesh colors
  51762. var barycenter = BABYLON.Vector3.Zero();
  51763. var sizeO = size;
  51764. while (f < totalFacets) {
  51765. size = sizeO + Math.floor((1 + delta) * Math.random());
  51766. if (f > totalFacets - size) {
  51767. size = totalFacets - f;
  51768. }
  51769. // reset temp arrays
  51770. facetPos.length = 0;
  51771. facetInd.length = 0;
  51772. facetUV.length = 0;
  51773. facetCol.length = 0;
  51774. // iterate over "size" facets
  51775. var fi = 0;
  51776. for (var j = f * 3; j < (f + size) * 3; j++) {
  51777. facetInd.push(fi);
  51778. var i = meshInd[j];
  51779. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  51780. if (meshUV) {
  51781. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  51782. }
  51783. if (meshCol) {
  51784. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  51785. }
  51786. fi++;
  51787. }
  51788. // create a model shape for each single particle
  51789. var idx = this.nbParticles;
  51790. var shape = this._posToShape(facetPos);
  51791. var shapeUV = this._uvsToShapeUV(facetUV);
  51792. // compute the barycenter of the shape
  51793. var v;
  51794. for (v = 0; v < shape.length; v++) {
  51795. barycenter.addInPlace(shape[v]);
  51796. }
  51797. barycenter.scaleInPlace(1 / shape.length);
  51798. // shift the shape from its barycenter to the origin
  51799. for (v = 0; v < shape.length; v++) {
  51800. shape[v].subtractInPlace(barycenter);
  51801. }
  51802. var bInfo;
  51803. if (this._particlesIntersect) {
  51804. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  51805. }
  51806. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  51807. // add the particle in the SPS
  51808. var currentPos = this._positions.length;
  51809. var currentInd = this._indices.length;
  51810. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  51811. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  51812. // initialize the particle position
  51813. this.particles[this.nbParticles].position.addInPlace(barycenter);
  51814. this._index += shape.length;
  51815. idx++;
  51816. this.nbParticles++;
  51817. this._shapeCounter++;
  51818. f += size;
  51819. }
  51820. return this;
  51821. };
  51822. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  51823. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  51824. var index = 0;
  51825. var idx = 0;
  51826. for (var p = 0; p < this.particles.length; p++) {
  51827. this._particle = this.particles[p];
  51828. this._shape = this._particle._model._shape;
  51829. if (this._particle.rotationQuaternion) {
  51830. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  51831. }
  51832. else {
  51833. this._yaw = this._particle.rotation.y;
  51834. this._pitch = this._particle.rotation.x;
  51835. this._roll = this._particle.rotation.z;
  51836. this._quaternionRotationYPR();
  51837. }
  51838. this._quaternionToRotationMatrix();
  51839. this._rotMatrix.invertToRef(this._invertMatrix);
  51840. for (var pt = 0; pt < this._shape.length; pt++) {
  51841. idx = index + pt * 3;
  51842. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  51843. this._fixedNormal32[idx] = this._normal.x;
  51844. this._fixedNormal32[idx + 1] = this._normal.y;
  51845. this._fixedNormal32[idx + 2] = this._normal.z;
  51846. }
  51847. index = idx + 3;
  51848. }
  51849. };
  51850. //reset copy
  51851. SolidParticleSystem.prototype._resetCopy = function () {
  51852. this._copy.position.x = 0;
  51853. this._copy.position.y = 0;
  51854. this._copy.position.z = 0;
  51855. this._copy.rotation.x = 0;
  51856. this._copy.rotation.y = 0;
  51857. this._copy.rotation.z = 0;
  51858. this._copy.rotationQuaternion = null;
  51859. this._copy.scaling.x = 1.0;
  51860. this._copy.scaling.y = 1.0;
  51861. this._copy.scaling.z = 1.0;
  51862. this._copy.uvs.x = 0;
  51863. this._copy.uvs.y = 0;
  51864. this._copy.uvs.z = 1.0;
  51865. this._copy.uvs.w = 1.0;
  51866. this._copy.color = null;
  51867. this._copy.translateFromPivot = false;
  51868. };
  51869. // _meshBuilder : inserts the shape model in the global SPS mesh
  51870. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  51871. var i;
  51872. var u = 0;
  51873. var c = 0;
  51874. var n = 0;
  51875. this._resetCopy();
  51876. if (options && options.positionFunction) {
  51877. options.positionFunction(this._copy, idx, idxInShape);
  51878. this._mustUnrotateFixedNormals = true;
  51879. }
  51880. if (this._copy.rotationQuaternion) {
  51881. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  51882. }
  51883. else {
  51884. this._yaw = this._copy.rotation.y;
  51885. this._pitch = this._copy.rotation.x;
  51886. this._roll = this._copy.rotation.z;
  51887. this._quaternionRotationYPR();
  51888. }
  51889. this._quaternionToRotationMatrix();
  51890. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  51891. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  51892. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  51893. if (this._copy.translateFromPivot) {
  51894. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  51895. }
  51896. else {
  51897. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  51898. }
  51899. for (i = 0; i < shape.length; i++) {
  51900. this._vertex.x = shape[i].x;
  51901. this._vertex.y = shape[i].y;
  51902. this._vertex.z = shape[i].z;
  51903. if (options && options.vertexFunction) {
  51904. options.vertexFunction(this._copy, this._vertex, i);
  51905. }
  51906. this._vertex.x *= this._copy.scaling.x;
  51907. this._vertex.y *= this._copy.scaling.y;
  51908. this._vertex.z *= this._copy.scaling.z;
  51909. this._vertex.x -= this._scaledPivot.x;
  51910. this._vertex.y -= this._scaledPivot.y;
  51911. this._vertex.z -= this._scaledPivot.z;
  51912. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  51913. this._rotated.addInPlace(this._pivotBackTranslation);
  51914. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  51915. if (meshUV) {
  51916. 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);
  51917. u += 2;
  51918. }
  51919. if (this._copy.color) {
  51920. this._color = this._copy.color;
  51921. }
  51922. else if (meshCol && meshCol[c] !== undefined) {
  51923. this._color.r = meshCol[c];
  51924. this._color.g = meshCol[c + 1];
  51925. this._color.b = meshCol[c + 2];
  51926. this._color.a = meshCol[c + 3];
  51927. }
  51928. else {
  51929. this._color.r = 1.0;
  51930. this._color.g = 1.0;
  51931. this._color.b = 1.0;
  51932. this._color.a = 1.0;
  51933. }
  51934. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  51935. c += 4;
  51936. if (!this.recomputeNormals && meshNor) {
  51937. this._normal.x = meshNor[n];
  51938. this._normal.y = meshNor[n + 1];
  51939. this._normal.z = meshNor[n + 2];
  51940. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  51941. normals.push(this._normal.x, this._normal.y, this._normal.z);
  51942. n += 3;
  51943. }
  51944. }
  51945. for (i = 0; i < meshInd.length; i++) {
  51946. var current_ind = p + meshInd[i];
  51947. indices.push(current_ind);
  51948. if (current_ind > 65535) {
  51949. this._needs32Bits = true;
  51950. }
  51951. }
  51952. if (this._pickable) {
  51953. var nbfaces = meshInd.length / 3;
  51954. for (i = 0; i < nbfaces; i++) {
  51955. this.pickedParticles.push({ idx: idx, faceId: i });
  51956. }
  51957. }
  51958. if (this._depthSort) {
  51959. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  51960. }
  51961. return this._copy;
  51962. };
  51963. // returns a shape array from positions array
  51964. SolidParticleSystem.prototype._posToShape = function (positions) {
  51965. var shape = [];
  51966. for (var i = 0; i < positions.length; i += 3) {
  51967. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  51968. }
  51969. return shape;
  51970. };
  51971. // returns a shapeUV array from a Vector4 uvs
  51972. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  51973. var shapeUV = [];
  51974. if (uvs) {
  51975. for (var i = 0; i < uvs.length; i++)
  51976. shapeUV.push(uvs[i]);
  51977. }
  51978. return shapeUV;
  51979. };
  51980. // adds a new particle object in the particles array
  51981. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  51982. if (bInfo === void 0) { bInfo = null; }
  51983. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  51984. this.particles.push(sp);
  51985. return sp;
  51986. };
  51987. /**
  51988. * Adds some particles to the SPS from the model shape. Returns the shape id.
  51989. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  51990. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  51991. * @param nb (positive integer) the number of particles to be created from this model
  51992. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  51993. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  51994. * @returns the number of shapes in the system
  51995. */
  51996. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  51997. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  51998. var meshInd = mesh.getIndices();
  51999. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52000. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52001. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52002. var bbInfo;
  52003. if (this._particlesIntersect) {
  52004. bbInfo = mesh.getBoundingInfo();
  52005. }
  52006. var shape = this._posToShape(meshPos);
  52007. var shapeUV = this._uvsToShapeUV(meshUV);
  52008. var posfunc = options ? options.positionFunction : null;
  52009. var vtxfunc = options ? options.vertexFunction : null;
  52010. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52011. // particles
  52012. var sp;
  52013. var currentCopy;
  52014. var idx = this.nbParticles;
  52015. for (var i = 0; i < nb; i++) {
  52016. var currentPos = this._positions.length;
  52017. var currentInd = this._indices.length;
  52018. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52019. if (this._updatable) {
  52020. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52021. sp.position.copyFrom(currentCopy.position);
  52022. sp.rotation.copyFrom(currentCopy.rotation);
  52023. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52024. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52025. }
  52026. if (currentCopy.color && sp.color) {
  52027. sp.color.copyFrom(currentCopy.color);
  52028. }
  52029. sp.scaling.copyFrom(currentCopy.scaling);
  52030. sp.uvs.copyFrom(currentCopy.uvs);
  52031. }
  52032. this._index += shape.length;
  52033. idx++;
  52034. }
  52035. this.nbParticles += nb;
  52036. this._shapeCounter++;
  52037. return this._shapeCounter - 1;
  52038. };
  52039. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52040. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52041. this._resetCopy();
  52042. if (particle._model._positionFunction) {
  52043. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52044. }
  52045. if (this._copy.rotationQuaternion) {
  52046. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52047. }
  52048. else {
  52049. this._yaw = this._copy.rotation.y;
  52050. this._pitch = this._copy.rotation.x;
  52051. this._roll = this._copy.rotation.z;
  52052. this._quaternionRotationYPR();
  52053. }
  52054. this._quaternionToRotationMatrix();
  52055. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52056. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52057. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52058. if (this._copy.translateFromPivot) {
  52059. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52060. }
  52061. else {
  52062. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52063. }
  52064. this._shape = particle._model._shape;
  52065. for (var pt = 0; pt < this._shape.length; pt++) {
  52066. this._vertex.x = this._shape[pt].x;
  52067. this._vertex.y = this._shape[pt].y;
  52068. this._vertex.z = this._shape[pt].z;
  52069. if (particle._model._vertexFunction) {
  52070. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52071. }
  52072. this._vertex.x *= this._copy.scaling.x;
  52073. this._vertex.y *= this._copy.scaling.y;
  52074. this._vertex.z *= this._copy.scaling.z;
  52075. this._vertex.x -= this._scaledPivot.x;
  52076. this._vertex.y -= this._scaledPivot.y;
  52077. this._vertex.z -= this._scaledPivot.z;
  52078. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52079. this._rotated.addInPlace(this._pivotBackTranslation);
  52080. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52081. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52082. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52083. }
  52084. particle.position.x = 0.0;
  52085. particle.position.y = 0.0;
  52086. particle.position.z = 0.0;
  52087. particle.rotation.x = 0.0;
  52088. particle.rotation.y = 0.0;
  52089. particle.rotation.z = 0.0;
  52090. particle.rotationQuaternion = null;
  52091. particle.scaling.x = 1.0;
  52092. particle.scaling.y = 1.0;
  52093. particle.scaling.z = 1.0;
  52094. particle.uvs.x = 0.0;
  52095. particle.uvs.y = 0.0;
  52096. particle.uvs.z = 1.0;
  52097. particle.uvs.w = 1.0;
  52098. particle.pivot.x = 0.0;
  52099. particle.pivot.y = 0.0;
  52100. particle.pivot.z = 0.0;
  52101. particle.translateFromPivot = false;
  52102. particle.parentId = null;
  52103. };
  52104. /**
  52105. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52106. * @returns the SPS.
  52107. */
  52108. SolidParticleSystem.prototype.rebuildMesh = function () {
  52109. for (var p = 0; p < this.particles.length; p++) {
  52110. this._rebuildParticle(this.particles[p]);
  52111. }
  52112. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52113. return this;
  52114. };
  52115. /**
  52116. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52117. * This method calls `updateParticle()` for each particle of the SPS.
  52118. * For an animated SPS, it is usually called within the render loop.
  52119. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52120. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52121. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52122. * @returns the SPS.
  52123. */
  52124. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52125. if (start === void 0) { start = 0; }
  52126. if (end === void 0) { end = this.nbParticles - 1; }
  52127. if (update === void 0) { update = true; }
  52128. if (!this._updatable) {
  52129. return this;
  52130. }
  52131. // custom beforeUpdate
  52132. this.beforeUpdateParticles(start, end, update);
  52133. this._cam_axisX.x = 1.0;
  52134. this._cam_axisX.y = 0.0;
  52135. this._cam_axisX.z = 0.0;
  52136. this._cam_axisY.x = 0.0;
  52137. this._cam_axisY.y = 1.0;
  52138. this._cam_axisY.z = 0.0;
  52139. this._cam_axisZ.x = 0.0;
  52140. this._cam_axisZ.y = 0.0;
  52141. this._cam_axisZ.z = 1.0;
  52142. // cases when the World Matrix is to be computed first
  52143. if (this.billboard || this._depthSort) {
  52144. this.mesh.computeWorldMatrix(true);
  52145. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52146. }
  52147. // if the particles will always face the camera
  52148. if (this.billboard) {
  52149. // compute the camera position and un-rotate it by the current mesh rotation
  52150. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52151. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52152. this._cam_axisZ.normalize();
  52153. // same for camera up vector extracted from the cam view matrix
  52154. var view = this._camera.getViewMatrix(true);
  52155. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52156. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52157. this._cam_axisY.normalize();
  52158. this._cam_axisX.normalize();
  52159. }
  52160. // if depthSort, compute the camera global position in the mesh local system
  52161. if (this._depthSort) {
  52162. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52163. }
  52164. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52165. var idx = 0; // current position index in the global array positions32
  52166. var index = 0; // position start index in the global array positions32 of the current particle
  52167. var colidx = 0; // current color index in the global array colors32
  52168. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52169. var uvidx = 0; // current uv index in the global array uvs32
  52170. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52171. var pt = 0; // current index in the particle model shape
  52172. if (this.mesh.isFacetDataEnabled) {
  52173. this._computeBoundingBox = true;
  52174. }
  52175. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52176. if (this._computeBoundingBox) {
  52177. if (start == 0 && end == this.nbParticles - 1) {
  52178. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52179. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52180. }
  52181. else {
  52182. if (this.mesh._boundingInfo) {
  52183. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52184. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52185. }
  52186. }
  52187. }
  52188. // particle loop
  52189. index = this.particles[start]._pos;
  52190. var vpos = (index / 3) | 0;
  52191. colorIndex = vpos * 4;
  52192. uvIndex = vpos * 2;
  52193. for (var p = start; p <= end; p++) {
  52194. this._particle = this.particles[p];
  52195. this._shape = this._particle._model._shape;
  52196. this._shapeUV = this._particle._model._shapeUV;
  52197. // call to custom user function to update the particle properties
  52198. this.updateParticle(this._particle);
  52199. // camera-particle distance for depth sorting
  52200. if (this._depthSort && this._depthSortParticles) {
  52201. var dsp = this.depthSortedParticles[p];
  52202. dsp.ind = this._particle._ind;
  52203. dsp.indicesLength = this._particle._model._indicesLength;
  52204. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52205. }
  52206. // skip the computations for inactive or already invisible particles
  52207. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52208. // increment indexes for the next particle
  52209. pt = this._shape.length;
  52210. index += pt * 3;
  52211. colorIndex += pt * 4;
  52212. uvIndex += pt * 2;
  52213. continue;
  52214. }
  52215. if (this._particle.isVisible) {
  52216. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52217. this._particleHasParent = (this._particle.parentId !== null);
  52218. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52219. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52220. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52221. // particle rotation matrix
  52222. if (this.billboard) {
  52223. this._particle.rotation.x = 0.0;
  52224. this._particle.rotation.y = 0.0;
  52225. }
  52226. if (this._computeParticleRotation || this.billboard) {
  52227. if (this._particle.rotationQuaternion) {
  52228. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52229. }
  52230. else {
  52231. this._yaw = this._particle.rotation.y;
  52232. this._pitch = this._particle.rotation.x;
  52233. this._roll = this._particle.rotation.z;
  52234. this._quaternionRotationYPR();
  52235. }
  52236. this._quaternionToRotationMatrix();
  52237. }
  52238. if (this._particleHasParent) {
  52239. this._parent = this.particles[this._particle.parentId];
  52240. 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];
  52241. 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];
  52242. 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];
  52243. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52244. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52245. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52246. if (this._computeParticleRotation || this.billboard) {
  52247. 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];
  52248. 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];
  52249. 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];
  52250. 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];
  52251. 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];
  52252. 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];
  52253. 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];
  52254. 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];
  52255. 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];
  52256. }
  52257. }
  52258. else {
  52259. this._particle._globalPosition.x = this._particle.position.x;
  52260. this._particle._globalPosition.y = this._particle.position.y;
  52261. this._particle._globalPosition.z = this._particle.position.z;
  52262. if (this._computeParticleRotation || this.billboard) {
  52263. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52264. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52265. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52266. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52267. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52268. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52269. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52270. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52271. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52272. }
  52273. }
  52274. if (this._particle.translateFromPivot) {
  52275. this._pivotBackTranslation.x = 0.0;
  52276. this._pivotBackTranslation.y = 0.0;
  52277. this._pivotBackTranslation.z = 0.0;
  52278. }
  52279. else {
  52280. this._pivotBackTranslation.x = this._scaledPivot.x;
  52281. this._pivotBackTranslation.y = this._scaledPivot.y;
  52282. this._pivotBackTranslation.z = this._scaledPivot.z;
  52283. }
  52284. // particle vertex loop
  52285. for (pt = 0; pt < this._shape.length; pt++) {
  52286. idx = index + pt * 3;
  52287. colidx = colorIndex + pt * 4;
  52288. uvidx = uvIndex + pt * 2;
  52289. this._vertex.x = this._shape[pt].x;
  52290. this._vertex.y = this._shape[pt].y;
  52291. this._vertex.z = this._shape[pt].z;
  52292. if (this._computeParticleVertex) {
  52293. this.updateParticleVertex(this._particle, this._vertex, pt);
  52294. }
  52295. // positions
  52296. this._vertex.x *= this._particle.scaling.x;
  52297. this._vertex.y *= this._particle.scaling.y;
  52298. this._vertex.z *= this._particle.scaling.z;
  52299. this._vertex.x -= this._scaledPivot.x;
  52300. this._vertex.y -= this._scaledPivot.y;
  52301. this._vertex.z -= this._scaledPivot.z;
  52302. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52303. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52304. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52305. this._rotated.x += this._pivotBackTranslation.x;
  52306. this._rotated.y += this._pivotBackTranslation.y;
  52307. this._rotated.z += this._pivotBackTranslation.z;
  52308. 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;
  52309. 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;
  52310. 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;
  52311. if (this._computeBoundingBox) {
  52312. if (this._positions32[idx] < this._minimum.x) {
  52313. this._minimum.x = this._positions32[idx];
  52314. }
  52315. if (this._positions32[idx] > this._maximum.x) {
  52316. this._maximum.x = this._positions32[idx];
  52317. }
  52318. if (this._positions32[idx + 1] < this._minimum.y) {
  52319. this._minimum.y = this._positions32[idx + 1];
  52320. }
  52321. if (this._positions32[idx + 1] > this._maximum.y) {
  52322. this._maximum.y = this._positions32[idx + 1];
  52323. }
  52324. if (this._positions32[idx + 2] < this._minimum.z) {
  52325. this._minimum.z = this._positions32[idx + 2];
  52326. }
  52327. if (this._positions32[idx + 2] > this._maximum.z) {
  52328. this._maximum.z = this._positions32[idx + 2];
  52329. }
  52330. }
  52331. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52332. if (!this._computeParticleVertex) {
  52333. this._normal.x = this._fixedNormal32[idx];
  52334. this._normal.y = this._fixedNormal32[idx + 1];
  52335. this._normal.z = this._fixedNormal32[idx + 2];
  52336. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52337. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52338. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52339. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52340. 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;
  52341. 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;
  52342. }
  52343. if (this._computeParticleColor && this._particle.color) {
  52344. this._colors32[colidx] = this._particle.color.r;
  52345. this._colors32[colidx + 1] = this._particle.color.g;
  52346. this._colors32[colidx + 2] = this._particle.color.b;
  52347. this._colors32[colidx + 3] = this._particle.color.a;
  52348. }
  52349. if (this._computeParticleTexture) {
  52350. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52351. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52352. }
  52353. }
  52354. }
  52355. else {
  52356. this._particle._stillInvisible = true; // mark the particle as invisible
  52357. for (pt = 0; pt < this._shape.length; pt++) {
  52358. idx = index + pt * 3;
  52359. colidx = colorIndex + pt * 4;
  52360. uvidx = uvIndex + pt * 2;
  52361. this._positions32[idx] = 0.0;
  52362. this._positions32[idx + 1] = 0.0;
  52363. this._positions32[idx + 2] = 0.0;
  52364. this._normals32[idx] = 0.0;
  52365. this._normals32[idx + 1] = 0.0;
  52366. this._normals32[idx + 2] = 0.0;
  52367. if (this._computeParticleColor && this._particle.color) {
  52368. this._colors32[colidx] = this._particle.color.r;
  52369. this._colors32[colidx + 1] = this._particle.color.g;
  52370. this._colors32[colidx + 2] = this._particle.color.b;
  52371. this._colors32[colidx + 3] = this._particle.color.a;
  52372. }
  52373. if (this._computeParticleTexture) {
  52374. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52375. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52376. }
  52377. }
  52378. }
  52379. // if the particle intersections must be computed : update the bbInfo
  52380. if (this._particlesIntersect) {
  52381. var bInfo = this._particle._boundingInfo;
  52382. var bBox = bInfo.boundingBox;
  52383. var bSphere = bInfo.boundingSphere;
  52384. if (!this._bSphereOnly) {
  52385. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52386. for (var b = 0; b < bBox.vectors.length; b++) {
  52387. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52388. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52389. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52390. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52391. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52392. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52393. 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;
  52394. 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;
  52395. 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;
  52396. }
  52397. bBox._update(this.mesh._worldMatrix);
  52398. }
  52399. // place and scale the particle bouding sphere in the SPS local system, then update it
  52400. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52401. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52402. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52403. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52404. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52405. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52406. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52407. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52408. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52409. 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));
  52410. bSphere._update(this.mesh._worldMatrix);
  52411. }
  52412. // increment indexes for the next particle
  52413. index = idx + 3;
  52414. colorIndex = colidx + 4;
  52415. uvIndex = uvidx + 2;
  52416. }
  52417. // if the VBO must be updated
  52418. if (update) {
  52419. if (this._computeParticleColor) {
  52420. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52421. }
  52422. if (this._computeParticleTexture) {
  52423. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52424. }
  52425. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52426. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52427. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52428. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52429. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52430. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52431. for (var i = 0; i < this._normals32.length; i++) {
  52432. this._fixedNormal32[i] = this._normals32[i];
  52433. }
  52434. }
  52435. if (!this.mesh.areNormalsFrozen) {
  52436. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52437. }
  52438. }
  52439. if (this._depthSort && this._depthSortParticles) {
  52440. this.depthSortedParticles.sort(this._depthSortFunction);
  52441. var dspl = this.depthSortedParticles.length;
  52442. var sorted = 0;
  52443. var lind = 0;
  52444. var sind = 0;
  52445. var sid = 0;
  52446. for (sorted = 0; sorted < dspl; sorted++) {
  52447. lind = this.depthSortedParticles[sorted].indicesLength;
  52448. sind = this.depthSortedParticles[sorted].ind;
  52449. for (var i = 0; i < lind; i++) {
  52450. this._indices32[sid] = this._indices[sind + i];
  52451. sid++;
  52452. }
  52453. }
  52454. this.mesh.updateIndices(this._indices32);
  52455. }
  52456. }
  52457. if (this._computeBoundingBox) {
  52458. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52459. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52460. }
  52461. this.afterUpdateParticles(start, end, update);
  52462. return this;
  52463. };
  52464. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52465. this._halfroll = this._roll * 0.5;
  52466. this._halfpitch = this._pitch * 0.5;
  52467. this._halfyaw = this._yaw * 0.5;
  52468. this._sinRoll = Math.sin(this._halfroll);
  52469. this._cosRoll = Math.cos(this._halfroll);
  52470. this._sinPitch = Math.sin(this._halfpitch);
  52471. this._cosPitch = Math.cos(this._halfpitch);
  52472. this._sinYaw = Math.sin(this._halfyaw);
  52473. this._cosYaw = Math.cos(this._halfyaw);
  52474. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52475. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52476. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52477. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52478. };
  52479. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52480. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52481. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52482. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52483. this._rotMatrix.m[3] = 0;
  52484. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52485. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52486. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52487. this._rotMatrix.m[7] = 0;
  52488. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52489. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52490. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52491. this._rotMatrix.m[11] = 0;
  52492. this._rotMatrix.m[12] = 0;
  52493. this._rotMatrix.m[13] = 0;
  52494. this._rotMatrix.m[14] = 0;
  52495. this._rotMatrix.m[15] = 1.0;
  52496. };
  52497. /**
  52498. * Disposes the SPS.
  52499. */
  52500. SolidParticleSystem.prototype.dispose = function () {
  52501. this.mesh.dispose();
  52502. this.vars = null;
  52503. // drop references to internal big arrays for the GC
  52504. this._positions = null;
  52505. this._indices = null;
  52506. this._normals = null;
  52507. this._uvs = null;
  52508. this._colors = null;
  52509. this._indices32 = null;
  52510. this._positions32 = null;
  52511. this._normals32 = null;
  52512. this._fixedNormal32 = null;
  52513. this._uvs32 = null;
  52514. this._colors32 = null;
  52515. this.pickedParticles = null;
  52516. };
  52517. /**
  52518. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52519. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52520. * @returns the SPS.
  52521. */
  52522. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52523. if (!this._isVisibilityBoxLocked) {
  52524. this.mesh.refreshBoundingInfo();
  52525. }
  52526. return this;
  52527. };
  52528. /**
  52529. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52530. * @param size the size (float) of the visibility box
  52531. * note : this doesn't lock the SPS mesh bounding box.
  52532. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52533. */
  52534. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52535. var vis = size / 2;
  52536. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52537. };
  52538. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52539. /**
  52540. * Gets whether the SPS as always visible or not
  52541. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52542. */
  52543. get: function () {
  52544. return this._alwaysVisible;
  52545. },
  52546. /**
  52547. * Sets the SPS as always visible or not
  52548. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52549. */
  52550. set: function (val) {
  52551. this._alwaysVisible = val;
  52552. this.mesh.alwaysSelectAsActiveMesh = val;
  52553. },
  52554. enumerable: true,
  52555. configurable: true
  52556. });
  52557. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52558. /**
  52559. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52560. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52561. */
  52562. get: function () {
  52563. return this._isVisibilityBoxLocked;
  52564. },
  52565. /**
  52566. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52567. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52568. */
  52569. set: function (val) {
  52570. this._isVisibilityBoxLocked = val;
  52571. var boundingInfo = this.mesh.getBoundingInfo();
  52572. boundingInfo.isLocked = val;
  52573. },
  52574. enumerable: true,
  52575. configurable: true
  52576. });
  52577. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  52578. /**
  52579. * Gets if `setParticles()` computes the particle rotations or not.
  52580. * Default value : true. The SPS is faster when it's set to false.
  52581. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52582. */
  52583. get: function () {
  52584. return this._computeParticleRotation;
  52585. },
  52586. /**
  52587. * Tells to `setParticles()` to compute the particle rotations or not.
  52588. * Default value : true. The SPS is faster when it's set to false.
  52589. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  52590. */
  52591. set: function (val) {
  52592. this._computeParticleRotation = val;
  52593. },
  52594. enumerable: true,
  52595. configurable: true
  52596. });
  52597. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  52598. /**
  52599. * Gets if `setParticles()` computes the particle colors or not.
  52600. * Default value : true. The SPS is faster when it's set to false.
  52601. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52602. */
  52603. get: function () {
  52604. return this._computeParticleColor;
  52605. },
  52606. /**
  52607. * Tells to `setParticles()` to compute the particle colors or not.
  52608. * Default value : true. The SPS is faster when it's set to false.
  52609. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  52610. */
  52611. set: function (val) {
  52612. this._computeParticleColor = val;
  52613. },
  52614. enumerable: true,
  52615. configurable: true
  52616. });
  52617. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  52618. /**
  52619. * Gets if `setParticles()` computes the particle textures or not.
  52620. * Default value : true. The SPS is faster when it's set to false.
  52621. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  52622. */
  52623. get: function () {
  52624. return this._computeParticleTexture;
  52625. },
  52626. set: function (val) {
  52627. this._computeParticleTexture = val;
  52628. },
  52629. enumerable: true,
  52630. configurable: true
  52631. });
  52632. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  52633. /**
  52634. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  52635. * Default value : false. The SPS is faster when it's set to false.
  52636. * Note : the particle custom vertex positions aren't stored values.
  52637. */
  52638. get: function () {
  52639. return this._computeParticleVertex;
  52640. },
  52641. /**
  52642. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  52643. * Default value : false. The SPS is faster when it's set to false.
  52644. * Note : the particle custom vertex positions aren't stored values.
  52645. */
  52646. set: function (val) {
  52647. this._computeParticleVertex = val;
  52648. },
  52649. enumerable: true,
  52650. configurable: true
  52651. });
  52652. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  52653. /**
  52654. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  52655. */
  52656. get: function () {
  52657. return this._computeBoundingBox;
  52658. },
  52659. /**
  52660. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  52661. */
  52662. set: function (val) {
  52663. this._computeBoundingBox = val;
  52664. },
  52665. enumerable: true,
  52666. configurable: true
  52667. });
  52668. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  52669. /**
  52670. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  52671. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52672. * Default : `true`
  52673. */
  52674. get: function () {
  52675. return this._depthSortParticles;
  52676. },
  52677. /**
  52678. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  52679. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  52680. * Default : `true`
  52681. */
  52682. set: function (val) {
  52683. this._depthSortParticles = val;
  52684. },
  52685. enumerable: true,
  52686. configurable: true
  52687. });
  52688. // =======================================================================
  52689. // Particle behavior logic
  52690. // these following methods may be overwritten by the user to fit his needs
  52691. /**
  52692. * This function does nothing. It may be overwritten to set all the particle first values.
  52693. * The SPS doesn't call this function, you may have to call it by your own.
  52694. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52695. */
  52696. SolidParticleSystem.prototype.initParticles = function () {
  52697. };
  52698. /**
  52699. * This function does nothing. It may be overwritten to recycle a particle.
  52700. * The SPS doesn't call this function, you may have to call it by your own.
  52701. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52702. * @param particle The particle to recycle
  52703. * @returns the recycled particle
  52704. */
  52705. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  52706. return particle;
  52707. };
  52708. /**
  52709. * Updates a particle : this function should be overwritten by the user.
  52710. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  52711. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  52712. * @example : just set a particle position or velocity and recycle conditions
  52713. * @param particle The particle to update
  52714. * @returns the updated particle
  52715. */
  52716. SolidParticleSystem.prototype.updateParticle = function (particle) {
  52717. return particle;
  52718. };
  52719. /**
  52720. * Updates a vertex of a particle : it can be overwritten by the user.
  52721. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  52722. * @param particle the current particle
  52723. * @param vertex the current index of the current particle
  52724. * @param pt the index of the current vertex in the particle shape
  52725. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  52726. * @example : just set a vertex particle position
  52727. * @returns the updated vertex
  52728. */
  52729. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  52730. return vertex;
  52731. };
  52732. /**
  52733. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  52734. * This does nothing and may be overwritten by the user.
  52735. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52736. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52737. * @param update the boolean update value actually passed to setParticles()
  52738. */
  52739. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  52740. };
  52741. /**
  52742. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  52743. * This will be passed three parameters.
  52744. * This does nothing and may be overwritten by the user.
  52745. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52746. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  52747. * @param update the boolean update value actually passed to setParticles()
  52748. */
  52749. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  52750. };
  52751. return SolidParticleSystem;
  52752. }());
  52753. BABYLON.SolidParticleSystem = SolidParticleSystem;
  52754. })(BABYLON || (BABYLON = {}));
  52755. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  52756. var BABYLON;
  52757. (function (BABYLON) {
  52758. var ShaderMaterial = /** @class */ (function (_super) {
  52759. __extends(ShaderMaterial, _super);
  52760. function ShaderMaterial(name, scene, shaderPath, options) {
  52761. var _this = _super.call(this, name, scene) || this;
  52762. _this._textures = {};
  52763. _this._textureArrays = {};
  52764. _this._floats = {};
  52765. _this._ints = {};
  52766. _this._floatsArrays = {};
  52767. _this._colors3 = {};
  52768. _this._colors3Arrays = {};
  52769. _this._colors4 = {};
  52770. _this._vectors2 = {};
  52771. _this._vectors3 = {};
  52772. _this._vectors4 = {};
  52773. _this._matrices = {};
  52774. _this._matrices3x3 = {};
  52775. _this._matrices2x2 = {};
  52776. _this._vectors2Arrays = {};
  52777. _this._vectors3Arrays = {};
  52778. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  52779. _this._shaderPath = shaderPath;
  52780. options.needAlphaBlending = options.needAlphaBlending || false;
  52781. options.needAlphaTesting = options.needAlphaTesting || false;
  52782. options.attributes = options.attributes || ["position", "normal", "uv"];
  52783. options.uniforms = options.uniforms || ["worldViewProjection"];
  52784. options.uniformBuffers = options.uniformBuffers || [];
  52785. options.samplers = options.samplers || [];
  52786. options.defines = options.defines || [];
  52787. _this._options = options;
  52788. return _this;
  52789. }
  52790. ShaderMaterial.prototype.getClassName = function () {
  52791. return "ShaderMaterial";
  52792. };
  52793. ShaderMaterial.prototype.needAlphaBlending = function () {
  52794. return this._options.needAlphaBlending;
  52795. };
  52796. ShaderMaterial.prototype.needAlphaTesting = function () {
  52797. return this._options.needAlphaTesting;
  52798. };
  52799. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  52800. if (this._options.uniforms.indexOf(uniformName) === -1) {
  52801. this._options.uniforms.push(uniformName);
  52802. }
  52803. };
  52804. ShaderMaterial.prototype.setTexture = function (name, texture) {
  52805. if (this._options.samplers.indexOf(name) === -1) {
  52806. this._options.samplers.push(name);
  52807. }
  52808. this._textures[name] = texture;
  52809. return this;
  52810. };
  52811. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  52812. if (this._options.samplers.indexOf(name) === -1) {
  52813. this._options.samplers.push(name);
  52814. }
  52815. this._checkUniform(name);
  52816. this._textureArrays[name] = textures;
  52817. return this;
  52818. };
  52819. ShaderMaterial.prototype.setFloat = function (name, value) {
  52820. this._checkUniform(name);
  52821. this._floats[name] = value;
  52822. return this;
  52823. };
  52824. ShaderMaterial.prototype.setInt = function (name, value) {
  52825. this._checkUniform(name);
  52826. this._ints[name] = value;
  52827. return this;
  52828. };
  52829. ShaderMaterial.prototype.setFloats = function (name, value) {
  52830. this._checkUniform(name);
  52831. this._floatsArrays[name] = value;
  52832. return this;
  52833. };
  52834. ShaderMaterial.prototype.setColor3 = function (name, value) {
  52835. this._checkUniform(name);
  52836. this._colors3[name] = value;
  52837. return this;
  52838. };
  52839. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  52840. this._checkUniform(name);
  52841. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  52842. color.toArray(arr, arr.length);
  52843. return arr;
  52844. }, []);
  52845. return this;
  52846. };
  52847. ShaderMaterial.prototype.setColor4 = function (name, value) {
  52848. this._checkUniform(name);
  52849. this._colors4[name] = value;
  52850. return this;
  52851. };
  52852. ShaderMaterial.prototype.setVector2 = function (name, value) {
  52853. this._checkUniform(name);
  52854. this._vectors2[name] = value;
  52855. return this;
  52856. };
  52857. ShaderMaterial.prototype.setVector3 = function (name, value) {
  52858. this._checkUniform(name);
  52859. this._vectors3[name] = value;
  52860. return this;
  52861. };
  52862. ShaderMaterial.prototype.setVector4 = function (name, value) {
  52863. this._checkUniform(name);
  52864. this._vectors4[name] = value;
  52865. return this;
  52866. };
  52867. ShaderMaterial.prototype.setMatrix = function (name, value) {
  52868. this._checkUniform(name);
  52869. this._matrices[name] = value;
  52870. return this;
  52871. };
  52872. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  52873. this._checkUniform(name);
  52874. this._matrices3x3[name] = value;
  52875. return this;
  52876. };
  52877. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  52878. this._checkUniform(name);
  52879. this._matrices2x2[name] = value;
  52880. return this;
  52881. };
  52882. ShaderMaterial.prototype.setArray2 = function (name, value) {
  52883. this._checkUniform(name);
  52884. this._vectors2Arrays[name] = value;
  52885. return this;
  52886. };
  52887. ShaderMaterial.prototype.setArray3 = function (name, value) {
  52888. this._checkUniform(name);
  52889. this._vectors3Arrays[name] = value;
  52890. return this;
  52891. };
  52892. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  52893. if (!mesh) {
  52894. return true;
  52895. }
  52896. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  52897. return false;
  52898. }
  52899. return false;
  52900. };
  52901. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  52902. var scene = this.getScene();
  52903. var engine = scene.getEngine();
  52904. if (!this.checkReadyOnEveryCall) {
  52905. if (this._renderId === scene.getRenderId()) {
  52906. if (this._checkCache(scene, mesh, useInstances)) {
  52907. return true;
  52908. }
  52909. }
  52910. }
  52911. // Instances
  52912. var defines = [];
  52913. var attribs = [];
  52914. var fallbacks = new BABYLON.EffectFallbacks();
  52915. if (useInstances) {
  52916. defines.push("#define INSTANCES");
  52917. }
  52918. for (var index = 0; index < this._options.defines.length; index++) {
  52919. defines.push(this._options.defines[index]);
  52920. }
  52921. for (var index = 0; index < this._options.attributes.length; index++) {
  52922. attribs.push(this._options.attributes[index]);
  52923. }
  52924. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  52925. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52926. defines.push("#define VERTEXCOLOR");
  52927. }
  52928. // Bones
  52929. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  52930. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52931. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52932. if (mesh.numBoneInfluencers > 4) {
  52933. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52934. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52935. }
  52936. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52937. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52938. fallbacks.addCPUSkinningFallback(0, mesh);
  52939. if (this._options.uniforms.indexOf("mBones") === -1) {
  52940. this._options.uniforms.push("mBones");
  52941. }
  52942. }
  52943. else {
  52944. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52945. }
  52946. // Textures
  52947. for (var name in this._textures) {
  52948. if (!this._textures[name].isReady()) {
  52949. return false;
  52950. }
  52951. }
  52952. // Alpha test
  52953. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  52954. defines.push("#define ALPHATEST");
  52955. }
  52956. var previousEffect = this._effect;
  52957. var join = defines.join("\n");
  52958. this._effect = engine.createEffect(this._shaderPath, {
  52959. attributes: attribs,
  52960. uniformsNames: this._options.uniforms,
  52961. uniformBuffersNames: this._options.uniformBuffers,
  52962. samplers: this._options.samplers,
  52963. defines: join,
  52964. fallbacks: fallbacks,
  52965. onCompiled: this.onCompiled,
  52966. onError: this.onError
  52967. }, engine);
  52968. if (!this._effect.isReady()) {
  52969. return false;
  52970. }
  52971. if (previousEffect !== this._effect) {
  52972. scene.resetCachedMaterial();
  52973. }
  52974. this._renderId = scene.getRenderId();
  52975. return true;
  52976. };
  52977. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52978. var scene = this.getScene();
  52979. if (!this._effect) {
  52980. return;
  52981. }
  52982. if (this._options.uniforms.indexOf("world") !== -1) {
  52983. this._effect.setMatrix("world", world);
  52984. }
  52985. if (this._options.uniforms.indexOf("worldView") !== -1) {
  52986. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  52987. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  52988. }
  52989. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  52990. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  52991. }
  52992. };
  52993. ShaderMaterial.prototype.bind = function (world, mesh) {
  52994. // Std values
  52995. this.bindOnlyWorldMatrix(world);
  52996. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  52997. if (this._options.uniforms.indexOf("view") !== -1) {
  52998. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  52999. }
  53000. if (this._options.uniforms.indexOf("projection") !== -1) {
  53001. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53002. }
  53003. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53004. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53005. }
  53006. // Bones
  53007. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53008. var name;
  53009. // Texture
  53010. for (name in this._textures) {
  53011. this._effect.setTexture(name, this._textures[name]);
  53012. }
  53013. // Texture arrays
  53014. for (name in this._textureArrays) {
  53015. this._effect.setTextureArray(name, this._textureArrays[name]);
  53016. }
  53017. // Int
  53018. for (name in this._ints) {
  53019. this._effect.setInt(name, this._ints[name]);
  53020. }
  53021. // Float
  53022. for (name in this._floats) {
  53023. this._effect.setFloat(name, this._floats[name]);
  53024. }
  53025. // Floats
  53026. for (name in this._floatsArrays) {
  53027. this._effect.setArray(name, this._floatsArrays[name]);
  53028. }
  53029. // Color3
  53030. for (name in this._colors3) {
  53031. this._effect.setColor3(name, this._colors3[name]);
  53032. }
  53033. for (name in this._colors3Arrays) {
  53034. this._effect.setArray3(name, this._colors3Arrays[name]);
  53035. }
  53036. // Color4
  53037. for (name in this._colors4) {
  53038. var color = this._colors4[name];
  53039. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53040. }
  53041. // Vector2
  53042. for (name in this._vectors2) {
  53043. this._effect.setVector2(name, this._vectors2[name]);
  53044. }
  53045. // Vector3
  53046. for (name in this._vectors3) {
  53047. this._effect.setVector3(name, this._vectors3[name]);
  53048. }
  53049. // Vector4
  53050. for (name in this._vectors4) {
  53051. this._effect.setVector4(name, this._vectors4[name]);
  53052. }
  53053. // Matrix
  53054. for (name in this._matrices) {
  53055. this._effect.setMatrix(name, this._matrices[name]);
  53056. }
  53057. // Matrix 3x3
  53058. for (name in this._matrices3x3) {
  53059. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53060. }
  53061. // Matrix 2x2
  53062. for (name in this._matrices2x2) {
  53063. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53064. }
  53065. // Vector2Array
  53066. for (name in this._vectors2Arrays) {
  53067. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53068. }
  53069. // Vector3Array
  53070. for (name in this._vectors3Arrays) {
  53071. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53072. }
  53073. }
  53074. this._afterBind(mesh);
  53075. };
  53076. ShaderMaterial.prototype.getActiveTextures = function () {
  53077. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53078. for (var name in this._textures) {
  53079. activeTextures.push(this._textures[name]);
  53080. }
  53081. for (var name in this._textureArrays) {
  53082. var array = this._textureArrays[name];
  53083. for (var index = 0; index < array.length; index++) {
  53084. activeTextures.push(array[index]);
  53085. }
  53086. }
  53087. return activeTextures;
  53088. };
  53089. ShaderMaterial.prototype.hasTexture = function (texture) {
  53090. if (_super.prototype.hasTexture.call(this, texture)) {
  53091. return true;
  53092. }
  53093. for (var name in this._textures) {
  53094. if (this._textures[name] === texture) {
  53095. return true;
  53096. }
  53097. }
  53098. for (var name in this._textureArrays) {
  53099. var array = this._textureArrays[name];
  53100. for (var index = 0; index < array.length; index++) {
  53101. if (array[index] === texture) {
  53102. return true;
  53103. }
  53104. }
  53105. }
  53106. return false;
  53107. };
  53108. ShaderMaterial.prototype.clone = function (name) {
  53109. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53110. return newShaderMaterial;
  53111. };
  53112. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53113. if (forceDisposeTextures) {
  53114. var name;
  53115. for (name in this._textures) {
  53116. this._textures[name].dispose();
  53117. }
  53118. for (name in this._textureArrays) {
  53119. var array = this._textureArrays[name];
  53120. for (var index = 0; index < array.length; index++) {
  53121. array[index].dispose();
  53122. }
  53123. }
  53124. }
  53125. this._textures = {};
  53126. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53127. };
  53128. ShaderMaterial.prototype.serialize = function () {
  53129. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53130. serializationObject.customType = "BABYLON.ShaderMaterial";
  53131. serializationObject.options = this._options;
  53132. serializationObject.shaderPath = this._shaderPath;
  53133. var name;
  53134. // Texture
  53135. serializationObject.textures = {};
  53136. for (name in this._textures) {
  53137. serializationObject.textures[name] = this._textures[name].serialize();
  53138. }
  53139. // Texture arrays
  53140. serializationObject.textureArrays = {};
  53141. for (name in this._textureArrays) {
  53142. serializationObject.textureArrays[name] = [];
  53143. var array = this._textureArrays[name];
  53144. for (var index = 0; index < array.length; index++) {
  53145. serializationObject.textureArrays[name].push(array[index].serialize());
  53146. }
  53147. }
  53148. // Float
  53149. serializationObject.floats = {};
  53150. for (name in this._floats) {
  53151. serializationObject.floats[name] = this._floats[name];
  53152. }
  53153. // Float s
  53154. serializationObject.FloatArrays = {};
  53155. for (name in this._floatsArrays) {
  53156. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53157. }
  53158. // Color3
  53159. serializationObject.colors3 = {};
  53160. for (name in this._colors3) {
  53161. serializationObject.colors3[name] = this._colors3[name].asArray();
  53162. }
  53163. // Color3 array
  53164. serializationObject.colors3Arrays = {};
  53165. for (name in this._colors3Arrays) {
  53166. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53167. }
  53168. // Color4
  53169. serializationObject.colors4 = {};
  53170. for (name in this._colors4) {
  53171. serializationObject.colors4[name] = this._colors4[name].asArray();
  53172. }
  53173. // Vector2
  53174. serializationObject.vectors2 = {};
  53175. for (name in this._vectors2) {
  53176. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53177. }
  53178. // Vector3
  53179. serializationObject.vectors3 = {};
  53180. for (name in this._vectors3) {
  53181. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53182. }
  53183. // Vector4
  53184. serializationObject.vectors4 = {};
  53185. for (name in this._vectors4) {
  53186. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53187. }
  53188. // Matrix
  53189. serializationObject.matrices = {};
  53190. for (name in this._matrices) {
  53191. serializationObject.matrices[name] = this._matrices[name].asArray();
  53192. }
  53193. // Matrix 3x3
  53194. serializationObject.matrices3x3 = {};
  53195. for (name in this._matrices3x3) {
  53196. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53197. }
  53198. // Matrix 2x2
  53199. serializationObject.matrices2x2 = {};
  53200. for (name in this._matrices2x2) {
  53201. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53202. }
  53203. // Vector2Array
  53204. serializationObject.vectors2Arrays = {};
  53205. for (name in this._vectors2Arrays) {
  53206. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53207. }
  53208. // Vector3Array
  53209. serializationObject.vectors3Arrays = {};
  53210. for (name in this._vectors3Arrays) {
  53211. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53212. }
  53213. return serializationObject;
  53214. };
  53215. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53216. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53217. var name;
  53218. // Texture
  53219. for (name in source.textures) {
  53220. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53221. }
  53222. // Texture arrays
  53223. for (name in source.textureArrays) {
  53224. var array = source.textureArrays[name];
  53225. var textureArray = new Array();
  53226. for (var index = 0; index < array.length; index++) {
  53227. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53228. }
  53229. material.setTextureArray(name, textureArray);
  53230. }
  53231. // Float
  53232. for (name in source.floats) {
  53233. material.setFloat(name, source.floats[name]);
  53234. }
  53235. // Float s
  53236. for (name in source.floatsArrays) {
  53237. material.setFloats(name, source.floatsArrays[name]);
  53238. }
  53239. // Color3
  53240. for (name in source.colors3) {
  53241. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53242. }
  53243. // Color3 arrays
  53244. for (name in source.colors3Arrays) {
  53245. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53246. if (i % 3 === 0) {
  53247. arr.push([num]);
  53248. }
  53249. else {
  53250. arr[arr.length - 1].push(num);
  53251. }
  53252. return arr;
  53253. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53254. material.setColor3Array(name, colors);
  53255. }
  53256. // Color4
  53257. for (name in source.colors4) {
  53258. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53259. }
  53260. // Vector2
  53261. for (name in source.vectors2) {
  53262. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53263. }
  53264. // Vector3
  53265. for (name in source.vectors3) {
  53266. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53267. }
  53268. // Vector4
  53269. for (name in source.vectors4) {
  53270. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53271. }
  53272. // Matrix
  53273. for (name in source.matrices) {
  53274. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53275. }
  53276. // Matrix 3x3
  53277. for (name in source.matrices3x3) {
  53278. material.setMatrix3x3(name, source.matrices3x3[name]);
  53279. }
  53280. // Matrix 2x2
  53281. for (name in source.matrices2x2) {
  53282. material.setMatrix2x2(name, source.matrices2x2[name]);
  53283. }
  53284. // Vector2Array
  53285. for (name in source.vectors2Arrays) {
  53286. material.setArray2(name, source.vectors2Arrays[name]);
  53287. }
  53288. // Vector3Array
  53289. for (name in source.vectors3Arrays) {
  53290. material.setArray3(name, source.vectors3Arrays[name]);
  53291. }
  53292. return material;
  53293. };
  53294. return ShaderMaterial;
  53295. }(BABYLON.Material));
  53296. BABYLON.ShaderMaterial = ShaderMaterial;
  53297. })(BABYLON || (BABYLON = {}));
  53298. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53299. var BABYLON;
  53300. (function (BABYLON) {
  53301. var GroundMesh = /** @class */ (function (_super) {
  53302. __extends(GroundMesh, _super);
  53303. function GroundMesh(name, scene) {
  53304. var _this = _super.call(this, name, scene) || this;
  53305. _this.generateOctree = false;
  53306. return _this;
  53307. }
  53308. GroundMesh.prototype.getClassName = function () {
  53309. return "GroundMesh";
  53310. };
  53311. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53312. get: function () {
  53313. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53314. },
  53315. enumerable: true,
  53316. configurable: true
  53317. });
  53318. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53319. get: function () {
  53320. return this._subdivisionsX;
  53321. },
  53322. enumerable: true,
  53323. configurable: true
  53324. });
  53325. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53326. get: function () {
  53327. return this._subdivisionsY;
  53328. },
  53329. enumerable: true,
  53330. configurable: true
  53331. });
  53332. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53333. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53334. this._subdivisionsX = chunksCount;
  53335. this._subdivisionsY = chunksCount;
  53336. this.subdivide(chunksCount);
  53337. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53338. };
  53339. /**
  53340. * Returns a height (y) value in the Worl system :
  53341. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53342. * Returns the ground y position if (x, z) are outside the ground surface.
  53343. */
  53344. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53345. var world = this.getWorldMatrix();
  53346. var invMat = BABYLON.Tmp.Matrix[5];
  53347. world.invertToRef(invMat);
  53348. var tmpVect = BABYLON.Tmp.Vector3[8];
  53349. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53350. x = tmpVect.x;
  53351. z = tmpVect.z;
  53352. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53353. return this.position.y;
  53354. }
  53355. if (!this._heightQuads || this._heightQuads.length == 0) {
  53356. this._initHeightQuads();
  53357. this._computeHeightQuads();
  53358. }
  53359. var facet = this._getFacetAt(x, z);
  53360. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53361. // return y in the World system
  53362. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53363. return tmpVect.y;
  53364. };
  53365. /**
  53366. * Returns a normalized vector (Vector3) orthogonal to the ground
  53367. * at the ground coordinates (x, z) expressed in the World system.
  53368. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53369. */
  53370. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53371. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53372. this.getNormalAtCoordinatesToRef(x, z, normal);
  53373. return normal;
  53374. };
  53375. /**
  53376. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53377. * at the ground coordinates (x, z) expressed in the World system.
  53378. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53379. * Returns the GroundMesh.
  53380. */
  53381. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53382. var world = this.getWorldMatrix();
  53383. var tmpMat = BABYLON.Tmp.Matrix[5];
  53384. world.invertToRef(tmpMat);
  53385. var tmpVect = BABYLON.Tmp.Vector3[8];
  53386. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53387. x = tmpVect.x;
  53388. z = tmpVect.z;
  53389. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53390. return this;
  53391. }
  53392. if (!this._heightQuads || this._heightQuads.length == 0) {
  53393. this._initHeightQuads();
  53394. this._computeHeightQuads();
  53395. }
  53396. var facet = this._getFacetAt(x, z);
  53397. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53398. return this;
  53399. };
  53400. /**
  53401. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53402. * if the ground has been updated.
  53403. * This can be used in the render loop.
  53404. * Returns the GroundMesh.
  53405. */
  53406. GroundMesh.prototype.updateCoordinateHeights = function () {
  53407. if (!this._heightQuads || this._heightQuads.length == 0) {
  53408. this._initHeightQuads();
  53409. }
  53410. this._computeHeightQuads();
  53411. return this;
  53412. };
  53413. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53414. GroundMesh.prototype._getFacetAt = function (x, z) {
  53415. // retrieve col and row from x, z coordinates in the ground local system
  53416. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53417. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53418. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53419. var facet;
  53420. if (z < quad.slope.x * x + quad.slope.y) {
  53421. facet = quad.facet1;
  53422. }
  53423. else {
  53424. facet = quad.facet2;
  53425. }
  53426. return facet;
  53427. };
  53428. // Creates and populates the heightMap array with "facet" elements :
  53429. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53430. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53431. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53432. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53433. // Returns the GroundMesh.
  53434. GroundMesh.prototype._initHeightQuads = function () {
  53435. var subdivisionsX = this._subdivisionsX;
  53436. var subdivisionsY = this._subdivisionsY;
  53437. this._heightQuads = new Array();
  53438. for (var row = 0; row < subdivisionsY; row++) {
  53439. for (var col = 0; col < subdivisionsX; col++) {
  53440. 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) };
  53441. this._heightQuads[row * subdivisionsX + col] = quad;
  53442. }
  53443. }
  53444. return this;
  53445. };
  53446. // Compute each quad element values and update the the heightMap array :
  53447. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53448. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53449. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53450. // Returns the GroundMesh.
  53451. GroundMesh.prototype._computeHeightQuads = function () {
  53452. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53453. if (!positions) {
  53454. return this;
  53455. }
  53456. var v1 = BABYLON.Tmp.Vector3[3];
  53457. var v2 = BABYLON.Tmp.Vector3[2];
  53458. var v3 = BABYLON.Tmp.Vector3[1];
  53459. var v4 = BABYLON.Tmp.Vector3[0];
  53460. var v1v2 = BABYLON.Tmp.Vector3[4];
  53461. var v1v3 = BABYLON.Tmp.Vector3[5];
  53462. var v1v4 = BABYLON.Tmp.Vector3[6];
  53463. var norm1 = BABYLON.Tmp.Vector3[7];
  53464. var norm2 = BABYLON.Tmp.Vector3[8];
  53465. var i = 0;
  53466. var j = 0;
  53467. var k = 0;
  53468. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53469. var h = 0;
  53470. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53471. var d2 = 0;
  53472. var subdivisionsX = this._subdivisionsX;
  53473. var subdivisionsY = this._subdivisionsY;
  53474. for (var row = 0; row < subdivisionsY; row++) {
  53475. for (var col = 0; col < subdivisionsX; col++) {
  53476. i = col * 3;
  53477. j = row * (subdivisionsX + 1) * 3;
  53478. k = (row + 1) * (subdivisionsX + 1) * 3;
  53479. v1.x = positions[j + i];
  53480. v1.y = positions[j + i + 1];
  53481. v1.z = positions[j + i + 2];
  53482. v2.x = positions[j + i + 3];
  53483. v2.y = positions[j + i + 4];
  53484. v2.z = positions[j + i + 5];
  53485. v3.x = positions[k + i];
  53486. v3.y = positions[k + i + 1];
  53487. v3.z = positions[k + i + 2];
  53488. v4.x = positions[k + i + 3];
  53489. v4.y = positions[k + i + 4];
  53490. v4.z = positions[k + i + 5];
  53491. // 2D slope V1V4
  53492. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53493. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53494. // facet equations :
  53495. // we compute each facet normal vector
  53496. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53497. // we compute the value d by applying the equation to v1 which belongs to the plane
  53498. // then we store the facet equation in a Vector4
  53499. v2.subtractToRef(v1, v1v2);
  53500. v3.subtractToRef(v1, v1v3);
  53501. v4.subtractToRef(v1, v1v4);
  53502. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53503. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53504. norm1.normalize();
  53505. norm2.normalize();
  53506. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53507. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53508. var quad = this._heightQuads[row * subdivisionsX + col];
  53509. quad.slope.copyFromFloats(cd, h);
  53510. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53511. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53512. }
  53513. }
  53514. return this;
  53515. };
  53516. GroundMesh.prototype.serialize = function (serializationObject) {
  53517. _super.prototype.serialize.call(this, serializationObject);
  53518. serializationObject.subdivisionsX = this._subdivisionsX;
  53519. serializationObject.subdivisionsY = this._subdivisionsY;
  53520. serializationObject.minX = this._minX;
  53521. serializationObject.maxX = this._maxX;
  53522. serializationObject.minZ = this._minZ;
  53523. serializationObject.maxZ = this._maxZ;
  53524. serializationObject.width = this._width;
  53525. serializationObject.height = this._height;
  53526. };
  53527. GroundMesh.Parse = function (parsedMesh, scene) {
  53528. var result = new GroundMesh(parsedMesh.name, scene);
  53529. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53530. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53531. result._minX = parsedMesh.minX;
  53532. result._maxX = parsedMesh.maxX;
  53533. result._minZ = parsedMesh.minZ;
  53534. result._maxZ = parsedMesh.maxZ;
  53535. result._width = parsedMesh.width;
  53536. result._height = parsedMesh.height;
  53537. return result;
  53538. };
  53539. return GroundMesh;
  53540. }(BABYLON.Mesh));
  53541. BABYLON.GroundMesh = GroundMesh;
  53542. })(BABYLON || (BABYLON = {}));
  53543. //# sourceMappingURL=babylon.groundMesh.js.map
  53544. var BABYLON;
  53545. (function (BABYLON) {
  53546. /**
  53547. * Creates an instance based on a source mesh.
  53548. */
  53549. var InstancedMesh = /** @class */ (function (_super) {
  53550. __extends(InstancedMesh, _super);
  53551. function InstancedMesh(name, source) {
  53552. var _this = _super.call(this, name, source.getScene()) || this;
  53553. source.instances.push(_this);
  53554. _this._sourceMesh = source;
  53555. _this.position.copyFrom(source.position);
  53556. _this.rotation.copyFrom(source.rotation);
  53557. _this.scaling.copyFrom(source.scaling);
  53558. if (source.rotationQuaternion) {
  53559. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53560. }
  53561. _this.infiniteDistance = source.infiniteDistance;
  53562. _this.setPivotMatrix(source.getPivotMatrix());
  53563. _this.refreshBoundingInfo();
  53564. _this._syncSubMeshes();
  53565. return _this;
  53566. }
  53567. /**
  53568. * Returns the string "InstancedMesh".
  53569. */
  53570. InstancedMesh.prototype.getClassName = function () {
  53571. return "InstancedMesh";
  53572. };
  53573. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53574. // Methods
  53575. get: function () {
  53576. return this._sourceMesh.receiveShadows;
  53577. },
  53578. enumerable: true,
  53579. configurable: true
  53580. });
  53581. Object.defineProperty(InstancedMesh.prototype, "material", {
  53582. get: function () {
  53583. return this._sourceMesh.material;
  53584. },
  53585. enumerable: true,
  53586. configurable: true
  53587. });
  53588. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  53589. get: function () {
  53590. return this._sourceMesh.visibility;
  53591. },
  53592. enumerable: true,
  53593. configurable: true
  53594. });
  53595. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  53596. get: function () {
  53597. return this._sourceMesh.skeleton;
  53598. },
  53599. enumerable: true,
  53600. configurable: true
  53601. });
  53602. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  53603. get: function () {
  53604. return this._sourceMesh.renderingGroupId;
  53605. },
  53606. enumerable: true,
  53607. configurable: true
  53608. });
  53609. /**
  53610. * Returns the total number of vertices (integer).
  53611. */
  53612. InstancedMesh.prototype.getTotalVertices = function () {
  53613. return this._sourceMesh.getTotalVertices();
  53614. };
  53615. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  53616. get: function () {
  53617. return this._sourceMesh;
  53618. },
  53619. enumerable: true,
  53620. configurable: true
  53621. });
  53622. /**
  53623. * Is this node ready to be used/rendered
  53624. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  53625. * @return {boolean} is it ready
  53626. */
  53627. InstancedMesh.prototype.isReady = function (completeCheck) {
  53628. if (completeCheck === void 0) { completeCheck = false; }
  53629. return this._sourceMesh.isReady(completeCheck, true);
  53630. };
  53631. /**
  53632. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  53633. */
  53634. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  53635. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  53636. };
  53637. /**
  53638. * Sets the vertex data of the mesh geometry for the requested `kind`.
  53639. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  53640. * The `data` are either a numeric array either a Float32Array.
  53641. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  53642. * 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).
  53643. * Note that a new underlying VertexBuffer object is created each call.
  53644. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  53645. *
  53646. * Possible `kind` values :
  53647. * - BABYLON.VertexBuffer.PositionKind
  53648. * - BABYLON.VertexBuffer.UVKind
  53649. * - BABYLON.VertexBuffer.UV2Kind
  53650. * - BABYLON.VertexBuffer.UV3Kind
  53651. * - BABYLON.VertexBuffer.UV4Kind
  53652. * - BABYLON.VertexBuffer.UV5Kind
  53653. * - BABYLON.VertexBuffer.UV6Kind
  53654. * - BABYLON.VertexBuffer.ColorKind
  53655. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53656. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53657. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53658. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53659. *
  53660. * Returns the Mesh.
  53661. */
  53662. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  53663. if (this.sourceMesh) {
  53664. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  53665. }
  53666. return this.sourceMesh;
  53667. };
  53668. /**
  53669. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  53670. * If the mesh has no geometry, it is simply returned as it is.
  53671. * The `data` are either a numeric array either a Float32Array.
  53672. * No new underlying VertexBuffer object is created.
  53673. * 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.
  53674. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  53675. *
  53676. * Possible `kind` values :
  53677. * - BABYLON.VertexBuffer.PositionKind
  53678. * - BABYLON.VertexBuffer.UVKind
  53679. * - BABYLON.VertexBuffer.UV2Kind
  53680. * - BABYLON.VertexBuffer.UV3Kind
  53681. * - BABYLON.VertexBuffer.UV4Kind
  53682. * - BABYLON.VertexBuffer.UV5Kind
  53683. * - BABYLON.VertexBuffer.UV6Kind
  53684. * - BABYLON.VertexBuffer.ColorKind
  53685. * - BABYLON.VertexBuffer.MatricesIndicesKind
  53686. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  53687. * - BABYLON.VertexBuffer.MatricesWeightsKind
  53688. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  53689. *
  53690. * Returns the Mesh.
  53691. */
  53692. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  53693. if (this.sourceMesh) {
  53694. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  53695. }
  53696. return this.sourceMesh;
  53697. };
  53698. /**
  53699. * Sets the mesh indices.
  53700. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  53701. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  53702. * This method creates a new index buffer each call.
  53703. * Returns the Mesh.
  53704. */
  53705. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  53706. if (totalVertices === void 0) { totalVertices = null; }
  53707. if (this.sourceMesh) {
  53708. this.sourceMesh.setIndices(indices, totalVertices);
  53709. }
  53710. return this.sourceMesh;
  53711. };
  53712. /**
  53713. * Boolean : True if the mesh owns the requested kind of data.
  53714. */
  53715. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  53716. return this._sourceMesh.isVerticesDataPresent(kind);
  53717. };
  53718. /**
  53719. * Returns an array of indices (IndicesArray).
  53720. */
  53721. InstancedMesh.prototype.getIndices = function () {
  53722. return this._sourceMesh.getIndices();
  53723. };
  53724. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  53725. get: function () {
  53726. return this._sourceMesh._positions;
  53727. },
  53728. enumerable: true,
  53729. configurable: true
  53730. });
  53731. /**
  53732. * Sets a new updated BoundingInfo to the mesh.
  53733. * Returns the mesh.
  53734. */
  53735. InstancedMesh.prototype.refreshBoundingInfo = function () {
  53736. var meshBB = this._sourceMesh.getBoundingInfo();
  53737. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  53738. this._updateBoundingInfo();
  53739. return this;
  53740. };
  53741. InstancedMesh.prototype._preActivate = function () {
  53742. if (this._currentLOD) {
  53743. this._currentLOD._preActivate();
  53744. }
  53745. return this;
  53746. };
  53747. InstancedMesh.prototype._activate = function (renderId) {
  53748. if (this._currentLOD) {
  53749. this._currentLOD._registerInstanceForRenderId(this, renderId);
  53750. }
  53751. return this;
  53752. };
  53753. /**
  53754. * Returns the current associated LOD AbstractMesh.
  53755. */
  53756. InstancedMesh.prototype.getLOD = function (camera) {
  53757. if (!camera) {
  53758. return this;
  53759. }
  53760. var boundingInfo = this.getBoundingInfo();
  53761. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  53762. if (this._currentLOD === this.sourceMesh) {
  53763. return this;
  53764. }
  53765. return this._currentLOD;
  53766. };
  53767. InstancedMesh.prototype._syncSubMeshes = function () {
  53768. this.releaseSubMeshes();
  53769. if (this._sourceMesh.subMeshes) {
  53770. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  53771. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  53772. }
  53773. }
  53774. return this;
  53775. };
  53776. InstancedMesh.prototype._generatePointsArray = function () {
  53777. return this._sourceMesh._generatePointsArray();
  53778. };
  53779. /**
  53780. * Creates a new InstancedMesh from the current mesh.
  53781. * - name (string) : the cloned mesh name
  53782. * - newParent (optional Node) : the optional Node to parent the clone to.
  53783. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  53784. *
  53785. * Returns the clone.
  53786. */
  53787. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53788. var result = this._sourceMesh.createInstance(name);
  53789. // Deep copy
  53790. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  53791. // Bounding info
  53792. this.refreshBoundingInfo();
  53793. // Parent
  53794. if (newParent) {
  53795. result.parent = newParent;
  53796. }
  53797. if (!doNotCloneChildren) {
  53798. // Children
  53799. for (var index = 0; index < this.getScene().meshes.length; index++) {
  53800. var mesh = this.getScene().meshes[index];
  53801. if (mesh.parent === this) {
  53802. mesh.clone(mesh.name, result);
  53803. }
  53804. }
  53805. }
  53806. result.computeWorldMatrix(true);
  53807. return result;
  53808. };
  53809. /**
  53810. * Disposes the InstancedMesh.
  53811. * Returns nothing.
  53812. */
  53813. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  53814. // Remove from mesh
  53815. var index = this._sourceMesh.instances.indexOf(this);
  53816. this._sourceMesh.instances.splice(index, 1);
  53817. _super.prototype.dispose.call(this, doNotRecurse);
  53818. };
  53819. return InstancedMesh;
  53820. }(BABYLON.AbstractMesh));
  53821. BABYLON.InstancedMesh = InstancedMesh;
  53822. })(BABYLON || (BABYLON = {}));
  53823. //# sourceMappingURL=babylon.instancedMesh.js.map
  53824. var BABYLON;
  53825. (function (BABYLON) {
  53826. var LinesMesh = /** @class */ (function (_super) {
  53827. __extends(LinesMesh, _super);
  53828. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  53829. if (scene === void 0) { scene = null; }
  53830. if (parent === void 0) { parent = null; }
  53831. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  53832. _this.useVertexColor = useVertexColor;
  53833. _this.useVertexAlpha = useVertexAlpha;
  53834. _this.color = new BABYLON.Color3(1, 1, 1);
  53835. _this.alpha = 1;
  53836. if (source) {
  53837. _this.color = source.color.clone();
  53838. _this.alpha = source.alpha;
  53839. _this.useVertexColor = source.useVertexColor;
  53840. _this.useVertexAlpha = source.useVertexAlpha;
  53841. }
  53842. _this._intersectionThreshold = 0.1;
  53843. var defines = [];
  53844. var options = {
  53845. attributes: [BABYLON.VertexBuffer.PositionKind],
  53846. uniforms: ["world", "viewProjection"],
  53847. needAlphaBlending: true,
  53848. defines: defines
  53849. };
  53850. if (useVertexAlpha === false) {
  53851. options.needAlphaBlending = false;
  53852. }
  53853. if (!useVertexColor) {
  53854. options.uniforms.push("color");
  53855. }
  53856. else {
  53857. options.defines.push("#define VERTEXCOLOR");
  53858. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  53859. }
  53860. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  53861. return _this;
  53862. }
  53863. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  53864. /**
  53865. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53866. * This margin is expressed in world space coordinates, so its value may vary.
  53867. * Default value is 0.1
  53868. * @returns the intersection Threshold value.
  53869. */
  53870. get: function () {
  53871. return this._intersectionThreshold;
  53872. },
  53873. /**
  53874. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  53875. * This margin is expressed in world space coordinates, so its value may vary.
  53876. * @param value the new threshold to apply
  53877. */
  53878. set: function (value) {
  53879. if (this._intersectionThreshold === value) {
  53880. return;
  53881. }
  53882. this._intersectionThreshold = value;
  53883. if (this.geometry) {
  53884. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  53885. }
  53886. },
  53887. enumerable: true,
  53888. configurable: true
  53889. });
  53890. /**
  53891. * Returns the string "LineMesh"
  53892. */
  53893. LinesMesh.prototype.getClassName = function () {
  53894. return "LinesMesh";
  53895. };
  53896. Object.defineProperty(LinesMesh.prototype, "material", {
  53897. get: function () {
  53898. return this._colorShader;
  53899. },
  53900. set: function (value) {
  53901. // Do nothing
  53902. },
  53903. enumerable: true,
  53904. configurable: true
  53905. });
  53906. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  53907. get: function () {
  53908. return false;
  53909. },
  53910. enumerable: true,
  53911. configurable: true
  53912. });
  53913. LinesMesh.prototype.createInstance = function (name) {
  53914. throw new Error("LinesMeshes do not support createInstance.");
  53915. };
  53916. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  53917. if (!this._geometry) {
  53918. return this;
  53919. }
  53920. // VBOs
  53921. this._geometry._bind(this._colorShader.getEffect());
  53922. // Color
  53923. if (!this.useVertexColor) {
  53924. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  53925. }
  53926. return this;
  53927. };
  53928. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  53929. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  53930. return this;
  53931. }
  53932. var engine = this.getScene().getEngine();
  53933. // Draw order
  53934. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  53935. return this;
  53936. };
  53937. LinesMesh.prototype.dispose = function (doNotRecurse) {
  53938. this._colorShader.dispose();
  53939. _super.prototype.dispose.call(this, doNotRecurse);
  53940. };
  53941. /**
  53942. * Returns a new LineMesh object cloned from the current one.
  53943. */
  53944. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  53945. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  53946. };
  53947. return LinesMesh;
  53948. }(BABYLON.Mesh));
  53949. BABYLON.LinesMesh = LinesMesh;
  53950. })(BABYLON || (BABYLON = {}));
  53951. //# sourceMappingURL=babylon.linesMesh.js.map
  53952. var BABYLON;
  53953. (function (BABYLON) {
  53954. var MeshBuilder = /** @class */ (function () {
  53955. function MeshBuilder() {
  53956. }
  53957. MeshBuilder.updateSideOrientation = function (orientation) {
  53958. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  53959. return BABYLON.Mesh.DOUBLESIDE;
  53960. }
  53961. if (orientation === undefined || orientation === null) {
  53962. return BABYLON.Mesh.FRONTSIDE;
  53963. }
  53964. return orientation;
  53965. };
  53966. /**
  53967. * Creates a box mesh.
  53968. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  53969. * The parameter `size` sets the size (float) of each box side (default 1).
  53970. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  53971. * 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).
  53972. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  53973. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53974. * 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).
  53975. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53976. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53977. */
  53978. MeshBuilder.CreateBox = function (name, options, scene) {
  53979. if (scene === void 0) { scene = null; }
  53980. var box = new BABYLON.Mesh(name, scene);
  53981. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  53982. box._originalBuilderSideOrientation = options.sideOrientation;
  53983. var vertexData = BABYLON.VertexData.CreateBox(options);
  53984. vertexData.applyToMesh(box, options.updatable);
  53985. return box;
  53986. };
  53987. /**
  53988. * Creates a sphere mesh.
  53989. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  53990. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  53991. * 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`).
  53992. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  53993. * 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
  53994. * 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).
  53995. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  53996. * 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).
  53997. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  53998. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  53999. */
  54000. MeshBuilder.CreateSphere = function (name, options, scene) {
  54001. var sphere = new BABYLON.Mesh(name, scene);
  54002. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54003. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54004. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54005. vertexData.applyToMesh(sphere, options.updatable);
  54006. return sphere;
  54007. };
  54008. /**
  54009. * Creates a plane polygonal mesh. By default, this is a disc.
  54010. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54011. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54012. * 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.
  54013. * 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
  54014. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54015. * 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).
  54016. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54017. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54018. */
  54019. MeshBuilder.CreateDisc = function (name, options, scene) {
  54020. if (scene === void 0) { scene = null; }
  54021. var disc = new BABYLON.Mesh(name, scene);
  54022. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54023. disc._originalBuilderSideOrientation = options.sideOrientation;
  54024. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54025. vertexData.applyToMesh(disc, options.updatable);
  54026. return disc;
  54027. };
  54028. /**
  54029. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54030. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54031. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54032. * 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`).
  54033. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54034. * 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.
  54035. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54036. * 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).
  54037. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54038. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54039. */
  54040. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54041. var sphere = new BABYLON.Mesh(name, scene);
  54042. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54043. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54044. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54045. vertexData.applyToMesh(sphere, options.updatable);
  54046. return sphere;
  54047. };
  54048. ;
  54049. /**
  54050. * Creates a ribbon mesh.
  54051. * 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.
  54052. *
  54053. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54054. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54055. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54056. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54057. * 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.
  54058. * 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.
  54059. * 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
  54060. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54061. * 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).
  54062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54063. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54064. * 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.
  54065. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54066. * 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
  54067. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54068. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54070. */
  54071. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54072. if (scene === void 0) { scene = null; }
  54073. var pathArray = options.pathArray;
  54074. var closeArray = options.closeArray;
  54075. var closePath = options.closePath;
  54076. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54077. var instance = options.instance;
  54078. var updatable = options.updatable;
  54079. if (instance) {
  54080. // positionFunction : ribbon case
  54081. // only pathArray and sideOrientation parameters are taken into account for positions update
  54082. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54083. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54084. var positionFunction = function (positions) {
  54085. var minlg = pathArray[0].length;
  54086. var i = 0;
  54087. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54088. for (var si = 1; si <= ns; si++) {
  54089. for (var p = 0; p < pathArray.length; p++) {
  54090. var path = pathArray[p];
  54091. var l = path.length;
  54092. minlg = (minlg < l) ? minlg : l;
  54093. var j = 0;
  54094. while (j < minlg) {
  54095. positions[i] = path[j].x;
  54096. positions[i + 1] = path[j].y;
  54097. positions[i + 2] = path[j].z;
  54098. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54099. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54100. }
  54101. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54102. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54103. }
  54104. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54105. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54106. }
  54107. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54108. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54109. }
  54110. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54111. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54112. }
  54113. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54114. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54115. }
  54116. j++;
  54117. i += 3;
  54118. }
  54119. if (instance._closePath) {
  54120. positions[i] = path[0].x;
  54121. positions[i + 1] = path[0].y;
  54122. positions[i + 2] = path[0].z;
  54123. i += 3;
  54124. }
  54125. }
  54126. }
  54127. };
  54128. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54129. positionFunction(positions);
  54130. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54131. instance._boundingInfo.update(instance._worldMatrix);
  54132. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54133. if (options.colors) {
  54134. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54135. for (var c = 0; c < options.colors.length; c++) {
  54136. colors[c * 4] = options.colors[c].r;
  54137. colors[c * 4 + 1] = options.colors[c].g;
  54138. colors[c * 4 + 2] = options.colors[c].b;
  54139. colors[c * 4 + 3] = options.colors[c].a;
  54140. }
  54141. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54142. }
  54143. if (options.uvs) {
  54144. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54145. for (var i = 0; i < options.uvs.length; i++) {
  54146. uvs[i * 2] = options.uvs[i].x;
  54147. uvs[i * 2 + 1] = options.uvs[i].y;
  54148. }
  54149. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54150. }
  54151. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54152. var indices = instance.getIndices();
  54153. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54154. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54155. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54156. if (instance._closePath) {
  54157. var indexFirst = 0;
  54158. var indexLast = 0;
  54159. for (var p = 0; p < pathArray.length; p++) {
  54160. indexFirst = instance._idx[p] * 3;
  54161. if (p + 1 < pathArray.length) {
  54162. indexLast = (instance._idx[p + 1] - 1) * 3;
  54163. }
  54164. else {
  54165. indexLast = normals.length - 3;
  54166. }
  54167. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54168. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54169. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54170. normals[indexLast] = normals[indexFirst];
  54171. normals[indexLast + 1] = normals[indexFirst + 1];
  54172. normals[indexLast + 2] = normals[indexFirst + 2];
  54173. }
  54174. }
  54175. if (!(instance.areNormalsFrozen)) {
  54176. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54177. }
  54178. }
  54179. return instance;
  54180. }
  54181. else {
  54182. var ribbon = new BABYLON.Mesh(name, scene);
  54183. ribbon._originalBuilderSideOrientation = sideOrientation;
  54184. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54185. if (closePath) {
  54186. ribbon._idx = vertexData._idx;
  54187. }
  54188. ribbon._closePath = closePath;
  54189. ribbon._closeArray = closeArray;
  54190. vertexData.applyToMesh(ribbon, updatable);
  54191. return ribbon;
  54192. }
  54193. };
  54194. /**
  54195. * Creates a cylinder or a cone mesh.
  54196. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54197. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54198. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54199. * 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.
  54200. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54201. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54202. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54203. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54204. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54205. * 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).
  54206. * 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
  54207. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54208. * 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
  54209. * 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.
  54210. * If `enclose` is false, a ring surface is one element.
  54211. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54212. * 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
  54213. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54214. * 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).
  54215. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54217. */
  54218. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54219. var cylinder = new BABYLON.Mesh(name, scene);
  54220. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54221. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54222. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54223. vertexData.applyToMesh(cylinder, options.updatable);
  54224. return cylinder;
  54225. };
  54226. /**
  54227. * Creates a torus mesh.
  54228. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54229. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54230. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54231. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54232. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54233. * 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).
  54234. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54235. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54236. */
  54237. MeshBuilder.CreateTorus = function (name, options, scene) {
  54238. var torus = new BABYLON.Mesh(name, scene);
  54239. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54240. torus._originalBuilderSideOrientation = options.sideOrientation;
  54241. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54242. vertexData.applyToMesh(torus, options.updatable);
  54243. return torus;
  54244. };
  54245. /**
  54246. * Creates a torus knot mesh.
  54247. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54248. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54249. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54250. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54251. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54252. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54253. * 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).
  54254. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54255. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54256. */
  54257. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54258. var torusKnot = new BABYLON.Mesh(name, scene);
  54259. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54260. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54261. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54262. vertexData.applyToMesh(torusKnot, options.updatable);
  54263. return torusKnot;
  54264. };
  54265. /**
  54266. * Creates a line system mesh.
  54267. * A line system is a pool of many lines gathered in a single mesh.
  54268. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54269. * 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.
  54270. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54271. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54272. * 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
  54273. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54274. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54275. * 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
  54276. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54278. */
  54279. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54280. var instance = options.instance;
  54281. var lines = options.lines;
  54282. var colors = options.colors;
  54283. if (instance) {
  54284. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54285. var vertexColor;
  54286. var lineColors;
  54287. if (colors) {
  54288. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54289. }
  54290. var i = 0;
  54291. var c = 0;
  54292. for (var l = 0; l < lines.length; l++) {
  54293. var points = lines[l];
  54294. for (var p = 0; p < points.length; p++) {
  54295. positions[i] = points[p].x;
  54296. positions[i + 1] = points[p].y;
  54297. positions[i + 2] = points[p].z;
  54298. if (colors && vertexColor) {
  54299. lineColors = colors[l];
  54300. vertexColor[c] = lineColors[p].r;
  54301. vertexColor[c + 1] = lineColors[p].g;
  54302. vertexColor[c + 2] = lineColors[p].b;
  54303. vertexColor[c + 3] = lineColors[p].a;
  54304. c += 4;
  54305. }
  54306. i += 3;
  54307. }
  54308. }
  54309. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54310. if (colors && vertexColor) {
  54311. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54312. }
  54313. return instance;
  54314. }
  54315. // line system creation
  54316. var useVertexColor = (colors) ? true : false;
  54317. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54318. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54319. vertexData.applyToMesh(lineSystem, options.updatable);
  54320. return lineSystem;
  54321. };
  54322. /**
  54323. * Creates a line mesh.
  54324. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54325. * 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.
  54326. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54327. * The parameter `points` is an array successive Vector3.
  54328. * 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
  54329. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54330. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54331. * When updating an instance, remember that only point positions can change, not the number of points.
  54332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54333. */
  54334. MeshBuilder.CreateLines = function (name, options, scene) {
  54335. if (scene === void 0) { scene = null; }
  54336. var colors = (options.colors) ? [options.colors] : null;
  54337. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54338. return lines;
  54339. };
  54340. /**
  54341. * Creates a dashed line mesh.
  54342. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54343. * 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.
  54344. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54345. * The parameter `points` is an array successive Vector3.
  54346. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54347. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54348. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54349. * 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
  54350. * When updating an instance, remember that only point positions can change, not the number of points.
  54351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54352. */
  54353. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54354. if (scene === void 0) { scene = null; }
  54355. var points = options.points;
  54356. var instance = options.instance;
  54357. var gapSize = options.gapSize || 1;
  54358. var dashSize = options.dashSize || 3;
  54359. if (instance) {
  54360. var positionFunction = function (positions) {
  54361. var curvect = BABYLON.Vector3.Zero();
  54362. var nbSeg = positions.length / 6;
  54363. var lg = 0;
  54364. var nb = 0;
  54365. var shft = 0;
  54366. var dashshft = 0;
  54367. var curshft = 0;
  54368. var p = 0;
  54369. var i = 0;
  54370. var j = 0;
  54371. for (i = 0; i < points.length - 1; i++) {
  54372. points[i + 1].subtractToRef(points[i], curvect);
  54373. lg += curvect.length();
  54374. }
  54375. shft = lg / nbSeg;
  54376. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54377. for (i = 0; i < points.length - 1; i++) {
  54378. points[i + 1].subtractToRef(points[i], curvect);
  54379. nb = Math.floor(curvect.length() / shft);
  54380. curvect.normalize();
  54381. j = 0;
  54382. while (j < nb && p < positions.length) {
  54383. curshft = shft * j;
  54384. positions[p] = points[i].x + curshft * curvect.x;
  54385. positions[p + 1] = points[i].y + curshft * curvect.y;
  54386. positions[p + 2] = points[i].z + curshft * curvect.z;
  54387. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54388. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54389. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54390. p += 6;
  54391. j++;
  54392. }
  54393. }
  54394. while (p < positions.length) {
  54395. positions[p] = points[i].x;
  54396. positions[p + 1] = points[i].y;
  54397. positions[p + 2] = points[i].z;
  54398. p += 3;
  54399. }
  54400. };
  54401. instance.updateMeshPositions(positionFunction, false);
  54402. return instance;
  54403. }
  54404. // dashed lines creation
  54405. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54406. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54407. vertexData.applyToMesh(dashedLines, options.updatable);
  54408. dashedLines.dashSize = dashSize;
  54409. dashedLines.gapSize = gapSize;
  54410. return dashedLines;
  54411. };
  54412. /**
  54413. * Creates an extruded shape mesh.
  54414. * 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.
  54415. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54416. *
  54417. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54418. * 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
  54419. * extruded along the Z axis.
  54420. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54421. * 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.
  54422. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54423. * 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
  54424. * 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
  54425. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54426. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54427. * 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).
  54428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54429. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54430. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54431. */
  54432. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54433. if (scene === void 0) { scene = null; }
  54434. var path = options.path;
  54435. var shape = options.shape;
  54436. var scale = options.scale || 1;
  54437. var rotation = options.rotation || 0;
  54438. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54439. var updatable = options.updatable;
  54440. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54441. var instance = options.instance || null;
  54442. var invertUV = options.invertUV || false;
  54443. 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);
  54444. };
  54445. /**
  54446. * Creates an custom extruded shape mesh.
  54447. * 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.
  54448. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54449. *
  54450. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54451. * 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
  54452. * extruded along the Z axis.
  54453. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54454. * 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
  54455. * and the distance of this point from the begining of the path :
  54456. * ```javascript
  54457. * var rotationFunction = function(i, distance) {
  54458. * // do things
  54459. * return rotationValue; }
  54460. * ```
  54461. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54462. * 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
  54463. * and the distance of this point from the begining of the path :
  54464. * ```javascript
  54465. * var scaleFunction = function(i, distance) {
  54466. * // do things
  54467. * return scaleValue;}
  54468. * ```
  54469. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54470. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54471. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54472. * 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
  54473. * 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
  54474. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54475. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54476. * 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).
  54477. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54478. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54479. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54480. */
  54481. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54482. var path = options.path;
  54483. var shape = options.shape;
  54484. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54485. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54486. var ribbonCloseArray = options.ribbonCloseArray || false;
  54487. var ribbonClosePath = options.ribbonClosePath || false;
  54488. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54489. var updatable = options.updatable;
  54490. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54491. var instance = options.instance;
  54492. var invertUV = options.invertUV || false;
  54493. 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);
  54494. };
  54495. /**
  54496. * Creates lathe mesh.
  54497. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54498. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54499. *
  54500. * 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
  54501. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54502. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54503. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54504. * 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.
  54505. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54506. * 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
  54507. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54508. * 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).
  54509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54510. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54511. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54512. */
  54513. MeshBuilder.CreateLathe = function (name, options, scene) {
  54514. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54515. var closed = (options.closed === undefined) ? true : options.closed;
  54516. var shape = options.shape;
  54517. var radius = options.radius || 1;
  54518. var tessellation = options.tessellation || 64;
  54519. var updatable = options.updatable;
  54520. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54521. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54522. var pi2 = Math.PI * 2;
  54523. var paths = new Array();
  54524. var invertUV = options.invertUV || false;
  54525. var i = 0;
  54526. var p = 0;
  54527. var step = pi2 / tessellation * arc;
  54528. var rotated;
  54529. var path = new Array();
  54530. ;
  54531. for (i = 0; i <= tessellation; i++) {
  54532. var path = [];
  54533. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54534. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54535. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54536. }
  54537. for (p = 0; p < shape.length; p++) {
  54538. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54539. path.push(rotated);
  54540. }
  54541. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54542. 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));
  54543. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54544. }
  54545. paths.push(path);
  54546. }
  54547. // lathe ribbon
  54548. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54549. return lathe;
  54550. };
  54551. /**
  54552. * Creates a plane mesh.
  54553. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54554. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54555. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54556. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54557. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54558. * 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).
  54559. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54560. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54561. */
  54562. MeshBuilder.CreatePlane = function (name, options, scene) {
  54563. var plane = new BABYLON.Mesh(name, scene);
  54564. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54565. plane._originalBuilderSideOrientation = options.sideOrientation;
  54566. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54567. vertexData.applyToMesh(plane, options.updatable);
  54568. if (options.sourcePlane) {
  54569. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54570. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54571. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54572. plane.rotate(vectorProduct, product);
  54573. }
  54574. return plane;
  54575. };
  54576. /**
  54577. * Creates a ground mesh.
  54578. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54579. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  54580. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  54581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54582. */
  54583. MeshBuilder.CreateGround = function (name, options, scene) {
  54584. var ground = new BABYLON.GroundMesh(name, scene);
  54585. ground._setReady(false);
  54586. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  54587. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  54588. ground._width = options.width || 1;
  54589. ground._height = options.height || 1;
  54590. ground._maxX = ground._width / 2;
  54591. ground._maxZ = ground._height / 2;
  54592. ground._minX = -ground._maxX;
  54593. ground._minZ = -ground._maxZ;
  54594. var vertexData = BABYLON.VertexData.CreateGround(options);
  54595. vertexData.applyToMesh(ground, options.updatable);
  54596. ground._setReady(true);
  54597. return ground;
  54598. };
  54599. /**
  54600. * Creates a tiled ground mesh.
  54601. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  54602. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  54603. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  54604. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  54605. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  54606. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  54607. * numbers of subdivisions on the ground width and height of each tile.
  54608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54609. */
  54610. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  54611. var tiledGround = new BABYLON.Mesh(name, scene);
  54612. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  54613. vertexData.applyToMesh(tiledGround, options.updatable);
  54614. return tiledGround;
  54615. };
  54616. /**
  54617. * Creates a ground mesh from a height map.
  54618. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  54619. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  54620. * The parameter `url` sets the URL of the height map image resource.
  54621. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  54622. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  54623. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  54624. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  54625. * 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.
  54626. * 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).
  54627. * This function is passed the newly built mesh :
  54628. * ```javascript
  54629. * function(mesh) { // do things
  54630. * return; }
  54631. * ```
  54632. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54633. */
  54634. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  54635. var width = options.width || 10.0;
  54636. var height = options.height || 10.0;
  54637. var subdivisions = options.subdivisions || 1 | 0;
  54638. var minHeight = options.minHeight || 0.0;
  54639. var maxHeight = options.maxHeight || 1.0;
  54640. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  54641. var updatable = options.updatable;
  54642. var onReady = options.onReady;
  54643. var ground = new BABYLON.GroundMesh(name, scene);
  54644. ground._subdivisionsX = subdivisions;
  54645. ground._subdivisionsY = subdivisions;
  54646. ground._width = width;
  54647. ground._height = height;
  54648. ground._maxX = ground._width / 2.0;
  54649. ground._maxZ = ground._height / 2.0;
  54650. ground._minX = -ground._maxX;
  54651. ground._minZ = -ground._maxZ;
  54652. ground._setReady(false);
  54653. var onload = function (img) {
  54654. // Getting height map data
  54655. var canvas = document.createElement("canvas");
  54656. var context = canvas.getContext("2d");
  54657. if (!context) {
  54658. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  54659. }
  54660. if (scene.isDisposed) {
  54661. return;
  54662. }
  54663. var bufferWidth = img.width;
  54664. var bufferHeight = img.height;
  54665. canvas.width = bufferWidth;
  54666. canvas.height = bufferHeight;
  54667. context.drawImage(img, 0, 0);
  54668. // Create VertexData from map data
  54669. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  54670. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  54671. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  54672. width: width, height: height,
  54673. subdivisions: subdivisions,
  54674. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  54675. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  54676. });
  54677. vertexData.applyToMesh(ground, updatable);
  54678. ground._setReady(true);
  54679. //execute ready callback, if set
  54680. if (onReady) {
  54681. onReady(ground);
  54682. }
  54683. };
  54684. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  54685. return ground;
  54686. };
  54687. /**
  54688. * Creates a polygon mesh.
  54689. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  54690. * 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.
  54691. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54692. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54693. * 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).
  54694. * Remember you can only change the shape positions, not their number when updating a polygon.
  54695. */
  54696. MeshBuilder.CreatePolygon = function (name, options, scene) {
  54697. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54698. var shape = options.shape;
  54699. var holes = options.holes || [];
  54700. var depth = options.depth || 0;
  54701. var contours = [];
  54702. var hole = [];
  54703. for (var i = 0; i < shape.length; i++) {
  54704. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  54705. }
  54706. var epsilon = 0.00000001;
  54707. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  54708. contours.pop();
  54709. }
  54710. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  54711. for (var hNb = 0; hNb < holes.length; hNb++) {
  54712. hole = [];
  54713. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  54714. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  54715. }
  54716. polygonTriangulation.addHole(hole);
  54717. }
  54718. var polygon = polygonTriangulation.build(options.updatable, depth);
  54719. polygon._originalBuilderSideOrientation = options.sideOrientation;
  54720. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  54721. vertexData.applyToMesh(polygon, options.updatable);
  54722. return polygon;
  54723. };
  54724. ;
  54725. /**
  54726. * Creates an extruded polygon mesh, with depth in the Y direction.
  54727. * 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).
  54728. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54729. */
  54730. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  54731. return MeshBuilder.CreatePolygon(name, options, scene);
  54732. };
  54733. ;
  54734. /**
  54735. * Creates a tube mesh.
  54736. * 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.
  54737. *
  54738. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  54739. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  54740. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  54741. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  54742. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  54743. * 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.
  54744. * It must return a radius value (positive float) :
  54745. * ```javascript
  54746. * var radiusFunction = function(i, distance) {
  54747. * // do things
  54748. * return radius; }
  54749. * ```
  54750. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  54751. * 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
  54752. * 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
  54753. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54754. * 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).
  54755. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54756. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54757. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54758. */
  54759. MeshBuilder.CreateTube = function (name, options, scene) {
  54760. var path = options.path;
  54761. var instance = options.instance;
  54762. var radius = 1.0;
  54763. if (instance) {
  54764. radius = instance.radius;
  54765. }
  54766. if (options.radius !== undefined) {
  54767. radius = options.radius;
  54768. }
  54769. ;
  54770. var tessellation = options.tessellation || 64 | 0;
  54771. var radiusFunction = options.radiusFunction || null;
  54772. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54773. var invertUV = options.invertUV || false;
  54774. var updatable = options.updatable;
  54775. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54776. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  54777. // tube geometry
  54778. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  54779. var tangents = path3D.getTangents();
  54780. var normals = path3D.getNormals();
  54781. var distances = path3D.getDistances();
  54782. var pi2 = Math.PI * 2;
  54783. var step = pi2 / tessellation * arc;
  54784. var returnRadius = function () { return radius; };
  54785. var radiusFunctionFinal = radiusFunction || returnRadius;
  54786. var circlePath;
  54787. var rad;
  54788. var normal;
  54789. var rotated;
  54790. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  54791. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  54792. for (var i = 0; i < path.length; i++) {
  54793. rad = radiusFunctionFinal(i, distances[i]); // current radius
  54794. circlePath = Array(); // current circle array
  54795. normal = normals[i]; // current normal
  54796. for (var t = 0; t < tessellation; t++) {
  54797. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  54798. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  54799. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  54800. rotated.scaleInPlace(rad).addInPlace(path[i]);
  54801. circlePath[t] = rotated;
  54802. }
  54803. circlePaths[index] = circlePath;
  54804. index++;
  54805. }
  54806. // cap
  54807. var capPath = function (nbPoints, pathIndex) {
  54808. var pointCap = Array();
  54809. for (var i = 0; i < nbPoints; i++) {
  54810. pointCap.push(path[pathIndex]);
  54811. }
  54812. return pointCap;
  54813. };
  54814. switch (cap) {
  54815. case BABYLON.Mesh.NO_CAP:
  54816. break;
  54817. case BABYLON.Mesh.CAP_START:
  54818. circlePaths[0] = capPath(tessellation, 0);
  54819. circlePaths[1] = circlePaths[2].slice(0);
  54820. break;
  54821. case BABYLON.Mesh.CAP_END:
  54822. circlePaths[index] = circlePaths[index - 1].slice(0);
  54823. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54824. break;
  54825. case BABYLON.Mesh.CAP_ALL:
  54826. circlePaths[0] = capPath(tessellation, 0);
  54827. circlePaths[1] = circlePaths[2].slice(0);
  54828. circlePaths[index] = circlePaths[index - 1].slice(0);
  54829. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  54830. break;
  54831. default:
  54832. break;
  54833. }
  54834. return circlePaths;
  54835. };
  54836. var path3D;
  54837. var pathArray;
  54838. if (instance) {
  54839. var arc = options.arc || instance.arc;
  54840. path3D = (instance.path3D).update(path);
  54841. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  54842. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  54843. instance.path3D = path3D;
  54844. instance.pathArray = pathArray;
  54845. instance.arc = arc;
  54846. instance.radius = radius;
  54847. return instance;
  54848. }
  54849. // tube creation
  54850. path3D = new BABYLON.Path3D(path);
  54851. var newPathArray = new Array();
  54852. cap = (cap < 0 || cap > 3) ? 0 : cap;
  54853. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  54854. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54855. tube.pathArray = pathArray;
  54856. tube.path3D = path3D;
  54857. tube.tessellation = tessellation;
  54858. tube.cap = cap;
  54859. tube.arc = options.arc;
  54860. tube.radius = radius;
  54861. return tube;
  54862. };
  54863. /**
  54864. * Creates a polyhedron mesh.
  54865. *
  54866. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  54867. * 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
  54868. * to choose the wanted type.
  54869. * The parameter `size` (positive float, default 1) sets the polygon size.
  54870. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  54871. * 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`.
  54872. * 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
  54873. * 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)`).
  54874. * 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
  54875. * 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.
  54876. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54877. * 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).
  54878. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54879. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54880. */
  54881. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  54882. var polyhedron = new BABYLON.Mesh(name, scene);
  54883. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54884. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  54885. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  54886. vertexData.applyToMesh(polyhedron, options.updatable);
  54887. return polyhedron;
  54888. };
  54889. /**
  54890. * Creates a decal mesh.
  54891. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  54892. * 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.
  54893. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  54894. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  54895. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  54896. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  54897. */
  54898. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  54899. var indices = sourceMesh.getIndices();
  54900. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54901. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54902. var position = options.position || BABYLON.Vector3.Zero();
  54903. var normal = options.normal || BABYLON.Vector3.Up();
  54904. var size = options.size || BABYLON.Vector3.One();
  54905. var angle = options.angle || 0;
  54906. // Getting correct rotation
  54907. if (!normal) {
  54908. var target = new BABYLON.Vector3(0, 0, 1);
  54909. var camera = sourceMesh.getScene().activeCamera;
  54910. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  54911. normal = camera.globalPosition.subtract(cameraWorldTarget);
  54912. }
  54913. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  54914. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  54915. var pitch = Math.atan2(normal.y, len);
  54916. // Matrix
  54917. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  54918. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  54919. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  54920. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  54921. var vertexData = new BABYLON.VertexData();
  54922. vertexData.indices = [];
  54923. vertexData.positions = [];
  54924. vertexData.normals = [];
  54925. vertexData.uvs = [];
  54926. var currentVertexDataIndex = 0;
  54927. var extractDecalVector3 = function (indexId) {
  54928. var result = new BABYLON.PositionNormalVertex();
  54929. if (!indices || !positions || !normals) {
  54930. return result;
  54931. }
  54932. var vertexId = indices[indexId];
  54933. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  54934. // Send vector to decal local world
  54935. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  54936. // Get normal
  54937. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  54938. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  54939. return result;
  54940. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  54941. var clip = function (vertices, axis) {
  54942. if (vertices.length === 0) {
  54943. return vertices;
  54944. }
  54945. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  54946. var clipVertices = function (v0, v1) {
  54947. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  54948. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  54949. };
  54950. var result = new Array();
  54951. for (var index = 0; index < vertices.length; index += 3) {
  54952. var v1Out;
  54953. var v2Out;
  54954. var v3Out;
  54955. var total = 0;
  54956. var nV1 = null;
  54957. var nV2 = null;
  54958. var nV3 = null;
  54959. var nV4 = null;
  54960. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  54961. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  54962. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  54963. v1Out = d1 > 0;
  54964. v2Out = d2 > 0;
  54965. v3Out = d3 > 0;
  54966. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  54967. switch (total) {
  54968. case 0:
  54969. result.push(vertices[index]);
  54970. result.push(vertices[index + 1]);
  54971. result.push(vertices[index + 2]);
  54972. break;
  54973. case 1:
  54974. if (v1Out) {
  54975. nV1 = vertices[index + 1];
  54976. nV2 = vertices[index + 2];
  54977. nV3 = clipVertices(vertices[index], nV1);
  54978. nV4 = clipVertices(vertices[index], nV2);
  54979. }
  54980. if (v2Out) {
  54981. nV1 = vertices[index];
  54982. nV2 = vertices[index + 2];
  54983. nV3 = clipVertices(vertices[index + 1], nV1);
  54984. nV4 = clipVertices(vertices[index + 1], nV2);
  54985. result.push(nV3);
  54986. result.push(nV2.clone());
  54987. result.push(nV1.clone());
  54988. result.push(nV2.clone());
  54989. result.push(nV3.clone());
  54990. result.push(nV4);
  54991. break;
  54992. }
  54993. if (v3Out) {
  54994. nV1 = vertices[index];
  54995. nV2 = vertices[index + 1];
  54996. nV3 = clipVertices(vertices[index + 2], nV1);
  54997. nV4 = clipVertices(vertices[index + 2], nV2);
  54998. }
  54999. if (nV1 && nV2 && nV3 && nV4) {
  55000. result.push(nV1.clone());
  55001. result.push(nV2.clone());
  55002. result.push(nV3);
  55003. result.push(nV4);
  55004. result.push(nV3.clone());
  55005. result.push(nV2.clone());
  55006. }
  55007. break;
  55008. case 2:
  55009. if (!v1Out) {
  55010. nV1 = vertices[index].clone();
  55011. nV2 = clipVertices(nV1, vertices[index + 1]);
  55012. nV3 = clipVertices(nV1, vertices[index + 2]);
  55013. result.push(nV1);
  55014. result.push(nV2);
  55015. result.push(nV3);
  55016. }
  55017. if (!v2Out) {
  55018. nV1 = vertices[index + 1].clone();
  55019. nV2 = clipVertices(nV1, vertices[index + 2]);
  55020. nV3 = clipVertices(nV1, vertices[index]);
  55021. result.push(nV1);
  55022. result.push(nV2);
  55023. result.push(nV3);
  55024. }
  55025. if (!v3Out) {
  55026. nV1 = vertices[index + 2].clone();
  55027. nV2 = clipVertices(nV1, vertices[index]);
  55028. nV3 = clipVertices(nV1, vertices[index + 1]);
  55029. result.push(nV1);
  55030. result.push(nV2);
  55031. result.push(nV3);
  55032. }
  55033. break;
  55034. case 3:
  55035. break;
  55036. }
  55037. }
  55038. return result;
  55039. };
  55040. for (var index = 0; index < indices.length; index += 3) {
  55041. var faceVertices = new Array();
  55042. faceVertices.push(extractDecalVector3(index));
  55043. faceVertices.push(extractDecalVector3(index + 1));
  55044. faceVertices.push(extractDecalVector3(index + 2));
  55045. // Clip
  55046. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55047. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55048. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55049. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55050. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55051. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55052. if (faceVertices.length === 0) {
  55053. continue;
  55054. }
  55055. // Add UVs and get back to world
  55056. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55057. var vertex = faceVertices[vIndex];
  55058. //TODO check for Int32Array | Uint32Array | Uint16Array
  55059. vertexData.indices.push(currentVertexDataIndex);
  55060. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55061. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55062. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55063. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55064. currentVertexDataIndex++;
  55065. }
  55066. }
  55067. // Return mesh
  55068. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55069. vertexData.applyToMesh(decal);
  55070. decal.position = position.clone();
  55071. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55072. return decal;
  55073. };
  55074. // Privates
  55075. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55076. // extrusion geometry
  55077. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55078. var tangents = path3D.getTangents();
  55079. var normals = path3D.getNormals();
  55080. var binormals = path3D.getBinormals();
  55081. var distances = path3D.getDistances();
  55082. var angle = 0;
  55083. var returnScale = function () { return scale !== null ? scale : 1; };
  55084. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55085. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55086. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55087. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55088. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55089. for (var i = 0; i < curve.length; i++) {
  55090. var shapePath = new Array();
  55091. var angleStep = rotate(i, distances[i]);
  55092. var scaleRatio = scl(i, distances[i]);
  55093. for (var p = 0; p < shape.length; p++) {
  55094. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55095. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55096. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55097. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55098. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55099. shapePath[p] = rotated;
  55100. }
  55101. shapePaths[index] = shapePath;
  55102. angle += angleStep;
  55103. index++;
  55104. }
  55105. // cap
  55106. var capPath = function (shapePath) {
  55107. var pointCap = Array();
  55108. var barycenter = BABYLON.Vector3.Zero();
  55109. var i;
  55110. for (i = 0; i < shapePath.length; i++) {
  55111. barycenter.addInPlace(shapePath[i]);
  55112. }
  55113. barycenter.scaleInPlace(1.0 / shapePath.length);
  55114. for (i = 0; i < shapePath.length; i++) {
  55115. pointCap.push(barycenter);
  55116. }
  55117. return pointCap;
  55118. };
  55119. switch (cap) {
  55120. case BABYLON.Mesh.NO_CAP:
  55121. break;
  55122. case BABYLON.Mesh.CAP_START:
  55123. shapePaths[0] = capPath(shapePaths[2]);
  55124. shapePaths[1] = shapePaths[2];
  55125. break;
  55126. case BABYLON.Mesh.CAP_END:
  55127. shapePaths[index] = shapePaths[index - 1];
  55128. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55129. break;
  55130. case BABYLON.Mesh.CAP_ALL:
  55131. shapePaths[0] = capPath(shapePaths[2]);
  55132. shapePaths[1] = shapePaths[2];
  55133. shapePaths[index] = shapePaths[index - 1];
  55134. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55135. break;
  55136. default:
  55137. break;
  55138. }
  55139. return shapePaths;
  55140. };
  55141. var path3D;
  55142. var pathArray;
  55143. if (instance) {
  55144. path3D = (instance.path3D).update(curve);
  55145. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55146. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55147. return instance;
  55148. }
  55149. // extruded shape creation
  55150. path3D = new BABYLON.Path3D(curve);
  55151. var newShapePaths = new Array();
  55152. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55153. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55154. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55155. extrudedGeneric.pathArray = pathArray;
  55156. extrudedGeneric.path3D = path3D;
  55157. extrudedGeneric.cap = cap;
  55158. return extrudedGeneric;
  55159. };
  55160. return MeshBuilder;
  55161. }());
  55162. BABYLON.MeshBuilder = MeshBuilder;
  55163. })(BABYLON || (BABYLON = {}));
  55164. //# sourceMappingURL=babylon.meshBuilder.js.map
  55165. var BABYLON;
  55166. (function (BABYLON) {
  55167. var AudioEngine = /** @class */ (function () {
  55168. function AudioEngine() {
  55169. this._audioContext = null;
  55170. this._audioContextInitialized = false;
  55171. this.canUseWebAudio = false;
  55172. this.WarnedWebAudioUnsupported = false;
  55173. this.unlocked = false;
  55174. this.isMP3supported = false;
  55175. this.isOGGsupported = false;
  55176. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55177. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55178. this.canUseWebAudio = true;
  55179. }
  55180. var audioElem = document.createElement('audio');
  55181. try {
  55182. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55183. this.isMP3supported = true;
  55184. }
  55185. }
  55186. catch (e) {
  55187. // protect error during capability check.
  55188. }
  55189. try {
  55190. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55191. this.isOGGsupported = true;
  55192. }
  55193. }
  55194. catch (e) {
  55195. // protect error during capability check.
  55196. }
  55197. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55198. this._unlockiOSaudio();
  55199. }
  55200. else {
  55201. this.unlocked = true;
  55202. }
  55203. }
  55204. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55205. get: function () {
  55206. if (!this._audioContextInitialized) {
  55207. this._initializeAudioContext();
  55208. }
  55209. return this._audioContext;
  55210. },
  55211. enumerable: true,
  55212. configurable: true
  55213. });
  55214. AudioEngine.prototype._unlockiOSaudio = function () {
  55215. var _this = this;
  55216. var unlockaudio = function () {
  55217. if (!_this.audioContext) {
  55218. return;
  55219. }
  55220. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55221. var source = _this.audioContext.createBufferSource();
  55222. source.buffer = buffer;
  55223. source.connect(_this.audioContext.destination);
  55224. source.start(0);
  55225. setTimeout(function () {
  55226. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55227. _this.unlocked = true;
  55228. window.removeEventListener('touchend', unlockaudio, false);
  55229. if (_this.onAudioUnlocked) {
  55230. _this.onAudioUnlocked();
  55231. }
  55232. }
  55233. }, 0);
  55234. };
  55235. window.addEventListener('touchend', unlockaudio, false);
  55236. };
  55237. AudioEngine.prototype._initializeAudioContext = function () {
  55238. try {
  55239. if (this.canUseWebAudio) {
  55240. this._audioContext = new AudioContext();
  55241. // create a global volume gain node
  55242. this.masterGain = this._audioContext.createGain();
  55243. this.masterGain.gain.value = 1;
  55244. this.masterGain.connect(this._audioContext.destination);
  55245. this._audioContextInitialized = true;
  55246. }
  55247. }
  55248. catch (e) {
  55249. this.canUseWebAudio = false;
  55250. BABYLON.Tools.Error("Web Audio: " + e.message);
  55251. }
  55252. };
  55253. AudioEngine.prototype.dispose = function () {
  55254. if (this.canUseWebAudio && this._audioContextInitialized) {
  55255. if (this._connectedAnalyser && this._audioContext) {
  55256. this._connectedAnalyser.stopDebugCanvas();
  55257. this._connectedAnalyser.dispose();
  55258. this.masterGain.disconnect();
  55259. this.masterGain.connect(this._audioContext.destination);
  55260. this._connectedAnalyser = null;
  55261. }
  55262. this.masterGain.gain.value = 1;
  55263. }
  55264. this.WarnedWebAudioUnsupported = false;
  55265. };
  55266. AudioEngine.prototype.getGlobalVolume = function () {
  55267. if (this.canUseWebAudio && this._audioContextInitialized) {
  55268. return this.masterGain.gain.value;
  55269. }
  55270. else {
  55271. return -1;
  55272. }
  55273. };
  55274. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55275. if (this.canUseWebAudio && this._audioContextInitialized) {
  55276. this.masterGain.gain.value = newVolume;
  55277. }
  55278. };
  55279. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55280. if (this._connectedAnalyser) {
  55281. this._connectedAnalyser.stopDebugCanvas();
  55282. }
  55283. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55284. this._connectedAnalyser = analyser;
  55285. this.masterGain.disconnect();
  55286. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  55287. }
  55288. };
  55289. return AudioEngine;
  55290. }());
  55291. BABYLON.AudioEngine = AudioEngine;
  55292. })(BABYLON || (BABYLON = {}));
  55293. //# sourceMappingURL=babylon.audioEngine.js.map
  55294. var BABYLON;
  55295. (function (BABYLON) {
  55296. var Sound = /** @class */ (function () {
  55297. /**
  55298. * Create a sound and attach it to a scene
  55299. * @param name Name of your sound
  55300. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  55301. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  55302. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  55303. */
  55304. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  55305. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55306. var _this = this;
  55307. this.autoplay = false;
  55308. this.loop = false;
  55309. this.useCustomAttenuation = false;
  55310. this.spatialSound = false;
  55311. this.refDistance = 1;
  55312. this.rolloffFactor = 1;
  55313. this.maxDistance = 100;
  55314. this.distanceModel = "linear";
  55315. this._panningModel = "equalpower";
  55316. this._playbackRate = 1;
  55317. this._streaming = false;
  55318. this._startTime = 0;
  55319. this._startOffset = 0;
  55320. this._position = BABYLON.Vector3.Zero();
  55321. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55322. this._volume = 1;
  55323. this._isReadyToPlay = false;
  55324. this.isPlaying = false;
  55325. this.isPaused = false;
  55326. this._isDirectional = false;
  55327. // Used if you'd like to create a directional sound.
  55328. // If not set, the sound will be omnidirectional
  55329. this._coneInnerAngle = 360;
  55330. this._coneOuterAngle = 360;
  55331. this._coneOuterGain = 0;
  55332. this._isOutputConnected = false;
  55333. this._urlType = "Unknown";
  55334. this.name = name;
  55335. this._scene = scene;
  55336. this._readyToPlayCallback = readyToPlayCallback;
  55337. // Default custom attenuation function is a linear attenuation
  55338. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55339. if (currentDistance < maxDistance) {
  55340. return currentVolume * (1 - currentDistance / maxDistance);
  55341. }
  55342. else {
  55343. return 0;
  55344. }
  55345. };
  55346. if (options) {
  55347. this.autoplay = options.autoplay || false;
  55348. this.loop = options.loop || false;
  55349. // if volume === 0, we need another way to check this option
  55350. if (options.volume !== undefined) {
  55351. this._volume = options.volume;
  55352. }
  55353. this.spatialSound = options.spatialSound || false;
  55354. this.maxDistance = options.maxDistance || 100;
  55355. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55356. this.rolloffFactor = options.rolloffFactor || 1;
  55357. this.refDistance = options.refDistance || 1;
  55358. this.distanceModel = options.distanceModel || "linear";
  55359. this._playbackRate = options.playbackRate || 1;
  55360. this._streaming = options.streaming || false;
  55361. }
  55362. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55363. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55364. this._soundGain.gain.value = this._volume;
  55365. this._inputAudioNode = this._soundGain;
  55366. this._ouputAudioNode = this._soundGain;
  55367. if (this.spatialSound) {
  55368. this._createSpatialParameters();
  55369. }
  55370. this._scene.mainSoundTrack.AddSound(this);
  55371. var validParameter = true;
  55372. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55373. if (urlOrArrayBuffer) {
  55374. if (typeof (urlOrArrayBuffer) === "string")
  55375. this._urlType = "String";
  55376. if (Array.isArray(urlOrArrayBuffer))
  55377. this._urlType = "Array";
  55378. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55379. this._urlType = "ArrayBuffer";
  55380. var urls = [];
  55381. var codecSupportedFound = false;
  55382. switch (this._urlType) {
  55383. case "ArrayBuffer":
  55384. if (urlOrArrayBuffer.byteLength > 0) {
  55385. codecSupportedFound = true;
  55386. this._soundLoaded(urlOrArrayBuffer);
  55387. }
  55388. break;
  55389. case "String":
  55390. urls.push(urlOrArrayBuffer);
  55391. case "Array":
  55392. if (urls.length === 0)
  55393. urls = urlOrArrayBuffer;
  55394. // If we found a supported format, we load it immediately and stop the loop
  55395. for (var i = 0; i < urls.length; i++) {
  55396. var url = urls[i];
  55397. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55398. codecSupportedFound = true;
  55399. }
  55400. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55401. codecSupportedFound = true;
  55402. }
  55403. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55404. codecSupportedFound = true;
  55405. }
  55406. if (url.indexOf("blob:") !== -1) {
  55407. codecSupportedFound = true;
  55408. }
  55409. if (codecSupportedFound) {
  55410. // Loading sound using XHR2
  55411. if (!this._streaming) {
  55412. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55413. }
  55414. else {
  55415. this._htmlAudioElement = new Audio(url);
  55416. this._htmlAudioElement.controls = false;
  55417. this._htmlAudioElement.loop = this.loop;
  55418. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55419. this._htmlAudioElement.preload = "auto";
  55420. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55421. _this._isReadyToPlay = true;
  55422. if (_this.autoplay) {
  55423. _this.play();
  55424. }
  55425. if (_this._readyToPlayCallback) {
  55426. _this._readyToPlayCallback();
  55427. }
  55428. });
  55429. document.body.appendChild(this._htmlAudioElement);
  55430. }
  55431. break;
  55432. }
  55433. }
  55434. break;
  55435. default:
  55436. validParameter = false;
  55437. break;
  55438. }
  55439. if (!validParameter) {
  55440. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55441. }
  55442. else {
  55443. if (!codecSupportedFound) {
  55444. this._isReadyToPlay = true;
  55445. // Simulating a ready to play event to avoid breaking code path
  55446. if (this._readyToPlayCallback) {
  55447. window.setTimeout(function () {
  55448. if (_this._readyToPlayCallback) {
  55449. _this._readyToPlayCallback();
  55450. }
  55451. }, 1000);
  55452. }
  55453. }
  55454. }
  55455. }
  55456. }
  55457. else {
  55458. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55459. this._scene.mainSoundTrack.AddSound(this);
  55460. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55461. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55462. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55463. }
  55464. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55465. if (this._readyToPlayCallback) {
  55466. window.setTimeout(function () {
  55467. if (_this._readyToPlayCallback) {
  55468. _this._readyToPlayCallback();
  55469. }
  55470. }, 1000);
  55471. }
  55472. }
  55473. }
  55474. Sound.prototype.dispose = function () {
  55475. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55476. if (this.isPlaying) {
  55477. this.stop();
  55478. }
  55479. this._isReadyToPlay = false;
  55480. if (this.soundTrackId === -1) {
  55481. this._scene.mainSoundTrack.RemoveSound(this);
  55482. }
  55483. else {
  55484. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55485. }
  55486. if (this._soundGain) {
  55487. this._soundGain.disconnect();
  55488. this._soundGain = null;
  55489. }
  55490. if (this._soundPanner) {
  55491. this._soundPanner.disconnect();
  55492. this._soundPanner = null;
  55493. }
  55494. if (this._soundSource) {
  55495. this._soundSource.disconnect();
  55496. this._soundSource = null;
  55497. }
  55498. this._audioBuffer = null;
  55499. if (this._htmlAudioElement) {
  55500. this._htmlAudioElement.pause();
  55501. this._htmlAudioElement.src = "";
  55502. document.body.removeChild(this._htmlAudioElement);
  55503. }
  55504. if (this._connectedMesh && this._registerFunc) {
  55505. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55506. this._connectedMesh = null;
  55507. }
  55508. }
  55509. };
  55510. Sound.prototype.isReady = function () {
  55511. return this._isReadyToPlay;
  55512. };
  55513. Sound.prototype._soundLoaded = function (audioData) {
  55514. var _this = this;
  55515. if (!BABYLON.Engine.audioEngine.audioContext) {
  55516. return;
  55517. }
  55518. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55519. _this._audioBuffer = buffer;
  55520. _this._isReadyToPlay = true;
  55521. if (_this.autoplay) {
  55522. _this.play();
  55523. }
  55524. if (_this._readyToPlayCallback) {
  55525. _this._readyToPlayCallback();
  55526. }
  55527. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55528. };
  55529. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55530. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55531. this._audioBuffer = audioBuffer;
  55532. this._isReadyToPlay = true;
  55533. }
  55534. };
  55535. Sound.prototype.updateOptions = function (options) {
  55536. if (options) {
  55537. this.loop = options.loop || this.loop;
  55538. this.maxDistance = options.maxDistance || this.maxDistance;
  55539. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55540. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55541. this.refDistance = options.refDistance || this.refDistance;
  55542. this.distanceModel = options.distanceModel || this.distanceModel;
  55543. this._playbackRate = options.playbackRate || this._playbackRate;
  55544. this._updateSpatialParameters();
  55545. if (this.isPlaying) {
  55546. if (this._streaming) {
  55547. this._htmlAudioElement.playbackRate = this._playbackRate;
  55548. }
  55549. else {
  55550. if (this._soundSource) {
  55551. this._soundSource.playbackRate.value = this._playbackRate;
  55552. }
  55553. }
  55554. }
  55555. }
  55556. };
  55557. Sound.prototype._createSpatialParameters = function () {
  55558. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55559. if (this._scene.headphone) {
  55560. this._panningModel = "HRTF";
  55561. }
  55562. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55563. this._updateSpatialParameters();
  55564. this._soundPanner.connect(this._ouputAudioNode);
  55565. this._inputAudioNode = this._soundPanner;
  55566. }
  55567. };
  55568. Sound.prototype._updateSpatialParameters = function () {
  55569. if (this.spatialSound && this._soundPanner) {
  55570. if (this.useCustomAttenuation) {
  55571. // Tricks to disable in a way embedded Web Audio attenuation
  55572. this._soundPanner.distanceModel = "linear";
  55573. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55574. this._soundPanner.refDistance = 1;
  55575. this._soundPanner.rolloffFactor = 1;
  55576. this._soundPanner.panningModel = this._panningModel;
  55577. }
  55578. else {
  55579. this._soundPanner.distanceModel = this.distanceModel;
  55580. this._soundPanner.maxDistance = this.maxDistance;
  55581. this._soundPanner.refDistance = this.refDistance;
  55582. this._soundPanner.rolloffFactor = this.rolloffFactor;
  55583. this._soundPanner.panningModel = this._panningModel;
  55584. }
  55585. }
  55586. };
  55587. Sound.prototype.switchPanningModelToHRTF = function () {
  55588. this._panningModel = "HRTF";
  55589. this._switchPanningModel();
  55590. };
  55591. Sound.prototype.switchPanningModelToEqualPower = function () {
  55592. this._panningModel = "equalpower";
  55593. this._switchPanningModel();
  55594. };
  55595. Sound.prototype._switchPanningModel = function () {
  55596. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55597. this._soundPanner.panningModel = this._panningModel;
  55598. }
  55599. };
  55600. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  55601. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55602. if (this._isOutputConnected) {
  55603. this._ouputAudioNode.disconnect();
  55604. }
  55605. this._ouputAudioNode.connect(soundTrackAudioNode);
  55606. this._isOutputConnected = true;
  55607. }
  55608. };
  55609. /**
  55610. * Transform this sound into a directional source
  55611. * @param coneInnerAngle Size of the inner cone in degree
  55612. * @param coneOuterAngle Size of the outer cone in degree
  55613. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  55614. */
  55615. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  55616. if (coneOuterAngle < coneInnerAngle) {
  55617. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  55618. return;
  55619. }
  55620. this._coneInnerAngle = coneInnerAngle;
  55621. this._coneOuterAngle = coneOuterAngle;
  55622. this._coneOuterGain = coneOuterGain;
  55623. this._isDirectional = true;
  55624. if (this.isPlaying && this.loop) {
  55625. this.stop();
  55626. this.play();
  55627. }
  55628. };
  55629. Sound.prototype.setPosition = function (newPosition) {
  55630. this._position = newPosition;
  55631. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  55632. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55633. }
  55634. };
  55635. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  55636. this._localDirection = newLocalDirection;
  55637. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  55638. this._updateDirection();
  55639. }
  55640. };
  55641. Sound.prototype._updateDirection = function () {
  55642. if (!this._connectedMesh || !this._soundPanner) {
  55643. return;
  55644. }
  55645. var mat = this._connectedMesh.getWorldMatrix();
  55646. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  55647. direction.normalize();
  55648. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  55649. };
  55650. Sound.prototype.updateDistanceFromListener = function () {
  55651. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  55652. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  55653. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  55654. }
  55655. };
  55656. Sound.prototype.setAttenuationFunction = function (callback) {
  55657. this._customAttenuationFunction = callback;
  55658. };
  55659. /**
  55660. * Play the sound
  55661. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  55662. * @param offset (optional) Start the sound setting it at a specific time
  55663. */
  55664. Sound.prototype.play = function (time, offset) {
  55665. var _this = this;
  55666. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  55667. try {
  55668. if (this._startOffset < 0) {
  55669. time = -this._startOffset;
  55670. this._startOffset = 0;
  55671. }
  55672. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55673. if (!this._soundSource || !this._streamingSource) {
  55674. if (this.spatialSound && this._soundPanner) {
  55675. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  55676. if (this._isDirectional) {
  55677. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  55678. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  55679. this._soundPanner.coneOuterGain = this._coneOuterGain;
  55680. if (this._connectedMesh) {
  55681. this._updateDirection();
  55682. }
  55683. else {
  55684. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  55685. }
  55686. }
  55687. }
  55688. }
  55689. if (this._streaming) {
  55690. if (!this._streamingSource) {
  55691. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  55692. this._htmlAudioElement.onended = function () { _this._onended(); };
  55693. this._htmlAudioElement.playbackRate = this._playbackRate;
  55694. }
  55695. this._streamingSource.disconnect();
  55696. this._streamingSource.connect(this._inputAudioNode);
  55697. this._htmlAudioElement.play();
  55698. }
  55699. else {
  55700. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  55701. this._soundSource.buffer = this._audioBuffer;
  55702. this._soundSource.connect(this._inputAudioNode);
  55703. this._soundSource.loop = this.loop;
  55704. this._soundSource.playbackRate.value = this._playbackRate;
  55705. this._soundSource.onended = function () { _this._onended(); };
  55706. if (this._soundSource.buffer) {
  55707. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  55708. }
  55709. }
  55710. this._startTime = startTime;
  55711. this.isPlaying = true;
  55712. this.isPaused = false;
  55713. }
  55714. catch (ex) {
  55715. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  55716. }
  55717. }
  55718. };
  55719. Sound.prototype._onended = function () {
  55720. this.isPlaying = false;
  55721. if (this.onended) {
  55722. this.onended();
  55723. }
  55724. };
  55725. /**
  55726. * Stop the sound
  55727. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  55728. */
  55729. Sound.prototype.stop = function (time) {
  55730. if (this.isPlaying) {
  55731. if (this._streaming) {
  55732. this._htmlAudioElement.pause();
  55733. // Test needed for Firefox or it will generate an Invalid State Error
  55734. if (this._htmlAudioElement.currentTime > 0) {
  55735. this._htmlAudioElement.currentTime = 0;
  55736. }
  55737. }
  55738. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  55739. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  55740. this._soundSource.stop(stopTime);
  55741. this._soundSource.onended = function () { };
  55742. if (!this.isPaused) {
  55743. this._startOffset = 0;
  55744. }
  55745. }
  55746. this.isPlaying = false;
  55747. }
  55748. };
  55749. Sound.prototype.pause = function () {
  55750. if (this.isPlaying) {
  55751. this.isPaused = true;
  55752. if (this._streaming) {
  55753. this._htmlAudioElement.pause();
  55754. }
  55755. else if (BABYLON.Engine.audioEngine.audioContext) {
  55756. this.stop(0);
  55757. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  55758. }
  55759. }
  55760. };
  55761. Sound.prototype.setVolume = function (newVolume, time) {
  55762. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  55763. if (time && BABYLON.Engine.audioEngine.audioContext) {
  55764. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  55765. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  55766. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  55767. }
  55768. else {
  55769. this._soundGain.gain.value = newVolume;
  55770. }
  55771. }
  55772. this._volume = newVolume;
  55773. };
  55774. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  55775. this._playbackRate = newPlaybackRate;
  55776. if (this.isPlaying) {
  55777. if (this._streaming) {
  55778. this._htmlAudioElement.playbackRate = this._playbackRate;
  55779. }
  55780. else if (this._soundSource) {
  55781. this._soundSource.playbackRate.value = this._playbackRate;
  55782. }
  55783. }
  55784. };
  55785. Sound.prototype.getVolume = function () {
  55786. return this._volume;
  55787. };
  55788. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  55789. var _this = this;
  55790. if (this._connectedMesh && this._registerFunc) {
  55791. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55792. this._registerFunc = null;
  55793. }
  55794. this._connectedMesh = meshToConnectTo;
  55795. if (!this.spatialSound) {
  55796. this.spatialSound = true;
  55797. this._createSpatialParameters();
  55798. if (this.isPlaying && this.loop) {
  55799. this.stop();
  55800. this.play();
  55801. }
  55802. }
  55803. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  55804. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  55805. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  55806. };
  55807. Sound.prototype.detachFromMesh = function () {
  55808. if (this._connectedMesh && this._registerFunc) {
  55809. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55810. this._registerFunc = null;
  55811. this._connectedMesh = null;
  55812. }
  55813. };
  55814. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  55815. if (!node.getBoundingInfo) {
  55816. return;
  55817. }
  55818. var mesh = node;
  55819. var boundingInfo = mesh.getBoundingInfo();
  55820. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  55821. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  55822. this._updateDirection();
  55823. }
  55824. };
  55825. Sound.prototype.clone = function () {
  55826. var _this = this;
  55827. if (!this._streaming) {
  55828. var setBufferAndRun = function () {
  55829. if (_this._isReadyToPlay) {
  55830. clonedSound._audioBuffer = _this.getAudioBuffer();
  55831. clonedSound._isReadyToPlay = true;
  55832. if (clonedSound.autoplay) {
  55833. clonedSound.play();
  55834. }
  55835. }
  55836. else {
  55837. window.setTimeout(setBufferAndRun, 300);
  55838. }
  55839. };
  55840. var currentOptions = {
  55841. autoplay: this.autoplay, loop: this.loop,
  55842. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  55843. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  55844. refDistance: this.refDistance, distanceModel: this.distanceModel
  55845. };
  55846. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  55847. if (this.useCustomAttenuation) {
  55848. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  55849. }
  55850. clonedSound.setPosition(this._position);
  55851. clonedSound.setPlaybackRate(this._playbackRate);
  55852. setBufferAndRun();
  55853. return clonedSound;
  55854. }
  55855. else {
  55856. return null;
  55857. }
  55858. };
  55859. Sound.prototype.getAudioBuffer = function () {
  55860. return this._audioBuffer;
  55861. };
  55862. Sound.prototype.serialize = function () {
  55863. var serializationObject = {
  55864. name: this.name,
  55865. url: this.name,
  55866. autoplay: this.autoplay,
  55867. loop: this.loop,
  55868. volume: this._volume,
  55869. spatialSound: this.spatialSound,
  55870. maxDistance: this.maxDistance,
  55871. rolloffFactor: this.rolloffFactor,
  55872. refDistance: this.refDistance,
  55873. distanceModel: this.distanceModel,
  55874. playbackRate: this._playbackRate,
  55875. panningModel: this._panningModel,
  55876. soundTrackId: this.soundTrackId
  55877. };
  55878. if (this.spatialSound) {
  55879. if (this._connectedMesh)
  55880. serializationObject.connectedMeshId = this._connectedMesh.id;
  55881. serializationObject.position = this._position.asArray();
  55882. serializationObject.refDistance = this.refDistance;
  55883. serializationObject.distanceModel = this.distanceModel;
  55884. serializationObject.isDirectional = this._isDirectional;
  55885. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  55886. serializationObject.coneInnerAngle = this._coneInnerAngle;
  55887. serializationObject.coneOuterAngle = this._coneOuterAngle;
  55888. serializationObject.coneOuterGain = this._coneOuterGain;
  55889. }
  55890. return serializationObject;
  55891. };
  55892. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  55893. var soundName = parsedSound.name;
  55894. var soundUrl;
  55895. if (parsedSound.url) {
  55896. soundUrl = rootUrl + parsedSound.url;
  55897. }
  55898. else {
  55899. soundUrl = rootUrl + soundName;
  55900. }
  55901. var options = {
  55902. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  55903. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  55904. rolloffFactor: parsedSound.rolloffFactor,
  55905. refDistance: parsedSound.refDistance,
  55906. distanceModel: parsedSound.distanceModel,
  55907. playbackRate: parsedSound.playbackRate
  55908. };
  55909. var newSound;
  55910. if (!sourceSound) {
  55911. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  55912. scene._addPendingData(newSound);
  55913. }
  55914. else {
  55915. var setBufferAndRun = function () {
  55916. if (sourceSound._isReadyToPlay) {
  55917. newSound._audioBuffer = sourceSound.getAudioBuffer();
  55918. newSound._isReadyToPlay = true;
  55919. if (newSound.autoplay) {
  55920. newSound.play();
  55921. }
  55922. }
  55923. else {
  55924. window.setTimeout(setBufferAndRun, 300);
  55925. }
  55926. };
  55927. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  55928. setBufferAndRun();
  55929. }
  55930. if (parsedSound.position) {
  55931. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  55932. newSound.setPosition(soundPosition);
  55933. }
  55934. if (parsedSound.isDirectional) {
  55935. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  55936. if (parsedSound.localDirectionToMesh) {
  55937. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  55938. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  55939. }
  55940. }
  55941. if (parsedSound.connectedMeshId) {
  55942. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  55943. if (connectedMesh) {
  55944. newSound.attachToMesh(connectedMesh);
  55945. }
  55946. }
  55947. return newSound;
  55948. };
  55949. return Sound;
  55950. }());
  55951. BABYLON.Sound = Sound;
  55952. })(BABYLON || (BABYLON = {}));
  55953. //# sourceMappingURL=babylon.sound.js.map
  55954. var BABYLON;
  55955. (function (BABYLON) {
  55956. var SoundTrack = /** @class */ (function () {
  55957. function SoundTrack(scene, options) {
  55958. this.id = -1;
  55959. this._isMainTrack = false;
  55960. this._isInitialized = false;
  55961. this._scene = scene;
  55962. this.soundCollection = new Array();
  55963. this._options = options;
  55964. if (!this._isMainTrack) {
  55965. this._scene.soundTracks.push(this);
  55966. this.id = this._scene.soundTracks.length - 1;
  55967. }
  55968. }
  55969. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  55970. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55971. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  55972. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  55973. if (this._options) {
  55974. if (this._options.volume) {
  55975. this._outputAudioNode.gain.value = this._options.volume;
  55976. }
  55977. if (this._options.mainTrack) {
  55978. this._isMainTrack = this._options.mainTrack;
  55979. }
  55980. }
  55981. this._isInitialized = true;
  55982. }
  55983. };
  55984. SoundTrack.prototype.dispose = function () {
  55985. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  55986. if (this._connectedAnalyser) {
  55987. this._connectedAnalyser.stopDebugCanvas();
  55988. }
  55989. while (this.soundCollection.length) {
  55990. this.soundCollection[0].dispose();
  55991. }
  55992. if (this._outputAudioNode) {
  55993. this._outputAudioNode.disconnect();
  55994. }
  55995. this._outputAudioNode = null;
  55996. }
  55997. };
  55998. SoundTrack.prototype.AddSound = function (sound) {
  55999. if (!this._isInitialized) {
  56000. this._initializeSoundTrackAudioGraph();
  56001. }
  56002. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56003. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56004. }
  56005. if (sound.soundTrackId) {
  56006. if (sound.soundTrackId === -1) {
  56007. this._scene.mainSoundTrack.RemoveSound(sound);
  56008. }
  56009. else {
  56010. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56011. }
  56012. }
  56013. this.soundCollection.push(sound);
  56014. sound.soundTrackId = this.id;
  56015. };
  56016. SoundTrack.prototype.RemoveSound = function (sound) {
  56017. var index = this.soundCollection.indexOf(sound);
  56018. if (index !== -1) {
  56019. this.soundCollection.splice(index, 1);
  56020. }
  56021. };
  56022. SoundTrack.prototype.setVolume = function (newVolume) {
  56023. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56024. this._outputAudioNode.gain.value = newVolume;
  56025. }
  56026. };
  56027. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56028. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56029. for (var i = 0; i < this.soundCollection.length; i++) {
  56030. this.soundCollection[i].switchPanningModelToHRTF();
  56031. }
  56032. }
  56033. };
  56034. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56035. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56036. for (var i = 0; i < this.soundCollection.length; i++) {
  56037. this.soundCollection[i].switchPanningModelToEqualPower();
  56038. }
  56039. }
  56040. };
  56041. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56042. if (this._connectedAnalyser) {
  56043. this._connectedAnalyser.stopDebugCanvas();
  56044. }
  56045. this._connectedAnalyser = analyser;
  56046. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56047. this._outputAudioNode.disconnect();
  56048. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56049. }
  56050. };
  56051. return SoundTrack;
  56052. }());
  56053. BABYLON.SoundTrack = SoundTrack;
  56054. })(BABYLON || (BABYLON = {}));
  56055. //# sourceMappingURL=babylon.soundtrack.js.map
  56056. var BABYLON;
  56057. (function (BABYLON) {
  56058. var Analyser = /** @class */ (function () {
  56059. function Analyser(scene) {
  56060. this.SMOOTHING = 0.75;
  56061. this.FFT_SIZE = 512;
  56062. this.BARGRAPHAMPLITUDE = 256;
  56063. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56064. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56065. this._scene = scene;
  56066. this._audioEngine = BABYLON.Engine.audioEngine;
  56067. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56068. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56069. this._webAudioAnalyser.minDecibels = -140;
  56070. this._webAudioAnalyser.maxDecibels = 0;
  56071. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56072. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56073. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56074. }
  56075. }
  56076. Analyser.prototype.getFrequencyBinCount = function () {
  56077. if (this._audioEngine.canUseWebAudio) {
  56078. return this._webAudioAnalyser.frequencyBinCount;
  56079. }
  56080. else {
  56081. return 0;
  56082. }
  56083. };
  56084. Analyser.prototype.getByteFrequencyData = function () {
  56085. if (this._audioEngine.canUseWebAudio) {
  56086. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56087. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56088. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56089. }
  56090. return this._byteFreqs;
  56091. };
  56092. Analyser.prototype.getByteTimeDomainData = function () {
  56093. if (this._audioEngine.canUseWebAudio) {
  56094. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56095. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56096. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56097. }
  56098. return this._byteTime;
  56099. };
  56100. Analyser.prototype.getFloatFrequencyData = function () {
  56101. if (this._audioEngine.canUseWebAudio) {
  56102. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56103. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56104. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56105. }
  56106. return this._floatFreqs;
  56107. };
  56108. Analyser.prototype.drawDebugCanvas = function () {
  56109. var _this = this;
  56110. if (this._audioEngine.canUseWebAudio) {
  56111. if (!this._debugCanvas) {
  56112. this._debugCanvas = document.createElement("canvas");
  56113. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56114. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56115. this._debugCanvas.style.position = "absolute";
  56116. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56117. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56118. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56119. document.body.appendChild(this._debugCanvas);
  56120. this._registerFunc = function () {
  56121. _this.drawDebugCanvas();
  56122. };
  56123. this._scene.registerBeforeRender(this._registerFunc);
  56124. }
  56125. if (this._registerFunc && this._debugCanvasContext) {
  56126. var workingArray = this.getByteFrequencyData();
  56127. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56128. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56129. // Draw the frequency domain chart.
  56130. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56131. var value = workingArray[i];
  56132. var percent = value / this.BARGRAPHAMPLITUDE;
  56133. var height = this.DEBUGCANVASSIZE.height * percent;
  56134. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56135. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56136. var hue = i / this.getFrequencyBinCount() * 360;
  56137. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56138. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56139. }
  56140. }
  56141. }
  56142. };
  56143. Analyser.prototype.stopDebugCanvas = function () {
  56144. if (this._debugCanvas) {
  56145. if (this._registerFunc) {
  56146. this._scene.unregisterBeforeRender(this._registerFunc);
  56147. this._registerFunc = null;
  56148. }
  56149. document.body.removeChild(this._debugCanvas);
  56150. this._debugCanvas = null;
  56151. this._debugCanvasContext = null;
  56152. }
  56153. };
  56154. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56155. if (this._audioEngine.canUseWebAudio) {
  56156. inputAudioNode.connect(this._webAudioAnalyser);
  56157. this._webAudioAnalyser.connect(outputAudioNode);
  56158. }
  56159. };
  56160. Analyser.prototype.dispose = function () {
  56161. if (this._audioEngine.canUseWebAudio) {
  56162. this._webAudioAnalyser.disconnect();
  56163. }
  56164. };
  56165. return Analyser;
  56166. }());
  56167. BABYLON.Analyser = Analyser;
  56168. })(BABYLON || (BABYLON = {}));
  56169. //# sourceMappingURL=babylon.analyser.js.map
  56170. var BABYLON;
  56171. (function (BABYLON) {
  56172. var CubeTexture = /** @class */ (function (_super) {
  56173. __extends(CubeTexture, _super);
  56174. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  56175. if (extensions === void 0) { extensions = null; }
  56176. if (noMipmap === void 0) { noMipmap = false; }
  56177. if (files === void 0) { files = null; }
  56178. if (onLoad === void 0) { onLoad = null; }
  56179. if (onError === void 0) { onError = null; }
  56180. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56181. if (prefiltered === void 0) { prefiltered = false; }
  56182. if (forcedExtension === void 0) { forcedExtension = null; }
  56183. var _this = _super.call(this, scene) || this;
  56184. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56185. /**
  56186. * Gets or sets the center of the bounding box associated with the cube texture
  56187. * It must define where the camera used to render the texture was set
  56188. */
  56189. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56190. _this.name = rootUrl;
  56191. _this.url = rootUrl;
  56192. _this._noMipmap = noMipmap;
  56193. _this.hasAlpha = false;
  56194. _this._format = format;
  56195. _this._prefiltered = prefiltered;
  56196. _this.isCube = true;
  56197. _this._textureMatrix = BABYLON.Matrix.Identity();
  56198. if (prefiltered) {
  56199. _this.gammaSpace = false;
  56200. }
  56201. if (!rootUrl && !files) {
  56202. return _this;
  56203. }
  56204. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56205. var lastDot = rootUrl.lastIndexOf(".");
  56206. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56207. var isDDS = (extension === ".dds");
  56208. if (!files) {
  56209. if (!isDDS && !extensions) {
  56210. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56211. }
  56212. files = [];
  56213. if (extensions) {
  56214. for (var index = 0; index < extensions.length; index++) {
  56215. files.push(rootUrl + extensions[index]);
  56216. }
  56217. }
  56218. }
  56219. _this._files = files;
  56220. if (!_this._texture) {
  56221. if (!scene.useDelayedTextureLoading) {
  56222. if (prefiltered) {
  56223. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56224. }
  56225. else {
  56226. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56227. }
  56228. }
  56229. else {
  56230. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56231. }
  56232. }
  56233. else if (onLoad) {
  56234. if (_this._texture.isReady) {
  56235. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56236. }
  56237. else {
  56238. _this._texture.onLoadedObservable.add(onLoad);
  56239. }
  56240. }
  56241. return _this;
  56242. }
  56243. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56244. get: function () {
  56245. return this._boundingBoxSize;
  56246. },
  56247. /**
  56248. * Gets or sets the size of the bounding box associated with the cube texture
  56249. * When defined, the cubemap will switch to local mode
  56250. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56251. * @example https://www.babylonjs-playground.com/#RNASML
  56252. */
  56253. set: function (value) {
  56254. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56255. return;
  56256. }
  56257. this._boundingBoxSize = value;
  56258. var scene = this.getScene();
  56259. if (scene) {
  56260. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56261. }
  56262. },
  56263. enumerable: true,
  56264. configurable: true
  56265. });
  56266. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56267. return new CubeTexture("", scene, null, noMipmap, files);
  56268. };
  56269. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56270. if (forcedExtension === void 0) { forcedExtension = null; }
  56271. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56272. };
  56273. // Methods
  56274. CubeTexture.prototype.delayLoad = function () {
  56275. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56276. return;
  56277. }
  56278. var scene = this.getScene();
  56279. if (!scene) {
  56280. return;
  56281. }
  56282. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56283. this._texture = this._getFromCache(this.url, this._noMipmap);
  56284. if (!this._texture) {
  56285. if (this._prefiltered) {
  56286. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  56287. }
  56288. else {
  56289. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  56290. }
  56291. }
  56292. };
  56293. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  56294. return this._textureMatrix;
  56295. };
  56296. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56297. this._textureMatrix = value;
  56298. };
  56299. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56300. var texture = BABYLON.SerializationHelper.Parse(function () {
  56301. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  56302. }, parsedTexture, scene);
  56303. // Animations
  56304. if (parsedTexture.animations) {
  56305. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56306. var parsedAnimation = parsedTexture.animations[animationIndex];
  56307. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56308. }
  56309. }
  56310. return texture;
  56311. };
  56312. CubeTexture.prototype.clone = function () {
  56313. var _this = this;
  56314. return BABYLON.SerializationHelper.Clone(function () {
  56315. var scene = _this.getScene();
  56316. if (!scene) {
  56317. return _this;
  56318. }
  56319. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56320. }, this);
  56321. };
  56322. return CubeTexture;
  56323. }(BABYLON.BaseTexture));
  56324. BABYLON.CubeTexture = CubeTexture;
  56325. })(BABYLON || (BABYLON = {}));
  56326. //# sourceMappingURL=babylon.cubeTexture.js.map
  56327. var BABYLON;
  56328. (function (BABYLON) {
  56329. var RenderTargetTexture = /** @class */ (function (_super) {
  56330. __extends(RenderTargetTexture, _super);
  56331. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56332. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56333. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56334. if (isCube === void 0) { isCube = false; }
  56335. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56336. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56337. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56338. if (isMulti === void 0) { isMulti = false; }
  56339. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56340. _this.isCube = isCube;
  56341. /**
  56342. * Use this list to define the list of mesh you want to render.
  56343. */
  56344. _this.renderList = new Array();
  56345. _this.renderParticles = true;
  56346. _this.renderSprites = false;
  56347. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56348. _this.ignoreCameraViewport = false;
  56349. // Events
  56350. /**
  56351. * An event triggered when the texture is unbind.
  56352. * @type {BABYLON.Observable}
  56353. */
  56354. _this.onBeforeBindObservable = new BABYLON.Observable();
  56355. /**
  56356. * An event triggered when the texture is unbind.
  56357. * @type {BABYLON.Observable}
  56358. */
  56359. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56360. /**
  56361. * An event triggered before rendering the texture
  56362. * @type {BABYLON.Observable}
  56363. */
  56364. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56365. /**
  56366. * An event triggered after rendering the texture
  56367. * @type {BABYLON.Observable}
  56368. */
  56369. _this.onAfterRenderObservable = new BABYLON.Observable();
  56370. /**
  56371. * An event triggered after the texture clear
  56372. * @type {BABYLON.Observable}
  56373. */
  56374. _this.onClearObservable = new BABYLON.Observable();
  56375. _this._currentRefreshId = -1;
  56376. _this._refreshRate = 1;
  56377. _this._samples = 1;
  56378. /**
  56379. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56380. * It must define where the camera used to render the texture is set
  56381. */
  56382. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56383. scene = _this.getScene();
  56384. if (!scene) {
  56385. return _this;
  56386. }
  56387. _this._engine = scene.getEngine();
  56388. _this.name = name;
  56389. _this.isRenderTarget = true;
  56390. _this._initialSizeParameter = size;
  56391. _this._processSizeParameter(size);
  56392. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56393. });
  56394. _this._generateMipMaps = generateMipMaps ? true : false;
  56395. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56396. // Rendering groups
  56397. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56398. if (isMulti) {
  56399. return _this;
  56400. }
  56401. _this._renderTargetOptions = {
  56402. generateMipMaps: generateMipMaps,
  56403. type: type,
  56404. samplingMode: samplingMode,
  56405. generateDepthBuffer: generateDepthBuffer,
  56406. generateStencilBuffer: generateStencilBuffer
  56407. };
  56408. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56409. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56410. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56411. }
  56412. if (isCube) {
  56413. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56414. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56415. _this._textureMatrix = BABYLON.Matrix.Identity();
  56416. }
  56417. else {
  56418. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56419. }
  56420. return _this;
  56421. }
  56422. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56423. get: function () {
  56424. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56425. },
  56426. enumerable: true,
  56427. configurable: true
  56428. });
  56429. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56430. get: function () {
  56431. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56432. },
  56433. enumerable: true,
  56434. configurable: true
  56435. });
  56436. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56437. get: function () {
  56438. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56439. },
  56440. enumerable: true,
  56441. configurable: true
  56442. });
  56443. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56444. set: function (callback) {
  56445. if (this._onAfterUnbindObserver) {
  56446. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56447. }
  56448. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56449. },
  56450. enumerable: true,
  56451. configurable: true
  56452. });
  56453. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56454. set: function (callback) {
  56455. if (this._onBeforeRenderObserver) {
  56456. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56457. }
  56458. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56459. },
  56460. enumerable: true,
  56461. configurable: true
  56462. });
  56463. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56464. set: function (callback) {
  56465. if (this._onAfterRenderObserver) {
  56466. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56467. }
  56468. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56469. },
  56470. enumerable: true,
  56471. configurable: true
  56472. });
  56473. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56474. set: function (callback) {
  56475. if (this._onClearObserver) {
  56476. this.onClearObservable.remove(this._onClearObserver);
  56477. }
  56478. this._onClearObserver = this.onClearObservable.add(callback);
  56479. },
  56480. enumerable: true,
  56481. configurable: true
  56482. });
  56483. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56484. get: function () {
  56485. return this._renderTargetOptions;
  56486. },
  56487. enumerable: true,
  56488. configurable: true
  56489. });
  56490. RenderTargetTexture.prototype._onRatioRescale = function () {
  56491. if (this._sizeRatio) {
  56492. this.resize(this._initialSizeParameter);
  56493. }
  56494. };
  56495. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56496. get: function () {
  56497. return this._boundingBoxSize;
  56498. },
  56499. /**
  56500. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56501. * When defined, the cubemap will switch to local mode
  56502. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56503. * @example https://www.babylonjs-playground.com/#RNASML
  56504. */
  56505. set: function (value) {
  56506. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56507. return;
  56508. }
  56509. this._boundingBoxSize = value;
  56510. var scene = this.getScene();
  56511. if (scene) {
  56512. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56513. }
  56514. },
  56515. enumerable: true,
  56516. configurable: true
  56517. });
  56518. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56519. if (size.ratio) {
  56520. this._sizeRatio = size.ratio;
  56521. this._size = {
  56522. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56523. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56524. };
  56525. }
  56526. else {
  56527. this._size = size;
  56528. }
  56529. };
  56530. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56531. get: function () {
  56532. return this._samples;
  56533. },
  56534. set: function (value) {
  56535. if (this._samples === value) {
  56536. return;
  56537. }
  56538. var scene = this.getScene();
  56539. if (!scene) {
  56540. return;
  56541. }
  56542. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56543. },
  56544. enumerable: true,
  56545. configurable: true
  56546. });
  56547. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56548. this._currentRefreshId = -1;
  56549. };
  56550. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56551. get: function () {
  56552. return this._refreshRate;
  56553. },
  56554. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56555. set: function (value) {
  56556. this._refreshRate = value;
  56557. this.resetRefreshCounter();
  56558. },
  56559. enumerable: true,
  56560. configurable: true
  56561. });
  56562. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56563. if (!this._postProcessManager) {
  56564. var scene = this.getScene();
  56565. if (!scene) {
  56566. return;
  56567. }
  56568. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56569. this._postProcesses = new Array();
  56570. }
  56571. this._postProcesses.push(postProcess);
  56572. this._postProcesses[0].autoClear = false;
  56573. };
  56574. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56575. if (!this._postProcesses) {
  56576. return;
  56577. }
  56578. if (dispose) {
  56579. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  56580. var postProcess = _a[_i];
  56581. postProcess.dispose();
  56582. }
  56583. }
  56584. this._postProcesses = [];
  56585. };
  56586. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  56587. if (!this._postProcesses) {
  56588. return;
  56589. }
  56590. var index = this._postProcesses.indexOf(postProcess);
  56591. if (index === -1) {
  56592. return;
  56593. }
  56594. this._postProcesses.splice(index, 1);
  56595. if (this._postProcesses.length > 0) {
  56596. this._postProcesses[0].autoClear = false;
  56597. }
  56598. };
  56599. RenderTargetTexture.prototype._shouldRender = function () {
  56600. if (this._currentRefreshId === -1) {
  56601. this._currentRefreshId = 1;
  56602. return true;
  56603. }
  56604. if (this.refreshRate === this._currentRefreshId) {
  56605. this._currentRefreshId = 1;
  56606. return true;
  56607. }
  56608. this._currentRefreshId++;
  56609. return false;
  56610. };
  56611. RenderTargetTexture.prototype.getRenderSize = function () {
  56612. if (this._size.width) {
  56613. return this._size.width;
  56614. }
  56615. return this._size;
  56616. };
  56617. RenderTargetTexture.prototype.getRenderWidth = function () {
  56618. if (this._size.width) {
  56619. return this._size.width;
  56620. }
  56621. return this._size;
  56622. };
  56623. RenderTargetTexture.prototype.getRenderHeight = function () {
  56624. if (this._size.width) {
  56625. return this._size.height;
  56626. }
  56627. return this._size;
  56628. };
  56629. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  56630. get: function () {
  56631. return true;
  56632. },
  56633. enumerable: true,
  56634. configurable: true
  56635. });
  56636. RenderTargetTexture.prototype.scale = function (ratio) {
  56637. var newSize = this.getRenderSize() * ratio;
  56638. this.resize(newSize);
  56639. };
  56640. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  56641. if (this.isCube) {
  56642. return this._textureMatrix;
  56643. }
  56644. return _super.prototype.getReflectionTextureMatrix.call(this);
  56645. };
  56646. RenderTargetTexture.prototype.resize = function (size) {
  56647. this.releaseInternalTexture();
  56648. var scene = this.getScene();
  56649. if (!scene) {
  56650. return;
  56651. }
  56652. this._processSizeParameter(size);
  56653. if (this.isCube) {
  56654. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  56655. }
  56656. else {
  56657. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  56658. }
  56659. };
  56660. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  56661. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  56662. if (dumpForDebug === void 0) { dumpForDebug = false; }
  56663. var scene = this.getScene();
  56664. if (!scene) {
  56665. return;
  56666. }
  56667. var engine = scene.getEngine();
  56668. if (this.useCameraPostProcesses !== undefined) {
  56669. useCameraPostProcess = this.useCameraPostProcesses;
  56670. }
  56671. if (this._waitingRenderList) {
  56672. this.renderList = [];
  56673. for (var index = 0; index < this._waitingRenderList.length; index++) {
  56674. var id = this._waitingRenderList[index];
  56675. var mesh_1 = scene.getMeshByID(id);
  56676. if (mesh_1) {
  56677. this.renderList.push(mesh_1);
  56678. }
  56679. }
  56680. delete this._waitingRenderList;
  56681. }
  56682. // Is predicate defined?
  56683. if (this.renderListPredicate) {
  56684. if (this.renderList) {
  56685. this.renderList.splice(0); // Clear previous renderList
  56686. }
  56687. else {
  56688. this.renderList = [];
  56689. }
  56690. var scene = this.getScene();
  56691. if (!scene) {
  56692. return;
  56693. }
  56694. var sceneMeshes = scene.meshes;
  56695. for (var index = 0; index < sceneMeshes.length; index++) {
  56696. var mesh = sceneMeshes[index];
  56697. if (this.renderListPredicate(mesh)) {
  56698. this.renderList.push(mesh);
  56699. }
  56700. }
  56701. }
  56702. this.onBeforeBindObservable.notifyObservers(this);
  56703. // Set custom projection.
  56704. // Needs to be before binding to prevent changing the aspect ratio.
  56705. var camera;
  56706. if (this.activeCamera) {
  56707. camera = this.activeCamera;
  56708. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56709. if (this.activeCamera !== scene.activeCamera) {
  56710. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  56711. }
  56712. }
  56713. else {
  56714. camera = scene.activeCamera;
  56715. if (camera) {
  56716. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  56717. }
  56718. }
  56719. // Prepare renderingManager
  56720. this._renderingManager.reset();
  56721. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  56722. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  56723. var sceneRenderId = scene.getRenderId();
  56724. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  56725. var mesh = currentRenderList[meshIndex];
  56726. if (mesh) {
  56727. if (!mesh.isReady()) {
  56728. // Reset _currentRefreshId
  56729. this.resetRefreshCounter();
  56730. continue;
  56731. }
  56732. mesh._preActivateForIntermediateRendering(sceneRenderId);
  56733. var isMasked = void 0;
  56734. if (!this.renderList && camera) {
  56735. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  56736. }
  56737. else {
  56738. isMasked = false;
  56739. }
  56740. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  56741. mesh._activate(sceneRenderId);
  56742. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  56743. var subMesh = mesh.subMeshes[subIndex];
  56744. scene._activeIndices.addCount(subMesh.indexCount, false);
  56745. this._renderingManager.dispatch(subMesh, mesh);
  56746. }
  56747. }
  56748. }
  56749. }
  56750. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  56751. var particleSystem = scene.particleSystems[particleIndex];
  56752. var emitter = particleSystem.emitter;
  56753. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  56754. continue;
  56755. }
  56756. if (currentRenderList.indexOf(emitter) >= 0) {
  56757. this._renderingManager.dispatchParticles(particleSystem);
  56758. }
  56759. }
  56760. if (this.isCube) {
  56761. for (var face = 0; face < 6; face++) {
  56762. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56763. scene.incrementRenderId();
  56764. scene.resetCachedMaterial();
  56765. }
  56766. }
  56767. else {
  56768. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  56769. }
  56770. this.onAfterUnbindObservable.notifyObservers(this);
  56771. if (scene.activeCamera) {
  56772. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  56773. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  56774. }
  56775. engine.setViewport(scene.activeCamera.viewport);
  56776. }
  56777. scene.resetCachedMaterial();
  56778. };
  56779. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  56780. var minimum = 128;
  56781. var x = renderDimension * scale;
  56782. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  56783. // Ensure we don't exceed the render dimension (while staying POT)
  56784. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  56785. };
  56786. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  56787. var _this = this;
  56788. if (!this._texture) {
  56789. return;
  56790. }
  56791. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  56792. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  56793. });
  56794. };
  56795. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  56796. var scene = this.getScene();
  56797. if (!scene) {
  56798. return;
  56799. }
  56800. var engine = scene.getEngine();
  56801. if (!this._texture) {
  56802. return;
  56803. }
  56804. // Bind
  56805. if (this._postProcessManager) {
  56806. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  56807. }
  56808. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  56809. if (this._texture) {
  56810. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  56811. }
  56812. }
  56813. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  56814. // Clear
  56815. if (this.onClearObservable.hasObservers()) {
  56816. this.onClearObservable.notifyObservers(engine);
  56817. }
  56818. else {
  56819. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  56820. }
  56821. if (!this._doNotChangeAspectRatio) {
  56822. scene.updateTransformMatrix(true);
  56823. }
  56824. // Render
  56825. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  56826. if (this._postProcessManager) {
  56827. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  56828. }
  56829. else if (useCameraPostProcess) {
  56830. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  56831. }
  56832. if (!this._doNotChangeAspectRatio) {
  56833. scene.updateTransformMatrix(true);
  56834. }
  56835. // Dump ?
  56836. if (dumpForDebug) {
  56837. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  56838. }
  56839. // Unbind
  56840. if (!this.isCube || faceIndex === 5) {
  56841. if (this.isCube) {
  56842. if (faceIndex === 5) {
  56843. engine.generateMipMapsForCubemap(this._texture);
  56844. }
  56845. }
  56846. this.unbindFrameBuffer(engine, faceIndex);
  56847. }
  56848. else {
  56849. this.onAfterRenderObservable.notifyObservers(faceIndex);
  56850. }
  56851. };
  56852. /**
  56853. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  56854. * This allowed control for front to back rendering or reversly depending of the special needs.
  56855. *
  56856. * @param renderingGroupId The rendering group id corresponding to its index
  56857. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  56858. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  56859. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  56860. */
  56861. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  56862. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  56863. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  56864. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  56865. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  56866. };
  56867. /**
  56868. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  56869. *
  56870. * @param renderingGroupId The rendering group id corresponding to its index
  56871. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  56872. */
  56873. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  56874. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  56875. };
  56876. RenderTargetTexture.prototype.clone = function () {
  56877. var textureSize = this.getSize();
  56878. 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);
  56879. // Base texture
  56880. newTexture.hasAlpha = this.hasAlpha;
  56881. newTexture.level = this.level;
  56882. // RenderTarget Texture
  56883. newTexture.coordinatesMode = this.coordinatesMode;
  56884. if (this.renderList) {
  56885. newTexture.renderList = this.renderList.slice(0);
  56886. }
  56887. return newTexture;
  56888. };
  56889. RenderTargetTexture.prototype.serialize = function () {
  56890. if (!this.name) {
  56891. return null;
  56892. }
  56893. var serializationObject = _super.prototype.serialize.call(this);
  56894. serializationObject.renderTargetSize = this.getRenderSize();
  56895. serializationObject.renderList = [];
  56896. if (this.renderList) {
  56897. for (var index = 0; index < this.renderList.length; index++) {
  56898. serializationObject.renderList.push(this.renderList[index].id);
  56899. }
  56900. }
  56901. return serializationObject;
  56902. };
  56903. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  56904. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  56905. var objBuffer = this.getInternalTexture();
  56906. var scene = this.getScene();
  56907. if (objBuffer && scene) {
  56908. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  56909. }
  56910. };
  56911. RenderTargetTexture.prototype.dispose = function () {
  56912. if (this._postProcessManager) {
  56913. this._postProcessManager.dispose();
  56914. this._postProcessManager = null;
  56915. }
  56916. this.clearPostProcesses(true);
  56917. if (this._resizeObserver) {
  56918. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  56919. this._resizeObserver = null;
  56920. }
  56921. this.renderList = null;
  56922. // Remove from custom render targets
  56923. var scene = this.getScene();
  56924. if (!scene) {
  56925. return;
  56926. }
  56927. var index = scene.customRenderTargets.indexOf(this);
  56928. if (index >= 0) {
  56929. scene.customRenderTargets.splice(index, 1);
  56930. }
  56931. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  56932. var camera = _a[_i];
  56933. index = camera.customRenderTargets.indexOf(this);
  56934. if (index >= 0) {
  56935. camera.customRenderTargets.splice(index, 1);
  56936. }
  56937. }
  56938. _super.prototype.dispose.call(this);
  56939. };
  56940. RenderTargetTexture.prototype._rebuild = function () {
  56941. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56942. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56943. }
  56944. if (this._postProcessManager) {
  56945. this._postProcessManager._rebuild();
  56946. }
  56947. };
  56948. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  56949. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  56950. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  56951. return RenderTargetTexture;
  56952. }(BABYLON.Texture));
  56953. BABYLON.RenderTargetTexture = RenderTargetTexture;
  56954. })(BABYLON || (BABYLON = {}));
  56955. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  56956. var BABYLON;
  56957. (function (BABYLON) {
  56958. ;
  56959. var MultiRenderTarget = /** @class */ (function (_super) {
  56960. __extends(MultiRenderTarget, _super);
  56961. function MultiRenderTarget(name, size, count, scene, options) {
  56962. var _this = this;
  56963. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  56964. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  56965. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  56966. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  56967. _this._engine = scene.getEngine();
  56968. if (!_this.isSupported) {
  56969. _this.dispose();
  56970. return;
  56971. }
  56972. var types = [];
  56973. var samplingModes = [];
  56974. for (var i = 0; i < count; i++) {
  56975. if (options && options.types && options.types[i] !== undefined) {
  56976. types.push(options.types[i]);
  56977. }
  56978. else {
  56979. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  56980. }
  56981. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  56982. samplingModes.push(options.samplingModes[i]);
  56983. }
  56984. else {
  56985. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  56986. }
  56987. }
  56988. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  56989. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  56990. _this._size = size;
  56991. _this._multiRenderTargetOptions = {
  56992. samplingModes: samplingModes,
  56993. generateMipMaps: generateMipMaps,
  56994. generateDepthBuffer: generateDepthBuffer,
  56995. generateStencilBuffer: generateStencilBuffer,
  56996. generateDepthTexture: generateDepthTexture,
  56997. types: types,
  56998. textureCount: count
  56999. };
  57000. _this._createInternalTextures();
  57001. _this._createTextures();
  57002. return _this;
  57003. }
  57004. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57005. get: function () {
  57006. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57007. },
  57008. enumerable: true,
  57009. configurable: true
  57010. });
  57011. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57012. get: function () {
  57013. return this._textures;
  57014. },
  57015. enumerable: true,
  57016. configurable: true
  57017. });
  57018. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57019. get: function () {
  57020. return this._textures[this._textures.length - 1];
  57021. },
  57022. enumerable: true,
  57023. configurable: true
  57024. });
  57025. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57026. set: function (wrap) {
  57027. if (this._textures) {
  57028. for (var i = 0; i < this._textures.length; i++) {
  57029. this._textures[i].wrapU = wrap;
  57030. }
  57031. }
  57032. },
  57033. enumerable: true,
  57034. configurable: true
  57035. });
  57036. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57037. set: function (wrap) {
  57038. if (this._textures) {
  57039. for (var i = 0; i < this._textures.length; i++) {
  57040. this._textures[i].wrapV = wrap;
  57041. }
  57042. }
  57043. },
  57044. enumerable: true,
  57045. configurable: true
  57046. });
  57047. MultiRenderTarget.prototype._rebuild = function () {
  57048. this.releaseInternalTextures();
  57049. this._createInternalTextures();
  57050. for (var i = 0; i < this._internalTextures.length; i++) {
  57051. var texture = this._textures[i];
  57052. texture._texture = this._internalTextures[i];
  57053. }
  57054. // Keeps references to frame buffer and stencil/depth buffer
  57055. this._texture = this._internalTextures[0];
  57056. };
  57057. MultiRenderTarget.prototype._createInternalTextures = function () {
  57058. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57059. };
  57060. MultiRenderTarget.prototype._createTextures = function () {
  57061. this._textures = [];
  57062. for (var i = 0; i < this._internalTextures.length; i++) {
  57063. var texture = new BABYLON.Texture(null, this.getScene());
  57064. texture._texture = this._internalTextures[i];
  57065. this._textures.push(texture);
  57066. }
  57067. // Keeps references to frame buffer and stencil/depth buffer
  57068. this._texture = this._internalTextures[0];
  57069. };
  57070. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57071. get: function () {
  57072. return this._samples;
  57073. },
  57074. set: function (value) {
  57075. if (this._samples === value) {
  57076. return;
  57077. }
  57078. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57079. },
  57080. enumerable: true,
  57081. configurable: true
  57082. });
  57083. MultiRenderTarget.prototype.resize = function (size) {
  57084. this.releaseInternalTextures();
  57085. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57086. this._createInternalTextures();
  57087. };
  57088. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57089. var _this = this;
  57090. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57091. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57092. });
  57093. };
  57094. MultiRenderTarget.prototype.dispose = function () {
  57095. this.releaseInternalTextures();
  57096. _super.prototype.dispose.call(this);
  57097. };
  57098. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57099. if (!this._internalTextures) {
  57100. return;
  57101. }
  57102. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57103. if (this._internalTextures[i] !== undefined) {
  57104. this._internalTextures[i].dispose();
  57105. this._internalTextures.splice(i, 1);
  57106. }
  57107. }
  57108. };
  57109. return MultiRenderTarget;
  57110. }(BABYLON.RenderTargetTexture));
  57111. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57112. })(BABYLON || (BABYLON = {}));
  57113. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57114. var BABYLON;
  57115. (function (BABYLON) {
  57116. var MirrorTexture = /** @class */ (function (_super) {
  57117. __extends(MirrorTexture, _super);
  57118. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57119. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57121. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57122. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57123. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57124. _this._transformMatrix = BABYLON.Matrix.Zero();
  57125. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57126. _this._adaptiveBlurKernel = 0;
  57127. _this._blurKernelX = 0;
  57128. _this._blurKernelY = 0;
  57129. _this._blurRatio = 1.0;
  57130. _this.ignoreCameraViewport = true;
  57131. _this.onBeforeRenderObservable.add(function () {
  57132. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57133. _this._savedViewMatrix = scene.getViewMatrix();
  57134. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57135. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57136. scene.clipPlane = _this.mirrorPlane;
  57137. scene.getEngine().cullBackFaces = false;
  57138. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57139. });
  57140. _this.onAfterRenderObservable.add(function () {
  57141. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  57142. scene.getEngine().cullBackFaces = true;
  57143. scene._mirroredCameraPosition = null;
  57144. delete scene.clipPlane;
  57145. });
  57146. return _this;
  57147. }
  57148. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  57149. get: function () {
  57150. return this._blurRatio;
  57151. },
  57152. set: function (value) {
  57153. if (this._blurRatio === value) {
  57154. return;
  57155. }
  57156. this._blurRatio = value;
  57157. this._preparePostProcesses();
  57158. },
  57159. enumerable: true,
  57160. configurable: true
  57161. });
  57162. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  57163. set: function (value) {
  57164. this._adaptiveBlurKernel = value;
  57165. this._autoComputeBlurKernel();
  57166. },
  57167. enumerable: true,
  57168. configurable: true
  57169. });
  57170. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  57171. set: function (value) {
  57172. this.blurKernelX = value;
  57173. this.blurKernelY = value;
  57174. },
  57175. enumerable: true,
  57176. configurable: true
  57177. });
  57178. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57179. get: function () {
  57180. return this._blurKernelX;
  57181. },
  57182. set: function (value) {
  57183. if (this._blurKernelX === value) {
  57184. return;
  57185. }
  57186. this._blurKernelX = value;
  57187. this._preparePostProcesses();
  57188. },
  57189. enumerable: true,
  57190. configurable: true
  57191. });
  57192. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57193. get: function () {
  57194. return this._blurKernelY;
  57195. },
  57196. set: function (value) {
  57197. if (this._blurKernelY === value) {
  57198. return;
  57199. }
  57200. this._blurKernelY = value;
  57201. this._preparePostProcesses();
  57202. },
  57203. enumerable: true,
  57204. configurable: true
  57205. });
  57206. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57207. var engine = this.getScene().getEngine();
  57208. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57209. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57210. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57211. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57212. };
  57213. MirrorTexture.prototype._onRatioRescale = function () {
  57214. if (this._sizeRatio) {
  57215. this.resize(this._initialSizeParameter);
  57216. if (!this._adaptiveBlurKernel) {
  57217. this._preparePostProcesses();
  57218. }
  57219. }
  57220. if (this._adaptiveBlurKernel) {
  57221. this._autoComputeBlurKernel();
  57222. }
  57223. };
  57224. MirrorTexture.prototype._preparePostProcesses = function () {
  57225. this.clearPostProcesses(true);
  57226. if (this._blurKernelX && this._blurKernelY) {
  57227. var engine = this.getScene().getEngine();
  57228. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57229. 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);
  57230. this._blurX.autoClear = false;
  57231. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57232. this._blurX.inputTexture = this._texture;
  57233. }
  57234. else {
  57235. this._blurX.alwaysForcePOT = true;
  57236. }
  57237. 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);
  57238. this._blurY.autoClear = false;
  57239. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57240. this.addPostProcess(this._blurX);
  57241. this.addPostProcess(this._blurY);
  57242. }
  57243. else {
  57244. if (this._blurY) {
  57245. this.removePostProcess(this._blurY);
  57246. this._blurY.dispose();
  57247. this._blurY = null;
  57248. }
  57249. if (this._blurX) {
  57250. this.removePostProcess(this._blurX);
  57251. this._blurX.dispose();
  57252. this._blurX = null;
  57253. }
  57254. }
  57255. };
  57256. MirrorTexture.prototype.clone = function () {
  57257. var scene = this.getScene();
  57258. if (!scene) {
  57259. return this;
  57260. }
  57261. var textureSize = this.getSize();
  57262. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  57263. // Base texture
  57264. newTexture.hasAlpha = this.hasAlpha;
  57265. newTexture.level = this.level;
  57266. // Mirror Texture
  57267. newTexture.mirrorPlane = this.mirrorPlane.clone();
  57268. if (this.renderList) {
  57269. newTexture.renderList = this.renderList.slice(0);
  57270. }
  57271. return newTexture;
  57272. };
  57273. MirrorTexture.prototype.serialize = function () {
  57274. if (!this.name) {
  57275. return null;
  57276. }
  57277. var serializationObject = _super.prototype.serialize.call(this);
  57278. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  57279. return serializationObject;
  57280. };
  57281. return MirrorTexture;
  57282. }(BABYLON.RenderTargetTexture));
  57283. BABYLON.MirrorTexture = MirrorTexture;
  57284. })(BABYLON || (BABYLON = {}));
  57285. //# sourceMappingURL=babylon.mirrorTexture.js.map
  57286. var BABYLON;
  57287. (function (BABYLON) {
  57288. /**
  57289. * Creates a refraction texture used by refraction channel of the standard material.
  57290. * @param name the texture name
  57291. * @param size size of the underlying texture
  57292. * @param scene root scene
  57293. */
  57294. var RefractionTexture = /** @class */ (function (_super) {
  57295. __extends(RefractionTexture, _super);
  57296. function RefractionTexture(name, size, scene, generateMipMaps) {
  57297. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  57298. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  57299. _this.depth = 2.0;
  57300. _this.onBeforeRenderObservable.add(function () {
  57301. scene.clipPlane = _this.refractionPlane;
  57302. });
  57303. _this.onAfterRenderObservable.add(function () {
  57304. delete scene.clipPlane;
  57305. });
  57306. return _this;
  57307. }
  57308. RefractionTexture.prototype.clone = function () {
  57309. var scene = this.getScene();
  57310. if (!scene) {
  57311. return this;
  57312. }
  57313. var textureSize = this.getSize();
  57314. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  57315. // Base texture
  57316. newTexture.hasAlpha = this.hasAlpha;
  57317. newTexture.level = this.level;
  57318. // Refraction Texture
  57319. newTexture.refractionPlane = this.refractionPlane.clone();
  57320. if (this.renderList) {
  57321. newTexture.renderList = this.renderList.slice(0);
  57322. }
  57323. newTexture.depth = this.depth;
  57324. return newTexture;
  57325. };
  57326. RefractionTexture.prototype.serialize = function () {
  57327. if (!this.name) {
  57328. return null;
  57329. }
  57330. var serializationObject = _super.prototype.serialize.call(this);
  57331. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57332. serializationObject.depth = this.depth;
  57333. return serializationObject;
  57334. };
  57335. return RefractionTexture;
  57336. }(BABYLON.RenderTargetTexture));
  57337. BABYLON.RefractionTexture = RefractionTexture;
  57338. })(BABYLON || (BABYLON = {}));
  57339. //# sourceMappingURL=babylon.refractionTexture.js.map
  57340. var BABYLON;
  57341. (function (BABYLON) {
  57342. var DynamicTexture = /** @class */ (function (_super) {
  57343. __extends(DynamicTexture, _super);
  57344. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57345. if (scene === void 0) { scene = null; }
  57346. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57347. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57348. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57349. _this.name = name;
  57350. _this._engine = _this.getScene().getEngine();
  57351. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57352. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57353. _this._generateMipMaps = generateMipMaps;
  57354. if (options.getContext) {
  57355. _this._canvas = options;
  57356. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57357. }
  57358. else {
  57359. _this._canvas = document.createElement("canvas");
  57360. if (options.width) {
  57361. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57362. }
  57363. else {
  57364. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57365. }
  57366. }
  57367. var textureSize = _this.getSize();
  57368. _this._canvas.width = textureSize.width;
  57369. _this._canvas.height = textureSize.height;
  57370. _this._context = _this._canvas.getContext("2d");
  57371. return _this;
  57372. }
  57373. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57374. get: function () {
  57375. return true;
  57376. },
  57377. enumerable: true,
  57378. configurable: true
  57379. });
  57380. DynamicTexture.prototype._recreate = function (textureSize) {
  57381. this._canvas.width = textureSize.width;
  57382. this._canvas.height = textureSize.height;
  57383. this.releaseInternalTexture();
  57384. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57385. };
  57386. DynamicTexture.prototype.scale = function (ratio) {
  57387. var textureSize = this.getSize();
  57388. textureSize.width *= ratio;
  57389. textureSize.height *= ratio;
  57390. this._recreate(textureSize);
  57391. };
  57392. DynamicTexture.prototype.scaleTo = function (width, height) {
  57393. var textureSize = this.getSize();
  57394. textureSize.width = width;
  57395. textureSize.height = height;
  57396. this._recreate(textureSize);
  57397. };
  57398. DynamicTexture.prototype.getContext = function () {
  57399. return this._context;
  57400. };
  57401. DynamicTexture.prototype.clear = function () {
  57402. var size = this.getSize();
  57403. this._context.fillRect(0, 0, size.width, size.height);
  57404. };
  57405. DynamicTexture.prototype.update = function (invertY) {
  57406. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57407. };
  57408. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57409. if (update === void 0) { update = true; }
  57410. var size = this.getSize();
  57411. if (clearColor) {
  57412. this._context.fillStyle = clearColor;
  57413. this._context.fillRect(0, 0, size.width, size.height);
  57414. }
  57415. this._context.font = font;
  57416. if (x === null || x === undefined) {
  57417. var textSize = this._context.measureText(text);
  57418. x = (size.width - textSize.width) / 2;
  57419. }
  57420. if (y === null || y === undefined) {
  57421. var fontSize = parseInt((font.replace(/\D/g, '')));
  57422. ;
  57423. y = (size.height / 2) + (fontSize / 3.65);
  57424. }
  57425. this._context.fillStyle = color;
  57426. this._context.fillText(text, x, y);
  57427. if (update) {
  57428. this.update(invertY);
  57429. }
  57430. };
  57431. DynamicTexture.prototype.clone = function () {
  57432. var scene = this.getScene();
  57433. if (!scene) {
  57434. return this;
  57435. }
  57436. var textureSize = this.getSize();
  57437. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57438. // Base texture
  57439. newTexture.hasAlpha = this.hasAlpha;
  57440. newTexture.level = this.level;
  57441. // Dynamic Texture
  57442. newTexture.wrapU = this.wrapU;
  57443. newTexture.wrapV = this.wrapV;
  57444. return newTexture;
  57445. };
  57446. DynamicTexture.prototype._rebuild = function () {
  57447. this.update();
  57448. };
  57449. return DynamicTexture;
  57450. }(BABYLON.Texture));
  57451. BABYLON.DynamicTexture = DynamicTexture;
  57452. })(BABYLON || (BABYLON = {}));
  57453. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57454. var BABYLON;
  57455. (function (BABYLON) {
  57456. var VideoTexture = /** @class */ (function (_super) {
  57457. __extends(VideoTexture, _super);
  57458. /**
  57459. * Creates a video texture.
  57460. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57461. * @param {string | null} name optional name, will detect from video source, if not defined
  57462. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57463. * @param {BABYLON.Scene} scene is obviously the current scene.
  57464. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57465. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57466. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57467. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57468. */
  57469. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57470. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57471. if (invertY === void 0) { invertY = false; }
  57472. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57473. if (settings === void 0) { settings = {
  57474. autoPlay: true,
  57475. loop: true,
  57476. autoUpdateTexture: true,
  57477. }; }
  57478. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57479. _this._createInternalTexture = function () {
  57480. if (_this._texture != null) {
  57481. return;
  57482. }
  57483. if (!_this._engine.needPOTTextures ||
  57484. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57485. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57486. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57487. }
  57488. else {
  57489. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57490. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57491. _this._generateMipMaps = false;
  57492. }
  57493. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57494. _this._texture.isReady = true;
  57495. _this._updateInternalTexture();
  57496. };
  57497. _this.reset = function () {
  57498. if (_this._texture == null) {
  57499. return;
  57500. }
  57501. _this._texture.dispose();
  57502. _this._texture = null;
  57503. };
  57504. _this._updateInternalTexture = function (e) {
  57505. if (_this._texture == null || !_this._texture.isReady) {
  57506. return;
  57507. }
  57508. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57509. return;
  57510. }
  57511. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57512. };
  57513. _this._engine = _this.getScene().getEngine();
  57514. _this._generateMipMaps = generateMipMaps;
  57515. _this._samplingMode = samplingMode;
  57516. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57517. _this.name = name || _this._getName(src);
  57518. _this.video = _this._getVideo(src);
  57519. if (settings.autoPlay !== undefined) {
  57520. _this.video.autoplay = settings.autoPlay;
  57521. }
  57522. if (settings.loop !== undefined) {
  57523. _this.video.loop = settings.loop;
  57524. }
  57525. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57526. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57527. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57528. _this.video.addEventListener("emptied", _this.reset);
  57529. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57530. _this._createInternalTexture();
  57531. }
  57532. return _this;
  57533. }
  57534. VideoTexture.prototype._getName = function (src) {
  57535. if (src instanceof HTMLVideoElement) {
  57536. return src.currentSrc;
  57537. }
  57538. if (typeof src === "object") {
  57539. return src.toString();
  57540. }
  57541. return src;
  57542. };
  57543. ;
  57544. VideoTexture.prototype._getVideo = function (src) {
  57545. if (src instanceof HTMLVideoElement) {
  57546. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57547. return src;
  57548. }
  57549. var video = document.createElement("video");
  57550. if (typeof src === "string") {
  57551. BABYLON.Tools.SetCorsBehavior(src, video);
  57552. video.src = src;
  57553. }
  57554. else {
  57555. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57556. src.forEach(function (url) {
  57557. var source = document.createElement("source");
  57558. source.src = url;
  57559. video.appendChild(source);
  57560. });
  57561. }
  57562. return video;
  57563. };
  57564. ;
  57565. /**
  57566. * Internal method to initiate `update`.
  57567. */
  57568. VideoTexture.prototype._rebuild = function () {
  57569. this.update();
  57570. };
  57571. /**
  57572. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57573. */
  57574. VideoTexture.prototype.update = function () {
  57575. if (!this.autoUpdateTexture) {
  57576. // Expecting user to call `updateTexture` manually
  57577. return;
  57578. }
  57579. this.updateTexture(true);
  57580. };
  57581. /**
  57582. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  57583. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  57584. */
  57585. VideoTexture.prototype.updateTexture = function (isVisible) {
  57586. if (!isVisible) {
  57587. return;
  57588. }
  57589. if (this.video.paused) {
  57590. return;
  57591. }
  57592. this._updateInternalTexture();
  57593. };
  57594. /**
  57595. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  57596. * @param url New url.
  57597. */
  57598. VideoTexture.prototype.updateURL = function (url) {
  57599. this.video.src = url;
  57600. };
  57601. VideoTexture.prototype.dispose = function () {
  57602. _super.prototype.dispose.call(this);
  57603. this.video.removeEventListener("canplay", this._createInternalTexture);
  57604. this.video.removeEventListener("paused", this._updateInternalTexture);
  57605. this.video.removeEventListener("seeked", this._updateInternalTexture);
  57606. this.video.removeEventListener("emptied", this.reset);
  57607. };
  57608. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  57609. var video = document.createElement("video");
  57610. var constraintsDeviceId;
  57611. if (constraints && constraints.deviceId) {
  57612. constraintsDeviceId = {
  57613. exact: constraints.deviceId,
  57614. };
  57615. }
  57616. navigator.getUserMedia =
  57617. navigator.getUserMedia ||
  57618. navigator.webkitGetUserMedia ||
  57619. navigator.mozGetUserMedia ||
  57620. navigator.msGetUserMedia;
  57621. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  57622. if (navigator.getUserMedia) {
  57623. navigator.getUserMedia({
  57624. video: {
  57625. deviceId: constraintsDeviceId,
  57626. width: {
  57627. min: (constraints && constraints.minWidth) || 256,
  57628. max: (constraints && constraints.maxWidth) || 640,
  57629. },
  57630. height: {
  57631. min: (constraints && constraints.minHeight) || 256,
  57632. max: (constraints && constraints.maxHeight) || 480,
  57633. },
  57634. },
  57635. }, function (stream) {
  57636. if (video.mozSrcObject !== undefined) {
  57637. // hack for Firefox < 19
  57638. video.mozSrcObject = stream;
  57639. }
  57640. else {
  57641. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  57642. }
  57643. video.play();
  57644. if (onReady) {
  57645. onReady(new VideoTexture("video", video, scene, true, true));
  57646. }
  57647. }, function (e) {
  57648. BABYLON.Tools.Error(e.name);
  57649. });
  57650. }
  57651. };
  57652. return VideoTexture;
  57653. }(BABYLON.Texture));
  57654. BABYLON.VideoTexture = VideoTexture;
  57655. })(BABYLON || (BABYLON = {}));
  57656. //# sourceMappingURL=babylon.videoTexture.js.map
  57657. var BABYLON;
  57658. (function (BABYLON) {
  57659. var RawTexture = /** @class */ (function (_super) {
  57660. __extends(RawTexture, _super);
  57661. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  57662. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57663. if (invertY === void 0) { invertY = false; }
  57664. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57665. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57666. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57667. _this.format = format;
  57668. _this._engine = scene.getEngine();
  57669. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  57670. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57671. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57672. return _this;
  57673. }
  57674. RawTexture.prototype.update = function (data) {
  57675. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  57676. };
  57677. // Statics
  57678. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57679. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57680. if (invertY === void 0) { invertY = false; }
  57681. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57682. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  57683. };
  57684. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57685. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57686. if (invertY === void 0) { invertY = false; }
  57687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57688. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57689. };
  57690. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  57691. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57692. if (invertY === void 0) { invertY = false; }
  57693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57694. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  57695. };
  57696. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57697. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57698. if (invertY === void 0) { invertY = false; }
  57699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57700. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57701. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  57702. };
  57703. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  57704. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57705. if (invertY === void 0) { invertY = false; }
  57706. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57707. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57708. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  57709. };
  57710. return RawTexture;
  57711. }(BABYLON.Texture));
  57712. BABYLON.RawTexture = RawTexture;
  57713. })(BABYLON || (BABYLON = {}));
  57714. //# sourceMappingURL=babylon.rawTexture.js.map
  57715. var BABYLON;
  57716. (function (BABYLON) {
  57717. /**
  57718. * PostProcess can be used to apply a shader to a texture after it has been rendered
  57719. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  57720. */
  57721. var PostProcess = /** @class */ (function () {
  57722. /**
  57723. * Creates a new instance of @see PostProcess
  57724. * @param name The name of the PostProcess.
  57725. * @param fragmentUrl The url of the fragment shader to be used.
  57726. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  57727. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  57728. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  57729. * @param camera The camera to apply the render pass to.
  57730. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  57731. * @param engine The engine which the post process will be applied. (default: current engine)
  57732. * @param reusable If the post process can be reused on the same frame. (default: false)
  57733. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  57734. * @param textureType Type of textures used when performing the post process. (default: 0)
  57735. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  57736. * @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
  57737. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  57738. */
  57739. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  57740. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  57741. if (defines === void 0) { defines = null; }
  57742. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57743. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  57744. if (blockCompilation === void 0) { blockCompilation = false; }
  57745. this.name = name;
  57746. /**
  57747. * Width of the texture to apply the post process on
  57748. */
  57749. this.width = -1;
  57750. /**
  57751. * Height of the texture to apply the post process on
  57752. */
  57753. this.height = -1;
  57754. /**
  57755. * If the buffer needs to be cleared before applying the post process. (default: true)
  57756. * Should be set to false if shader will overwrite all previous pixels.
  57757. */
  57758. this.autoClear = true;
  57759. /**
  57760. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  57761. */
  57762. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  57763. /**
  57764. * Animations to be used for the post processing
  57765. */
  57766. this.animations = new Array();
  57767. /**
  57768. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  57769. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  57770. */
  57771. this.enablePixelPerfectMode = false;
  57772. /**
  57773. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  57774. */
  57775. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  57776. /**
  57777. * Force textures to be a power of two (default: false)
  57778. */
  57779. this.alwaysForcePOT = false;
  57780. /**
  57781. * Number of sample textures (default: 1)
  57782. */
  57783. this.samples = 1;
  57784. /**
  57785. * Modify the scale of the post process to be the same as the viewport (default: false)
  57786. */
  57787. this.adaptScaleToCurrentViewport = false;
  57788. this._reusable = false;
  57789. /**
  57790. * Smart array of input and output textures for the post process.
  57791. */
  57792. this._textures = new BABYLON.SmartArray(2);
  57793. /**
  57794. * The index in _textures that corresponds to the output texture.
  57795. */
  57796. this._currentRenderTextureInd = 0;
  57797. this._scaleRatio = new BABYLON.Vector2(1, 1);
  57798. this._texelSize = BABYLON.Vector2.Zero();
  57799. // Events
  57800. /**
  57801. * An event triggered when the postprocess is activated.
  57802. * @type {BABYLON.Observable}
  57803. */
  57804. this.onActivateObservable = new BABYLON.Observable();
  57805. /**
  57806. * An event triggered when the postprocess changes its size.
  57807. * @type {BABYLON.Observable}
  57808. */
  57809. this.onSizeChangedObservable = new BABYLON.Observable();
  57810. /**
  57811. * An event triggered when the postprocess applies its effect.
  57812. * @type {BABYLON.Observable}
  57813. */
  57814. this.onApplyObservable = new BABYLON.Observable();
  57815. /**
  57816. * An event triggered before rendering the postprocess
  57817. * @type {BABYLON.Observable}
  57818. */
  57819. this.onBeforeRenderObservable = new BABYLON.Observable();
  57820. /**
  57821. * An event triggered after rendering the postprocess
  57822. * @type {BABYLON.Observable}
  57823. */
  57824. this.onAfterRenderObservable = new BABYLON.Observable();
  57825. if (camera != null) {
  57826. this._camera = camera;
  57827. this._scene = camera.getScene();
  57828. camera.attachPostProcess(this);
  57829. this._engine = this._scene.getEngine();
  57830. this._scene.postProcesses.push(this);
  57831. }
  57832. else if (engine) {
  57833. this._engine = engine;
  57834. this._engine.postProcesses.push(this);
  57835. }
  57836. this._options = options;
  57837. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  57838. this._reusable = reusable || false;
  57839. this._textureType = textureType;
  57840. this._samplers = samplers || [];
  57841. this._samplers.push("textureSampler");
  57842. this._fragmentUrl = fragmentUrl;
  57843. this._vertexUrl = vertexUrl;
  57844. this._parameters = parameters || [];
  57845. this._parameters.push("scale");
  57846. this._indexParameters = indexParameters;
  57847. if (!blockCompilation) {
  57848. this.updateEffect(defines);
  57849. }
  57850. }
  57851. Object.defineProperty(PostProcess.prototype, "onActivate", {
  57852. /**
  57853. * A function that is added to the onActivateObservable
  57854. */
  57855. set: function (callback) {
  57856. if (this._onActivateObserver) {
  57857. this.onActivateObservable.remove(this._onActivateObserver);
  57858. }
  57859. if (callback) {
  57860. this._onActivateObserver = this.onActivateObservable.add(callback);
  57861. }
  57862. },
  57863. enumerable: true,
  57864. configurable: true
  57865. });
  57866. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  57867. /**
  57868. * A function that is added to the onSizeChangedObservable
  57869. */
  57870. set: function (callback) {
  57871. if (this._onSizeChangedObserver) {
  57872. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  57873. }
  57874. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  57875. },
  57876. enumerable: true,
  57877. configurable: true
  57878. });
  57879. Object.defineProperty(PostProcess.prototype, "onApply", {
  57880. /**
  57881. * A function that is added to the onApplyObservable
  57882. */
  57883. set: function (callback) {
  57884. if (this._onApplyObserver) {
  57885. this.onApplyObservable.remove(this._onApplyObserver);
  57886. }
  57887. this._onApplyObserver = this.onApplyObservable.add(callback);
  57888. },
  57889. enumerable: true,
  57890. configurable: true
  57891. });
  57892. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  57893. /**
  57894. * A function that is added to the onBeforeRenderObservable
  57895. */
  57896. set: function (callback) {
  57897. if (this._onBeforeRenderObserver) {
  57898. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57899. }
  57900. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57901. },
  57902. enumerable: true,
  57903. configurable: true
  57904. });
  57905. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  57906. /**
  57907. * A function that is added to the onAfterRenderObservable
  57908. */
  57909. set: function (callback) {
  57910. if (this._onAfterRenderObserver) {
  57911. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57912. }
  57913. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57914. },
  57915. enumerable: true,
  57916. configurable: true
  57917. });
  57918. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  57919. /**
  57920. * 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
  57921. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  57922. */
  57923. get: function () {
  57924. return this._textures.data[this._currentRenderTextureInd];
  57925. },
  57926. set: function (value) {
  57927. this._forcedOutputTexture = value;
  57928. },
  57929. enumerable: true,
  57930. configurable: true
  57931. });
  57932. /**
  57933. * Gets the camera which post process is applied to.
  57934. * @returns The camera the post process is applied to.
  57935. */
  57936. PostProcess.prototype.getCamera = function () {
  57937. return this._camera;
  57938. };
  57939. Object.defineProperty(PostProcess.prototype, "texelSize", {
  57940. /**
  57941. * Gets the texel size of the postprocess.
  57942. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  57943. */
  57944. get: function () {
  57945. if (this._shareOutputWithPostProcess) {
  57946. return this._shareOutputWithPostProcess.texelSize;
  57947. }
  57948. if (this._forcedOutputTexture) {
  57949. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  57950. }
  57951. return this._texelSize;
  57952. },
  57953. enumerable: true,
  57954. configurable: true
  57955. });
  57956. /**
  57957. * Gets the engine which this post process belongs to.
  57958. * @returns The engine the post process was enabled with.
  57959. */
  57960. PostProcess.prototype.getEngine = function () {
  57961. return this._engine;
  57962. };
  57963. /**
  57964. * The effect that is created when initializing the post process.
  57965. * @returns The created effect corrisponding the the postprocess.
  57966. */
  57967. PostProcess.prototype.getEffect = function () {
  57968. return this._effect;
  57969. };
  57970. /**
  57971. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  57972. * @param postProcess The post process to share the output with.
  57973. * @returns This post process.
  57974. */
  57975. PostProcess.prototype.shareOutputWith = function (postProcess) {
  57976. this._disposeTextures();
  57977. this._shareOutputWithPostProcess = postProcess;
  57978. return this;
  57979. };
  57980. /**
  57981. * Updates the effect with the current post process compile time values and recompiles the shader.
  57982. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  57983. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  57984. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  57985. * @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
  57986. * @param onCompiled Called when the shader has been compiled.
  57987. * @param onError Called if there is an error when compiling a shader.
  57988. */
  57989. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  57990. if (defines === void 0) { defines = null; }
  57991. if (uniforms === void 0) { uniforms = null; }
  57992. if (samplers === void 0) { samplers = null; }
  57993. 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);
  57994. };
  57995. /**
  57996. * The post process is reusable if it can be used multiple times within one frame.
  57997. * @returns If the post process is reusable
  57998. */
  57999. PostProcess.prototype.isReusable = function () {
  58000. return this._reusable;
  58001. };
  58002. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58003. PostProcess.prototype.markTextureDirty = function () {
  58004. this.width = -1;
  58005. };
  58006. /**
  58007. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58008. * 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.
  58009. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58010. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58011. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58012. */
  58013. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58014. var _this = this;
  58015. if (sourceTexture === void 0) { sourceTexture = null; }
  58016. camera = camera || this._camera;
  58017. var scene = camera.getScene();
  58018. var engine = scene.getEngine();
  58019. var maxSize = engine.getCaps().maxTextureSize;
  58020. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58021. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58022. var desiredWidth = (this._options.width || requiredWidth);
  58023. var desiredHeight = this._options.height || requiredHeight;
  58024. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58025. if (this.adaptScaleToCurrentViewport) {
  58026. var currentViewport = engine.currentViewport;
  58027. if (currentViewport) {
  58028. desiredWidth *= currentViewport.width;
  58029. desiredHeight *= currentViewport.height;
  58030. }
  58031. }
  58032. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  58033. if (!this._options.width) {
  58034. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  58035. }
  58036. if (!this._options.height) {
  58037. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58038. }
  58039. }
  58040. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58041. if (this._textures.length > 0) {
  58042. for (var i = 0; i < this._textures.length; i++) {
  58043. this._engine._releaseTexture(this._textures.data[i]);
  58044. }
  58045. this._textures.reset();
  58046. }
  58047. this.width = desiredWidth;
  58048. this.height = desiredHeight;
  58049. var textureSize = { width: this.width, height: this.height };
  58050. var textureOptions = {
  58051. generateMipMaps: false,
  58052. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58053. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58054. samplingMode: this.renderTargetSamplingMode,
  58055. type: this._textureType
  58056. };
  58057. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58058. if (this._reusable) {
  58059. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58060. }
  58061. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58062. this.onSizeChangedObservable.notifyObservers(this);
  58063. }
  58064. this._textures.forEach(function (texture) {
  58065. if (texture.samples !== _this.samples) {
  58066. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58067. }
  58068. });
  58069. }
  58070. var target;
  58071. if (this._shareOutputWithPostProcess) {
  58072. target = this._shareOutputWithPostProcess.inputTexture;
  58073. }
  58074. else if (this._forcedOutputTexture) {
  58075. target = this._forcedOutputTexture;
  58076. this.width = this._forcedOutputTexture.width;
  58077. this.height = this._forcedOutputTexture.height;
  58078. }
  58079. else {
  58080. target = this.inputTexture;
  58081. }
  58082. // Bind the input of this post process to be used as the output of the previous post process.
  58083. if (this.enablePixelPerfectMode) {
  58084. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58085. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  58086. }
  58087. else {
  58088. this._scaleRatio.copyFromFloats(1, 1);
  58089. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  58090. }
  58091. this.onActivateObservable.notifyObservers(camera);
  58092. // Clear
  58093. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  58094. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  58095. }
  58096. if (this._reusable) {
  58097. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  58098. }
  58099. };
  58100. Object.defineProperty(PostProcess.prototype, "isSupported", {
  58101. /**
  58102. * If the post process is supported.
  58103. */
  58104. get: function () {
  58105. return this._effect.isSupported;
  58106. },
  58107. enumerable: true,
  58108. configurable: true
  58109. });
  58110. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  58111. /**
  58112. * The aspect ratio of the output texture.
  58113. */
  58114. get: function () {
  58115. if (this._shareOutputWithPostProcess) {
  58116. return this._shareOutputWithPostProcess.aspectRatio;
  58117. }
  58118. if (this._forcedOutputTexture) {
  58119. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  58120. }
  58121. return this.width / this.height;
  58122. },
  58123. enumerable: true,
  58124. configurable: true
  58125. });
  58126. /**
  58127. * Get a value indicating if the post-process is ready to be used
  58128. * @returns true if the post-process is ready (shader is compiled)
  58129. */
  58130. PostProcess.prototype.isReady = function () {
  58131. return this._effect && this._effect.isReady();
  58132. };
  58133. /**
  58134. * Binds all textures and uniforms to the shader, this will be run on every pass.
  58135. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  58136. */
  58137. PostProcess.prototype.apply = function () {
  58138. // Check
  58139. if (!this._effect || !this._effect.isReady())
  58140. return null;
  58141. // States
  58142. this._engine.enableEffect(this._effect);
  58143. this._engine.setState(false);
  58144. this._engine.setDepthBuffer(false);
  58145. this._engine.setDepthWrite(false);
  58146. // Alpha
  58147. this._engine.setAlphaMode(this.alphaMode);
  58148. if (this.alphaConstants) {
  58149. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  58150. }
  58151. // Bind the output texture of the preivous post process as the input to this post process.
  58152. var source;
  58153. if (this._shareOutputWithPostProcess) {
  58154. source = this._shareOutputWithPostProcess.inputTexture;
  58155. }
  58156. else if (this._forcedOutputTexture) {
  58157. source = this._forcedOutputTexture;
  58158. }
  58159. else {
  58160. source = this.inputTexture;
  58161. }
  58162. this._effect._bindTexture("textureSampler", source);
  58163. // Parameters
  58164. this._effect.setVector2("scale", this._scaleRatio);
  58165. this.onApplyObservable.notifyObservers(this._effect);
  58166. return this._effect;
  58167. };
  58168. PostProcess.prototype._disposeTextures = function () {
  58169. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  58170. return;
  58171. }
  58172. if (this._textures.length > 0) {
  58173. for (var i = 0; i < this._textures.length; i++) {
  58174. this._engine._releaseTexture(this._textures.data[i]);
  58175. }
  58176. }
  58177. this._textures.dispose();
  58178. };
  58179. /**
  58180. * Disposes the post process.
  58181. * @param camera The camera to dispose the post process on.
  58182. */
  58183. PostProcess.prototype.dispose = function (camera) {
  58184. camera = camera || this._camera;
  58185. this._disposeTextures();
  58186. if (this._scene) {
  58187. var index_1 = this._scene.postProcesses.indexOf(this);
  58188. if (index_1 !== -1) {
  58189. this._scene.postProcesses.splice(index_1, 1);
  58190. }
  58191. }
  58192. else {
  58193. var index_2 = this._engine.postProcesses.indexOf(this);
  58194. if (index_2 !== -1) {
  58195. this._engine.postProcesses.splice(index_2, 1);
  58196. }
  58197. }
  58198. if (!camera) {
  58199. return;
  58200. }
  58201. camera.detachPostProcess(this);
  58202. var index = camera._postProcesses.indexOf(this);
  58203. if (index === 0 && camera._postProcesses.length > 0) {
  58204. this._camera._postProcesses[0].markTextureDirty();
  58205. }
  58206. this.onActivateObservable.clear();
  58207. this.onAfterRenderObservable.clear();
  58208. this.onApplyObservable.clear();
  58209. this.onBeforeRenderObservable.clear();
  58210. this.onSizeChangedObservable.clear();
  58211. };
  58212. return PostProcess;
  58213. }());
  58214. BABYLON.PostProcess = PostProcess;
  58215. })(BABYLON || (BABYLON = {}));
  58216. //# sourceMappingURL=babylon.postProcess.js.map
  58217. var BABYLON;
  58218. (function (BABYLON) {
  58219. var PassPostProcess = /** @class */ (function (_super) {
  58220. __extends(PassPostProcess, _super);
  58221. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58222. if (camera === void 0) { camera = null; }
  58223. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58224. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  58225. }
  58226. return PassPostProcess;
  58227. }(BABYLON.PostProcess));
  58228. BABYLON.PassPostProcess = PassPostProcess;
  58229. })(BABYLON || (BABYLON = {}));
  58230. //# sourceMappingURL=babylon.passPostProcess.js.map
  58231. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58232. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58233. s = arguments[i];
  58234. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58235. t[p] = s[p];
  58236. }
  58237. return t;
  58238. };
  58239. var BABYLON;
  58240. (function (BABYLON) {
  58241. /**
  58242. * Default implementation of @see IShadowGenerator.
  58243. * This is the main object responsible of generating shadows in the framework.
  58244. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58245. */
  58246. var ShadowGenerator = /** @class */ (function () {
  58247. /**
  58248. * Creates a ShadowGenerator object.
  58249. * A ShadowGenerator is the required tool to use the shadows.
  58250. * Each light casting shadows needs to use its own ShadowGenerator.
  58251. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58252. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58253. * @param light The light object generating the shadows.
  58254. * @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.
  58255. */
  58256. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  58257. this._bias = 0.00005;
  58258. this._blurBoxOffset = 1;
  58259. this._blurScale = 2;
  58260. this._blurKernel = 1;
  58261. this._useKernelBlur = false;
  58262. this._filter = ShadowGenerator.FILTER_NONE;
  58263. this._darkness = 0;
  58264. this._transparencyShadow = false;
  58265. /**
  58266. * Controls the extent to which the shadows fade out at the edge of the frustum
  58267. * Used only by directionals and spots
  58268. */
  58269. this.frustumEdgeFalloff = 0;
  58270. /**
  58271. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  58272. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  58273. * It might on the other hand introduce peter panning.
  58274. */
  58275. this.forceBackFacesOnly = false;
  58276. this._lightDirection = BABYLON.Vector3.Zero();
  58277. this._viewMatrix = BABYLON.Matrix.Zero();
  58278. this._projectionMatrix = BABYLON.Matrix.Zero();
  58279. this._transformMatrix = BABYLON.Matrix.Zero();
  58280. this._currentFaceIndex = 0;
  58281. this._currentFaceIndexCache = 0;
  58282. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  58283. this._mapSize = mapSize;
  58284. this._light = light;
  58285. this._scene = light.getScene();
  58286. light._shadowGenerator = this;
  58287. // Texture type fallback from float to int if not supported.
  58288. var caps = this._scene.getEngine().getCaps();
  58289. if (!useFullFloatFirst) {
  58290. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58291. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58292. }
  58293. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58294. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58295. }
  58296. else {
  58297. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58298. }
  58299. }
  58300. else {
  58301. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58302. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58303. }
  58304. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58305. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58306. }
  58307. else {
  58308. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58309. }
  58310. }
  58311. this._initializeGenerator();
  58312. }
  58313. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  58314. /**
  58315. * Shadow generator mode None: no filtering applied.
  58316. */
  58317. get: function () {
  58318. return ShadowGenerator._FILTER_NONE;
  58319. },
  58320. enumerable: true,
  58321. configurable: true
  58322. });
  58323. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58324. /**
  58325. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58326. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58327. */
  58328. get: function () {
  58329. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58330. },
  58331. enumerable: true,
  58332. configurable: true
  58333. });
  58334. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58335. /**
  58336. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58337. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58338. */
  58339. get: function () {
  58340. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58341. },
  58342. enumerable: true,
  58343. configurable: true
  58344. });
  58345. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58346. /**
  58347. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58348. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58349. */
  58350. get: function () {
  58351. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58352. },
  58353. enumerable: true,
  58354. configurable: true
  58355. });
  58356. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58357. /**
  58358. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58359. * edge artifacts on steep falloff.
  58360. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58361. */
  58362. get: function () {
  58363. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58364. },
  58365. enumerable: true,
  58366. configurable: true
  58367. });
  58368. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58369. /**
  58370. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58371. * edge artifacts on steep falloff.
  58372. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58373. */
  58374. get: function () {
  58375. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58376. },
  58377. enumerable: true,
  58378. configurable: true
  58379. });
  58380. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58381. /**
  58382. * Gets the bias: offset applied on the depth preventing acnea.
  58383. */
  58384. get: function () {
  58385. return this._bias;
  58386. },
  58387. /**
  58388. * Sets the bias: offset applied on the depth preventing acnea.
  58389. */
  58390. set: function (bias) {
  58391. this._bias = bias;
  58392. },
  58393. enumerable: true,
  58394. configurable: true
  58395. });
  58396. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58397. /**
  58398. * Gets the blur box offset: offset applied during the blur pass.
  58399. * Only usefull if useKernelBlur = false
  58400. */
  58401. get: function () {
  58402. return this._blurBoxOffset;
  58403. },
  58404. /**
  58405. * Sets the blur box offset: offset applied during the blur pass.
  58406. * Only usefull if useKernelBlur = false
  58407. */
  58408. set: function (value) {
  58409. if (this._blurBoxOffset === value) {
  58410. return;
  58411. }
  58412. this._blurBoxOffset = value;
  58413. this._disposeBlurPostProcesses();
  58414. },
  58415. enumerable: true,
  58416. configurable: true
  58417. });
  58418. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58419. /**
  58420. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58421. * 2 means half of the size.
  58422. */
  58423. get: function () {
  58424. return this._blurScale;
  58425. },
  58426. /**
  58427. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58428. * 2 means half of the size.
  58429. */
  58430. set: function (value) {
  58431. if (this._blurScale === value) {
  58432. return;
  58433. }
  58434. this._blurScale = value;
  58435. this._disposeBlurPostProcesses();
  58436. },
  58437. enumerable: true,
  58438. configurable: true
  58439. });
  58440. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58441. /**
  58442. * Gets the blur kernel: kernel size of the blur pass.
  58443. * Only usefull if useKernelBlur = true
  58444. */
  58445. get: function () {
  58446. return this._blurKernel;
  58447. },
  58448. /**
  58449. * Sets the blur kernel: kernel size of the blur pass.
  58450. * Only usefull if useKernelBlur = true
  58451. */
  58452. set: function (value) {
  58453. if (this._blurKernel === value) {
  58454. return;
  58455. }
  58456. this._blurKernel = value;
  58457. this._disposeBlurPostProcesses();
  58458. },
  58459. enumerable: true,
  58460. configurable: true
  58461. });
  58462. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58463. /**
  58464. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58465. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58466. */
  58467. get: function () {
  58468. return this._useKernelBlur;
  58469. },
  58470. /**
  58471. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58472. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58473. */
  58474. set: function (value) {
  58475. if (this._useKernelBlur === value) {
  58476. return;
  58477. }
  58478. this._useKernelBlur = value;
  58479. this._disposeBlurPostProcesses();
  58480. },
  58481. enumerable: true,
  58482. configurable: true
  58483. });
  58484. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58485. /**
  58486. * Gets the depth scale used in ESM mode.
  58487. */
  58488. get: function () {
  58489. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58490. },
  58491. /**
  58492. * Sets the depth scale used in ESM mode.
  58493. * This can override the scale stored on the light.
  58494. */
  58495. set: function (value) {
  58496. this._depthScale = value;
  58497. },
  58498. enumerable: true,
  58499. configurable: true
  58500. });
  58501. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58502. /**
  58503. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58504. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58505. */
  58506. get: function () {
  58507. return this._filter;
  58508. },
  58509. /**
  58510. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58511. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58512. */
  58513. set: function (value) {
  58514. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58515. if (this._light.needCube()) {
  58516. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58517. this.useExponentialShadowMap = true;
  58518. return;
  58519. }
  58520. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58521. this.useCloseExponentialShadowMap = true;
  58522. return;
  58523. }
  58524. }
  58525. if (this._filter === value) {
  58526. return;
  58527. }
  58528. this._filter = value;
  58529. this._disposeBlurPostProcesses();
  58530. this._applyFilterValues();
  58531. this._light._markMeshesAsLightDirty();
  58532. },
  58533. enumerable: true,
  58534. configurable: true
  58535. });
  58536. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58537. /**
  58538. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58539. */
  58540. get: function () {
  58541. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58542. },
  58543. /**
  58544. * Sets the current filter to Poisson Sampling aka PCF.
  58545. */
  58546. set: function (value) {
  58547. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58548. return;
  58549. }
  58550. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58551. },
  58552. enumerable: true,
  58553. configurable: true
  58554. });
  58555. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58556. /**
  58557. * Gets if the current filter is set to VSM.
  58558. * DEPRECATED. Should use useExponentialShadowMap instead.
  58559. */
  58560. get: function () {
  58561. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58562. return this.useExponentialShadowMap;
  58563. },
  58564. /**
  58565. * Sets the current filter is to VSM.
  58566. * DEPRECATED. Should use useExponentialShadowMap instead.
  58567. */
  58568. set: function (value) {
  58569. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58570. this.useExponentialShadowMap = value;
  58571. },
  58572. enumerable: true,
  58573. configurable: true
  58574. });
  58575. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58576. /**
  58577. * Gets if the current filter is set to blurred VSM.
  58578. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58579. */
  58580. get: function () {
  58581. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58582. return this.useBlurExponentialShadowMap;
  58583. },
  58584. /**
  58585. * Sets the current filter is to blurred VSM.
  58586. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  58587. */
  58588. set: function (value) {
  58589. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  58590. this.useBlurExponentialShadowMap = value;
  58591. },
  58592. enumerable: true,
  58593. configurable: true
  58594. });
  58595. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  58596. /**
  58597. * Gets if the current filter is set to ESM.
  58598. */
  58599. get: function () {
  58600. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  58601. },
  58602. /**
  58603. * Sets the current filter is to ESM.
  58604. */
  58605. set: function (value) {
  58606. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  58607. return;
  58608. }
  58609. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58610. },
  58611. enumerable: true,
  58612. configurable: true
  58613. });
  58614. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  58615. /**
  58616. * Gets if the current filter is set to filtered ESM.
  58617. */
  58618. get: function () {
  58619. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  58620. },
  58621. /**
  58622. * Gets if the current filter is set to filtered ESM.
  58623. */
  58624. set: function (value) {
  58625. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58626. return;
  58627. }
  58628. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58629. },
  58630. enumerable: true,
  58631. configurable: true
  58632. });
  58633. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  58634. /**
  58635. * Gets if the current filter is set to "close ESM" (using the inverse of the
  58636. * exponential to prevent steep falloff artifacts).
  58637. */
  58638. get: function () {
  58639. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58640. },
  58641. /**
  58642. * Sets the current filter to "close ESM" (using the inverse of the
  58643. * exponential to prevent steep falloff artifacts).
  58644. */
  58645. set: function (value) {
  58646. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  58647. return;
  58648. }
  58649. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58650. },
  58651. enumerable: true,
  58652. configurable: true
  58653. });
  58654. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  58655. /**
  58656. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  58657. * exponential to prevent steep falloff artifacts).
  58658. */
  58659. get: function () {
  58660. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58661. },
  58662. /**
  58663. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  58664. * exponential to prevent steep falloff artifacts).
  58665. */
  58666. set: function (value) {
  58667. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58668. return;
  58669. }
  58670. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  58671. },
  58672. enumerable: true,
  58673. configurable: true
  58674. });
  58675. /**
  58676. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  58677. * 0 means strongest and 1 would means no shadow.
  58678. * @returns the darkness.
  58679. */
  58680. ShadowGenerator.prototype.getDarkness = function () {
  58681. return this._darkness;
  58682. };
  58683. /**
  58684. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  58685. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  58686. * @returns the shadow generator allowing fluent coding.
  58687. */
  58688. ShadowGenerator.prototype.setDarkness = function (darkness) {
  58689. if (darkness >= 1.0)
  58690. this._darkness = 1.0;
  58691. else if (darkness <= 0.0)
  58692. this._darkness = 0.0;
  58693. else
  58694. this._darkness = darkness;
  58695. return this;
  58696. };
  58697. /**
  58698. * Sets the ability to have transparent shadow (boolean).
  58699. * @param transparent True if transparent else False
  58700. * @returns the shadow generator allowing fluent coding
  58701. */
  58702. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  58703. this._transparencyShadow = transparent;
  58704. return this;
  58705. };
  58706. /**
  58707. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  58708. * @returns The render target texture if present otherwise, null
  58709. */
  58710. ShadowGenerator.prototype.getShadowMap = function () {
  58711. return this._shadowMap;
  58712. };
  58713. /**
  58714. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  58715. * @returns The render target texture if the shadow map is present otherwise, null
  58716. */
  58717. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  58718. if (this._shadowMap2) {
  58719. return this._shadowMap2;
  58720. }
  58721. return this._shadowMap;
  58722. };
  58723. /**
  58724. * Helper function to add a mesh and its descendants to the list of shadow casters.
  58725. * @param mesh Mesh to add
  58726. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  58727. * @returns the Shadow Generator itself
  58728. */
  58729. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  58730. if (includeDescendants === void 0) { includeDescendants = true; }
  58731. if (!this._shadowMap) {
  58732. return this;
  58733. }
  58734. if (!this._shadowMap.renderList) {
  58735. this._shadowMap.renderList = [];
  58736. }
  58737. this._shadowMap.renderList.push(mesh);
  58738. if (includeDescendants) {
  58739. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  58740. }
  58741. return this;
  58742. var _a;
  58743. };
  58744. /**
  58745. * Helper function to remove a mesh and its descendants from the list of shadow casters
  58746. * @param mesh Mesh to remove
  58747. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  58748. * @returns the Shadow Generator itself
  58749. */
  58750. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  58751. if (includeDescendants === void 0) { includeDescendants = true; }
  58752. if (!this._shadowMap || !this._shadowMap.renderList) {
  58753. return this;
  58754. }
  58755. var index = this._shadowMap.renderList.indexOf(mesh);
  58756. if (index !== -1) {
  58757. this._shadowMap.renderList.splice(index, 1);
  58758. }
  58759. if (includeDescendants) {
  58760. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  58761. var child = _a[_i];
  58762. this.removeShadowCaster(child);
  58763. }
  58764. }
  58765. return this;
  58766. };
  58767. /**
  58768. * Returns the associated light object.
  58769. * @returns the light generating the shadow
  58770. */
  58771. ShadowGenerator.prototype.getLight = function () {
  58772. return this._light;
  58773. };
  58774. ShadowGenerator.prototype._initializeGenerator = function () {
  58775. this._light._markMeshesAsLightDirty();
  58776. this._initializeShadowMap();
  58777. };
  58778. ShadowGenerator.prototype._initializeShadowMap = function () {
  58779. var _this = this;
  58780. // Render target
  58781. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  58782. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58783. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58784. this._shadowMap.anisotropicFilteringLevel = 1;
  58785. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58786. this._shadowMap.renderParticles = false;
  58787. this._shadowMap.ignoreCameraViewport = true;
  58788. // Record Face Index before render.
  58789. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  58790. _this._currentFaceIndex = faceIndex;
  58791. });
  58792. // Custom render function.
  58793. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  58794. // Blur if required afer render.
  58795. this._shadowMap.onAfterUnbindObservable.add(function () {
  58796. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  58797. return;
  58798. }
  58799. var shadowMap = _this.getShadowMapForRendering();
  58800. if (shadowMap) {
  58801. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  58802. }
  58803. });
  58804. // Clear according to the chosen filter.
  58805. this._shadowMap.onClearObservable.add(function (engine) {
  58806. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  58807. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  58808. }
  58809. else {
  58810. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  58811. }
  58812. });
  58813. };
  58814. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  58815. var _this = this;
  58816. var engine = this._scene.getEngine();
  58817. var targetSize = this._mapSize / this.blurScale;
  58818. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  58819. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  58820. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58821. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58822. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58823. }
  58824. if (this.useKernelBlur) {
  58825. 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);
  58826. this._kernelBlurXPostprocess.width = targetSize;
  58827. this._kernelBlurXPostprocess.height = targetSize;
  58828. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  58829. effect.setTexture("textureSampler", _this._shadowMap);
  58830. });
  58831. 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);
  58832. this._kernelBlurXPostprocess.autoClear = false;
  58833. this._kernelBlurYPostprocess.autoClear = false;
  58834. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  58835. this._kernelBlurXPostprocess.packedFloat = true;
  58836. this._kernelBlurYPostprocess.packedFloat = true;
  58837. }
  58838. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  58839. }
  58840. else {
  58841. 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);
  58842. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  58843. effect.setFloat2("screenSize", targetSize, targetSize);
  58844. effect.setTexture("textureSampler", _this._shadowMap);
  58845. });
  58846. this._boxBlurPostprocess.autoClear = false;
  58847. this._blurPostProcesses = [this._boxBlurPostprocess];
  58848. }
  58849. };
  58850. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  58851. var index;
  58852. var engine = this._scene.getEngine();
  58853. if (depthOnlySubMeshes.length) {
  58854. engine.setColorWrite(false);
  58855. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  58856. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  58857. }
  58858. engine.setColorWrite(true);
  58859. }
  58860. for (index = 0; index < opaqueSubMeshes.length; index++) {
  58861. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  58862. }
  58863. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  58864. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  58865. }
  58866. if (this._transparencyShadow) {
  58867. for (index = 0; index < transparentSubMeshes.length; index++) {
  58868. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  58869. }
  58870. }
  58871. };
  58872. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  58873. var _this = this;
  58874. var mesh = subMesh.getRenderingMesh();
  58875. var scene = this._scene;
  58876. var engine = scene.getEngine();
  58877. var material = subMesh.getMaterial();
  58878. if (!material) {
  58879. return;
  58880. }
  58881. // Culling
  58882. engine.setState(material.backFaceCulling);
  58883. // Managing instances
  58884. var batch = mesh._getInstancesRenderList(subMesh._id);
  58885. if (batch.mustReturn) {
  58886. return;
  58887. }
  58888. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  58889. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  58890. engine.enableEffect(this._effect);
  58891. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  58892. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  58893. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  58894. this._effect.setVector3("lightPosition", this.getLight().position);
  58895. if (scene.activeCamera) {
  58896. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  58897. }
  58898. // Alpha test
  58899. if (material && material.needAlphaTesting()) {
  58900. var alphaTexture = material.getAlphaTestTexture();
  58901. if (alphaTexture) {
  58902. this._effect.setTexture("diffuseSampler", alphaTexture);
  58903. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  58904. }
  58905. }
  58906. // Bones
  58907. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  58908. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  58909. }
  58910. if (this.forceBackFacesOnly) {
  58911. engine.setState(true, 0, false, true);
  58912. }
  58913. // Draw
  58914. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  58915. if (this.forceBackFacesOnly) {
  58916. engine.setState(true, 0, false, false);
  58917. }
  58918. }
  58919. else {
  58920. // Need to reset refresh rate of the shadowMap
  58921. if (this._shadowMap) {
  58922. this._shadowMap.resetRefreshCounter();
  58923. }
  58924. }
  58925. };
  58926. ShadowGenerator.prototype._applyFilterValues = function () {
  58927. if (!this._shadowMap) {
  58928. return;
  58929. }
  58930. if (this.filter === ShadowGenerator.FILTER_NONE) {
  58931. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  58932. }
  58933. else {
  58934. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  58935. }
  58936. };
  58937. /**
  58938. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58939. * @param onCompiled Callback triggered at the and of the effects compilation
  58940. * @param options Sets of optional options forcing the compilation with different modes
  58941. */
  58942. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  58943. var _this = this;
  58944. var localOptions = __assign({ useInstances: false }, options);
  58945. var shadowMap = this.getShadowMap();
  58946. if (!shadowMap) {
  58947. if (onCompiled) {
  58948. onCompiled(this);
  58949. }
  58950. return;
  58951. }
  58952. var renderList = shadowMap.renderList;
  58953. if (!renderList) {
  58954. if (onCompiled) {
  58955. onCompiled(this);
  58956. }
  58957. return;
  58958. }
  58959. var subMeshes = new Array();
  58960. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  58961. var mesh = renderList_1[_i];
  58962. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  58963. }
  58964. if (subMeshes.length === 0) {
  58965. if (onCompiled) {
  58966. onCompiled(this);
  58967. }
  58968. return;
  58969. }
  58970. var currentIndex = 0;
  58971. var checkReady = function () {
  58972. if (!_this._scene || !_this._scene.getEngine()) {
  58973. return;
  58974. }
  58975. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  58976. currentIndex++;
  58977. if (currentIndex >= subMeshes.length) {
  58978. if (onCompiled) {
  58979. onCompiled(_this);
  58980. }
  58981. return;
  58982. }
  58983. }
  58984. setTimeout(checkReady, 16);
  58985. };
  58986. checkReady();
  58987. };
  58988. /**
  58989. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  58990. * @param options Sets of optional options forcing the compilation with different modes
  58991. * @returns A promise that resolves when the compilation completes
  58992. */
  58993. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  58994. var _this = this;
  58995. return new Promise(function (resolve) {
  58996. _this.forceCompilation(function () {
  58997. resolve();
  58998. }, options);
  58999. });
  59000. };
  59001. /**
  59002. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59003. * @param subMesh The submesh we want to render in the shadow map
  59004. * @param useInstances Defines wether will draw in the map using instances
  59005. * @returns true if ready otherwise, false
  59006. */
  59007. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59008. var defines = [];
  59009. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59010. defines.push("#define FLOAT");
  59011. }
  59012. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59013. defines.push("#define ESM");
  59014. }
  59015. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59016. var mesh = subMesh.getMesh();
  59017. var material = subMesh.getMaterial();
  59018. // Alpha test
  59019. if (material && material.needAlphaTesting()) {
  59020. var alphaTexture = material.getAlphaTestTexture();
  59021. if (alphaTexture) {
  59022. defines.push("#define ALPHATEST");
  59023. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59024. attribs.push(BABYLON.VertexBuffer.UVKind);
  59025. defines.push("#define UV1");
  59026. }
  59027. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59028. if (alphaTexture.coordinatesIndex === 1) {
  59029. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59030. defines.push("#define UV2");
  59031. }
  59032. }
  59033. }
  59034. }
  59035. // Bones
  59036. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59037. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59038. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59039. if (mesh.numBoneInfluencers > 4) {
  59040. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59041. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59042. }
  59043. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59044. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59045. }
  59046. else {
  59047. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59048. }
  59049. // Instances
  59050. if (useInstances) {
  59051. defines.push("#define INSTANCES");
  59052. attribs.push("world0");
  59053. attribs.push("world1");
  59054. attribs.push("world2");
  59055. attribs.push("world3");
  59056. }
  59057. // Get correct effect
  59058. var join = defines.join("\n");
  59059. if (this._cachedDefines !== join) {
  59060. this._cachedDefines = join;
  59061. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59062. }
  59063. if (!this._effect.isReady()) {
  59064. return false;
  59065. }
  59066. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59067. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59068. this._initializeBlurRTTAndPostProcesses();
  59069. }
  59070. }
  59071. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59072. return false;
  59073. }
  59074. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59075. return false;
  59076. }
  59077. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59078. return false;
  59079. }
  59080. return true;
  59081. };
  59082. /**
  59083. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59084. * @param defines Defines of the material we want to update
  59085. * @param lightIndex Index of the light in the enabled light list of the material
  59086. */
  59087. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  59088. var scene = this._scene;
  59089. var light = this._light;
  59090. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59091. return;
  59092. }
  59093. defines["SHADOW" + lightIndex] = true;
  59094. if (this.usePoissonSampling) {
  59095. defines["SHADOWPCF" + lightIndex] = true;
  59096. }
  59097. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59098. defines["SHADOWESM" + lightIndex] = true;
  59099. }
  59100. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59101. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59102. }
  59103. if (light.needCube()) {
  59104. defines["SHADOWCUBE" + lightIndex] = true;
  59105. }
  59106. };
  59107. /**
  59108. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  59109. * defined in the generator but impacting the effect).
  59110. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  59111. * @param effect The effect we are binfing the information for
  59112. */
  59113. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  59114. var light = this._light;
  59115. var scene = this._scene;
  59116. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59117. return;
  59118. }
  59119. var camera = scene.activeCamera;
  59120. if (!camera) {
  59121. return;
  59122. }
  59123. var shadowMap = this.getShadowMap();
  59124. if (!shadowMap) {
  59125. return;
  59126. }
  59127. if (!light.needCube()) {
  59128. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  59129. }
  59130. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  59131. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  59132. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  59133. };
  59134. /**
  59135. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  59136. * (eq to shadow prjection matrix * light transform matrix)
  59137. * @returns The transform matrix used to create the shadow map
  59138. */
  59139. ShadowGenerator.prototype.getTransformMatrix = function () {
  59140. var scene = this._scene;
  59141. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  59142. return this._transformMatrix;
  59143. }
  59144. this._currentRenderID = scene.getRenderId();
  59145. this._currentFaceIndexCache = this._currentFaceIndex;
  59146. var lightPosition = this._light.position;
  59147. if (this._light.computeTransformedInformation()) {
  59148. lightPosition = this._light.transformedPosition;
  59149. }
  59150. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  59151. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  59152. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  59153. }
  59154. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  59155. this._cachedPosition = lightPosition.clone();
  59156. this._cachedDirection = this._lightDirection.clone();
  59157. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  59158. var shadowMap = this.getShadowMap();
  59159. if (shadowMap) {
  59160. var renderList = shadowMap.renderList;
  59161. if (renderList) {
  59162. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  59163. }
  59164. }
  59165. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  59166. }
  59167. return this._transformMatrix;
  59168. };
  59169. /**
  59170. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  59171. * Cube and 2D textures for instance.
  59172. */
  59173. ShadowGenerator.prototype.recreateShadowMap = function () {
  59174. var shadowMap = this._shadowMap;
  59175. if (!shadowMap) {
  59176. return;
  59177. }
  59178. // Track render list.
  59179. var renderList = shadowMap.renderList;
  59180. // Clean up existing data.
  59181. this._disposeRTTandPostProcesses();
  59182. // Reinitializes.
  59183. this._initializeGenerator();
  59184. // Reaffect the filter to ensure a correct fallback if necessary.
  59185. this.filter = this.filter;
  59186. // Reaffect the filter.
  59187. this._applyFilterValues();
  59188. // Reaffect Render List.
  59189. this._shadowMap.renderList = renderList;
  59190. };
  59191. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  59192. if (this._shadowMap2) {
  59193. this._shadowMap2.dispose();
  59194. this._shadowMap2 = null;
  59195. }
  59196. if (this._boxBlurPostprocess) {
  59197. this._boxBlurPostprocess.dispose();
  59198. this._boxBlurPostprocess = null;
  59199. }
  59200. if (this._kernelBlurXPostprocess) {
  59201. this._kernelBlurXPostprocess.dispose();
  59202. this._kernelBlurXPostprocess = null;
  59203. }
  59204. if (this._kernelBlurYPostprocess) {
  59205. this._kernelBlurYPostprocess.dispose();
  59206. this._kernelBlurYPostprocess = null;
  59207. }
  59208. this._blurPostProcesses = [];
  59209. };
  59210. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  59211. if (this._shadowMap) {
  59212. this._shadowMap.dispose();
  59213. this._shadowMap = null;
  59214. }
  59215. this._disposeBlurPostProcesses();
  59216. };
  59217. /**
  59218. * Disposes the ShadowGenerator.
  59219. * Returns nothing.
  59220. */
  59221. ShadowGenerator.prototype.dispose = function () {
  59222. this._disposeRTTandPostProcesses();
  59223. if (this._light) {
  59224. this._light._shadowGenerator = null;
  59225. this._light._markMeshesAsLightDirty();
  59226. }
  59227. };
  59228. /**
  59229. * Serializes the shadow generator setup to a json object.
  59230. * @returns The serialized JSON object
  59231. */
  59232. ShadowGenerator.prototype.serialize = function () {
  59233. var serializationObject = {};
  59234. var shadowMap = this.getShadowMap();
  59235. if (!shadowMap) {
  59236. return serializationObject;
  59237. }
  59238. serializationObject.lightId = this._light.id;
  59239. serializationObject.mapSize = shadowMap.getRenderSize();
  59240. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59241. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59242. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59243. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59244. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59245. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59246. serializationObject.depthScale = this.depthScale;
  59247. serializationObject.darkness = this.getDarkness();
  59248. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59249. serializationObject.blurKernel = this.blurKernel;
  59250. serializationObject.blurScale = this.blurScale;
  59251. serializationObject.useKernelBlur = this.useKernelBlur;
  59252. serializationObject.transparencyShadow = this._transparencyShadow;
  59253. serializationObject.renderList = [];
  59254. if (shadowMap.renderList) {
  59255. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  59256. var mesh = shadowMap.renderList[meshIndex];
  59257. serializationObject.renderList.push(mesh.id);
  59258. }
  59259. }
  59260. return serializationObject;
  59261. };
  59262. /**
  59263. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  59264. * @param parsedShadowGenerator The JSON object to parse
  59265. * @param scene The scene to create the shadow map for
  59266. * @returns The parsed shadow generator
  59267. */
  59268. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  59269. //casting to point light, as light is missing the position attr and typescript complains.
  59270. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  59271. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  59272. var shadowMap = shadowGenerator.getShadowMap();
  59273. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  59274. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  59275. meshes.forEach(function (mesh) {
  59276. if (!shadowMap) {
  59277. return;
  59278. }
  59279. if (!shadowMap.renderList) {
  59280. shadowMap.renderList = [];
  59281. }
  59282. shadowMap.renderList.push(mesh);
  59283. });
  59284. }
  59285. if (parsedShadowGenerator.usePoissonSampling) {
  59286. shadowGenerator.usePoissonSampling = true;
  59287. }
  59288. else if (parsedShadowGenerator.useExponentialShadowMap) {
  59289. shadowGenerator.useExponentialShadowMap = true;
  59290. }
  59291. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  59292. shadowGenerator.useBlurExponentialShadowMap = true;
  59293. }
  59294. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  59295. shadowGenerator.useCloseExponentialShadowMap = true;
  59296. }
  59297. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  59298. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  59299. }
  59300. else if (parsedShadowGenerator.useVarianceShadowMap) {
  59301. shadowGenerator.useExponentialShadowMap = true;
  59302. }
  59303. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  59304. shadowGenerator.useBlurExponentialShadowMap = true;
  59305. }
  59306. if (parsedShadowGenerator.depthScale) {
  59307. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  59308. }
  59309. if (parsedShadowGenerator.blurScale) {
  59310. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  59311. }
  59312. if (parsedShadowGenerator.blurBoxOffset) {
  59313. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  59314. }
  59315. if (parsedShadowGenerator.useKernelBlur) {
  59316. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  59317. }
  59318. if (parsedShadowGenerator.blurKernel) {
  59319. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59320. }
  59321. if (parsedShadowGenerator.bias !== undefined) {
  59322. shadowGenerator.bias = parsedShadowGenerator.bias;
  59323. }
  59324. if (parsedShadowGenerator.darkness) {
  59325. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59326. }
  59327. if (parsedShadowGenerator.transparencyShadow) {
  59328. shadowGenerator.setTransparencyShadow(true);
  59329. }
  59330. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59331. return shadowGenerator;
  59332. };
  59333. ShadowGenerator._FILTER_NONE = 0;
  59334. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59335. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59336. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59337. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59338. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59339. return ShadowGenerator;
  59340. }());
  59341. BABYLON.ShadowGenerator = ShadowGenerator;
  59342. })(BABYLON || (BABYLON = {}));
  59343. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59344. var BABYLON;
  59345. (function (BABYLON) {
  59346. var DefaultLoadingScreen = /** @class */ (function () {
  59347. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59348. if (_loadingText === void 0) { _loadingText = ""; }
  59349. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59350. var _this = this;
  59351. this._renderingCanvas = _renderingCanvas;
  59352. this._loadingText = _loadingText;
  59353. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59354. // Resize
  59355. this._resizeLoadingUI = function () {
  59356. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59357. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59358. if (!_this._loadingDiv) {
  59359. return;
  59360. }
  59361. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59362. _this._loadingDiv.style.left = canvasRect.left + "px";
  59363. _this._loadingDiv.style.top = canvasRect.top + "px";
  59364. _this._loadingDiv.style.width = canvasRect.width + "px";
  59365. _this._loadingDiv.style.height = canvasRect.height + "px";
  59366. };
  59367. }
  59368. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59369. if (this._loadingDiv) {
  59370. // Do not add a loading screen if there is already one
  59371. return;
  59372. }
  59373. this._loadingDiv = document.createElement("div");
  59374. this._loadingDiv.id = "babylonjsLoadingDiv";
  59375. this._loadingDiv.style.opacity = "0";
  59376. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59377. this._loadingDiv.style.pointerEvents = "none";
  59378. // Loading text
  59379. this._loadingTextDiv = document.createElement("div");
  59380. this._loadingTextDiv.style.position = "absolute";
  59381. this._loadingTextDiv.style.left = "0";
  59382. this._loadingTextDiv.style.top = "50%";
  59383. this._loadingTextDiv.style.marginTop = "80px";
  59384. this._loadingTextDiv.style.width = "100%";
  59385. this._loadingTextDiv.style.height = "20px";
  59386. this._loadingTextDiv.style.fontFamily = "Arial";
  59387. this._loadingTextDiv.style.fontSize = "14px";
  59388. this._loadingTextDiv.style.color = "white";
  59389. this._loadingTextDiv.style.textAlign = "center";
  59390. this._loadingTextDiv.innerHTML = "Loading";
  59391. this._loadingDiv.appendChild(this._loadingTextDiv);
  59392. //set the predefined text
  59393. this._loadingTextDiv.innerHTML = this._loadingText;
  59394. // Generating keyframes
  59395. var style = document.createElement('style');
  59396. style.type = 'text/css';
  59397. 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 }";
  59398. style.innerHTML = keyFrames;
  59399. document.getElementsByTagName('head')[0].appendChild(style);
  59400. // Loading img
  59401. var imgBack = new Image();
  59402. 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";
  59403. imgBack.style.position = "absolute";
  59404. imgBack.style.left = "50%";
  59405. imgBack.style.top = "50%";
  59406. imgBack.style.marginLeft = "-60px";
  59407. imgBack.style.marginTop = "-60px";
  59408. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59409. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59410. imgBack.style.transformOrigin = "50% 50%";
  59411. imgBack.style.webkitTransformOrigin = "50% 50%";
  59412. this._loadingDiv.appendChild(imgBack);
  59413. this._resizeLoadingUI();
  59414. window.addEventListener("resize", this._resizeLoadingUI);
  59415. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59416. document.body.appendChild(this._loadingDiv);
  59417. this._loadingDiv.style.opacity = "1";
  59418. };
  59419. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59420. var _this = this;
  59421. if (!this._loadingDiv) {
  59422. return;
  59423. }
  59424. var onTransitionEnd = function () {
  59425. if (!_this._loadingDiv) {
  59426. return;
  59427. }
  59428. document.body.removeChild(_this._loadingDiv);
  59429. window.removeEventListener("resize", _this._resizeLoadingUI);
  59430. _this._loadingDiv = null;
  59431. };
  59432. this._loadingDiv.style.opacity = "0";
  59433. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59434. };
  59435. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59436. set: function (text) {
  59437. this._loadingText = text;
  59438. if (this._loadingTextDiv) {
  59439. this._loadingTextDiv.innerHTML = this._loadingText;
  59440. }
  59441. },
  59442. enumerable: true,
  59443. configurable: true
  59444. });
  59445. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59446. get: function () {
  59447. return this._loadingDivBackgroundColor;
  59448. },
  59449. set: function (color) {
  59450. this._loadingDivBackgroundColor = color;
  59451. if (!this._loadingDiv) {
  59452. return;
  59453. }
  59454. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59455. },
  59456. enumerable: true,
  59457. configurable: true
  59458. });
  59459. return DefaultLoadingScreen;
  59460. }());
  59461. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59462. })(BABYLON || (BABYLON = {}));
  59463. //# sourceMappingURL=babylon.loadingScreen.js.map
  59464. var BABYLON;
  59465. (function (BABYLON) {
  59466. var SceneLoaderProgressEvent = /** @class */ (function () {
  59467. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59468. this.lengthComputable = lengthComputable;
  59469. this.loaded = loaded;
  59470. this.total = total;
  59471. }
  59472. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59473. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59474. };
  59475. return SceneLoaderProgressEvent;
  59476. }());
  59477. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59478. var SceneLoader = /** @class */ (function () {
  59479. function SceneLoader() {
  59480. }
  59481. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59482. get: function () {
  59483. return 0;
  59484. },
  59485. enumerable: true,
  59486. configurable: true
  59487. });
  59488. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59489. get: function () {
  59490. return 1;
  59491. },
  59492. enumerable: true,
  59493. configurable: true
  59494. });
  59495. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59496. get: function () {
  59497. return 2;
  59498. },
  59499. enumerable: true,
  59500. configurable: true
  59501. });
  59502. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59503. get: function () {
  59504. return 3;
  59505. },
  59506. enumerable: true,
  59507. configurable: true
  59508. });
  59509. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59510. get: function () {
  59511. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59512. },
  59513. set: function (value) {
  59514. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59515. },
  59516. enumerable: true,
  59517. configurable: true
  59518. });
  59519. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59520. get: function () {
  59521. return SceneLoader._ShowLoadingScreen;
  59522. },
  59523. set: function (value) {
  59524. SceneLoader._ShowLoadingScreen = value;
  59525. },
  59526. enumerable: true,
  59527. configurable: true
  59528. });
  59529. Object.defineProperty(SceneLoader, "loggingLevel", {
  59530. get: function () {
  59531. return SceneLoader._loggingLevel;
  59532. },
  59533. set: function (value) {
  59534. SceneLoader._loggingLevel = value;
  59535. },
  59536. enumerable: true,
  59537. configurable: true
  59538. });
  59539. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59540. get: function () {
  59541. return SceneLoader._CleanBoneMatrixWeights;
  59542. },
  59543. set: function (value) {
  59544. SceneLoader._CleanBoneMatrixWeights = value;
  59545. },
  59546. enumerable: true,
  59547. configurable: true
  59548. });
  59549. SceneLoader._getDefaultPlugin = function () {
  59550. return SceneLoader._registeredPlugins[".babylon"];
  59551. };
  59552. SceneLoader._getPluginForExtension = function (extension) {
  59553. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59554. if (registeredPlugin) {
  59555. return registeredPlugin;
  59556. }
  59557. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59558. return SceneLoader._getDefaultPlugin();
  59559. };
  59560. SceneLoader._getPluginForDirectLoad = function (data) {
  59561. for (var extension in SceneLoader._registeredPlugins) {
  59562. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59563. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59564. return SceneLoader._registeredPlugins[extension];
  59565. }
  59566. }
  59567. return SceneLoader._getDefaultPlugin();
  59568. };
  59569. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59570. if (sceneFilename.name) {
  59571. sceneFilename = sceneFilename.name;
  59572. }
  59573. var queryStringPosition = sceneFilename.indexOf("?");
  59574. if (queryStringPosition !== -1) {
  59575. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59576. }
  59577. var dotPosition = sceneFilename.lastIndexOf(".");
  59578. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  59579. return SceneLoader._getPluginForExtension(extension);
  59580. };
  59581. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  59582. SceneLoader._getDirectLoad = function (sceneFilename) {
  59583. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  59584. return sceneFilename.substr(5);
  59585. }
  59586. return null;
  59587. };
  59588. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  59589. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  59590. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  59591. var plugin;
  59592. if (registeredPlugin.plugin.createPlugin) {
  59593. plugin = registeredPlugin.plugin.createPlugin();
  59594. }
  59595. else {
  59596. plugin = registeredPlugin.plugin;
  59597. }
  59598. var useArrayBuffer = registeredPlugin.isBinary;
  59599. var database;
  59600. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  59601. var dataCallback = function (data, responseURL) {
  59602. if (scene.isDisposed) {
  59603. onError("Scene has been disposed");
  59604. return;
  59605. }
  59606. scene.database = database;
  59607. onSuccess(plugin, data, responseURL);
  59608. };
  59609. var request = null;
  59610. var pluginDisposed = false;
  59611. var onDisposeObservable = plugin.onDisposeObservable;
  59612. if (onDisposeObservable) {
  59613. onDisposeObservable.add(function () {
  59614. pluginDisposed = true;
  59615. if (request) {
  59616. request.abort();
  59617. request = null;
  59618. }
  59619. onDispose();
  59620. });
  59621. }
  59622. var manifestChecked = function () {
  59623. if (pluginDisposed) {
  59624. return;
  59625. }
  59626. var url = rootUrl + sceneFilename;
  59627. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  59628. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  59629. } : undefined, database, useArrayBuffer, function (request, exception) {
  59630. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  59631. });
  59632. };
  59633. if (directLoad) {
  59634. dataCallback(directLoad);
  59635. return plugin;
  59636. }
  59637. if (rootUrl.indexOf("file:") === -1) {
  59638. if (scene.getEngine().enableOfflineSupport) {
  59639. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  59640. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  59641. }
  59642. else {
  59643. manifestChecked();
  59644. }
  59645. }
  59646. else {
  59647. var fileOrString = sceneFilename;
  59648. if (fileOrString.name) {
  59649. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  59650. }
  59651. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  59652. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  59653. }
  59654. else {
  59655. onError("Unable to find file named " + sceneFilename);
  59656. }
  59657. }
  59658. return plugin;
  59659. };
  59660. // Public functions
  59661. SceneLoader.GetPluginForExtension = function (extension) {
  59662. return SceneLoader._getPluginForExtension(extension).plugin;
  59663. };
  59664. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  59665. return !!SceneLoader._registeredPlugins[extension];
  59666. };
  59667. SceneLoader.RegisterPlugin = function (plugin) {
  59668. if (typeof plugin.extensions === "string") {
  59669. var extension = plugin.extensions;
  59670. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59671. plugin: plugin,
  59672. isBinary: false
  59673. };
  59674. }
  59675. else {
  59676. var extensions = plugin.extensions;
  59677. Object.keys(extensions).forEach(function (extension) {
  59678. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  59679. plugin: plugin,
  59680. isBinary: extensions[extension].isBinary
  59681. };
  59682. });
  59683. }
  59684. };
  59685. /**
  59686. * Import meshes into a scene
  59687. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59688. * @param rootUrl a string that defines the root url for scene and resources
  59689. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59690. * @param scene the instance of BABYLON.Scene to append to
  59691. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  59692. * @param onProgress a callback with a progress event for each file being loaded
  59693. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59694. * @param pluginExtension the extension used to determine the plugin
  59695. * @returns The loaded plugin
  59696. */
  59697. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59698. if (onSuccess === void 0) { onSuccess = null; }
  59699. if (onProgress === void 0) { onProgress = null; }
  59700. if (onError === void 0) { onError = null; }
  59701. if (pluginExtension === void 0) { pluginExtension = null; }
  59702. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59703. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59704. return null;
  59705. }
  59706. var loadingToken = {};
  59707. scene._addPendingData(loadingToken);
  59708. var disposeHandler = function () {
  59709. scene._removePendingData(loadingToken);
  59710. };
  59711. var errorHandler = function (message, exception) {
  59712. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  59713. if (onError) {
  59714. onError(scene, errorMessage, exception);
  59715. }
  59716. else {
  59717. BABYLON.Tools.Error(errorMessage);
  59718. // should the exception be thrown?
  59719. }
  59720. disposeHandler();
  59721. };
  59722. var progressHandler = onProgress ? function (event) {
  59723. try {
  59724. onProgress(event);
  59725. }
  59726. catch (e) {
  59727. errorHandler("Error in onProgress callback", e);
  59728. }
  59729. } : undefined;
  59730. var successHandler = function (meshes, particleSystems, skeletons) {
  59731. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  59732. if (onSuccess) {
  59733. try {
  59734. onSuccess(meshes, particleSystems, skeletons);
  59735. }
  59736. catch (e) {
  59737. errorHandler("Error in onSuccess callback", e);
  59738. }
  59739. }
  59740. scene._removePendingData(loadingToken);
  59741. };
  59742. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59743. if (plugin.rewriteRootURL) {
  59744. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  59745. }
  59746. if (sceneFilename === "") {
  59747. if (sceneFilename === "") {
  59748. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59749. }
  59750. }
  59751. if (plugin.importMesh) {
  59752. var syncedPlugin = plugin;
  59753. var meshes = new Array();
  59754. var particleSystems = new Array();
  59755. var skeletons = new Array();
  59756. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  59757. return;
  59758. }
  59759. scene.loadingPluginName = plugin.name;
  59760. successHandler(meshes, particleSystems, skeletons);
  59761. }
  59762. else {
  59763. var asyncedPlugin = plugin;
  59764. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  59765. scene.loadingPluginName = plugin.name;
  59766. successHandler(result.meshes, result.particleSystems, result.skeletons);
  59767. }).catch(function (error) {
  59768. errorHandler(error.message, error);
  59769. });
  59770. }
  59771. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59772. };
  59773. /**
  59774. * Import meshes into a scene
  59775. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  59776. * @param rootUrl a string that defines the root url for scene and resources
  59777. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59778. * @param scene the instance of BABYLON.Scene to append to
  59779. * @param onProgress a callback with a progress event for each file being loaded
  59780. * @param pluginExtension the extension used to determine the plugin
  59781. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  59782. */
  59783. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59784. if (onProgress === void 0) { onProgress = null; }
  59785. if (pluginExtension === void 0) { pluginExtension = null; }
  59786. return new Promise(function (resolve, reject) {
  59787. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  59788. resolve({
  59789. meshes: meshes,
  59790. particleSystems: particleSystems,
  59791. skeletons: skeletons
  59792. });
  59793. }, onProgress, function (scene, message, exception) {
  59794. reject(exception || new Error(message));
  59795. });
  59796. });
  59797. };
  59798. /**
  59799. * Load a scene
  59800. * @param rootUrl a string that defines the root url for scene and resources
  59801. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59802. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59803. * @param onSuccess a callback with the scene when import succeeds
  59804. * @param onProgress a callback with a progress event for each file being loaded
  59805. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59806. * @param pluginExtension the extension used to determine the plugin
  59807. * @returns The loaded plugin
  59808. */
  59809. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  59810. if (onSuccess === void 0) { onSuccess = null; }
  59811. if (onProgress === void 0) { onProgress = null; }
  59812. if (onError === void 0) { onError = null; }
  59813. if (pluginExtension === void 0) { pluginExtension = null; }
  59814. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  59815. };
  59816. /**
  59817. * Load a scene
  59818. * @param rootUrl a string that defines the root url for scene and resources
  59819. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59820. * @param engine is the instance of BABYLON.Engine to use to create the scene
  59821. * @param onProgress a callback with a progress event for each file being loaded
  59822. * @param pluginExtension the extension used to determine the plugin
  59823. * @returns The loaded scene
  59824. */
  59825. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  59826. if (onProgress === void 0) { onProgress = null; }
  59827. if (pluginExtension === void 0) { pluginExtension = null; }
  59828. return new Promise(function (resolve, reject) {
  59829. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  59830. resolve(scene);
  59831. }, onProgress, function (scene, message, exception) {
  59832. reject(exception || new Error(message));
  59833. }, pluginExtension);
  59834. });
  59835. };
  59836. /**
  59837. * Append a scene
  59838. * @param rootUrl a string that defines the root url for scene and resources
  59839. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59840. * @param scene is the instance of BABYLON.Scene to append to
  59841. * @param onSuccess a callback with the scene when import succeeds
  59842. * @param onProgress a callback with a progress event for each file being loaded
  59843. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59844. * @param pluginExtension the extension used to determine the plugin
  59845. * @returns The loaded plugin
  59846. */
  59847. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59848. if (onSuccess === void 0) { onSuccess = null; }
  59849. if (onProgress === void 0) { onProgress = null; }
  59850. if (onError === void 0) { onError = null; }
  59851. if (pluginExtension === void 0) { pluginExtension = null; }
  59852. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59853. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59854. return null;
  59855. }
  59856. if (SceneLoader.ShowLoadingScreen) {
  59857. scene.getEngine().displayLoadingUI();
  59858. }
  59859. var loadingToken = {};
  59860. scene._addPendingData(loadingToken);
  59861. var disposeHandler = function () {
  59862. scene._removePendingData(loadingToken);
  59863. scene.getEngine().hideLoadingUI();
  59864. };
  59865. var errorHandler = function (message, exception) {
  59866. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59867. if (onError) {
  59868. onError(scene, errorMessage, exception);
  59869. }
  59870. else {
  59871. BABYLON.Tools.Error(errorMessage);
  59872. // should the exception be thrown?
  59873. }
  59874. disposeHandler();
  59875. };
  59876. var progressHandler = onProgress ? function (event) {
  59877. try {
  59878. onProgress(event);
  59879. }
  59880. catch (e) {
  59881. errorHandler("Error in onProgress callback", e);
  59882. }
  59883. } : undefined;
  59884. var successHandler = function () {
  59885. if (onSuccess) {
  59886. try {
  59887. onSuccess(scene);
  59888. }
  59889. catch (e) {
  59890. errorHandler("Error in onSuccess callback", e);
  59891. }
  59892. }
  59893. scene._removePendingData(loadingToken);
  59894. };
  59895. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59896. if (sceneFilename === "") {
  59897. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  59898. }
  59899. if (plugin.load) {
  59900. var syncedPlugin = plugin;
  59901. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  59902. return;
  59903. }
  59904. scene.loadingPluginName = plugin.name;
  59905. successHandler();
  59906. }
  59907. else {
  59908. var asyncedPlugin = plugin;
  59909. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  59910. scene.loadingPluginName = plugin.name;
  59911. successHandler();
  59912. }).catch(function (error) {
  59913. errorHandler(error.message, error);
  59914. });
  59915. }
  59916. if (SceneLoader.ShowLoadingScreen) {
  59917. scene.executeWhenReady(function () {
  59918. scene.getEngine().hideLoadingUI();
  59919. });
  59920. }
  59921. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  59922. };
  59923. /**
  59924. * Append a scene
  59925. * @param rootUrl a string that defines the root url for scene and resources
  59926. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59927. * @param scene is the instance of BABYLON.Scene to append to
  59928. * @param onProgress a callback with a progress event for each file being loaded
  59929. * @param pluginExtension the extension used to determine the plugin
  59930. * @returns The given scene
  59931. */
  59932. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  59933. if (onProgress === void 0) { onProgress = null; }
  59934. if (pluginExtension === void 0) { pluginExtension = null; }
  59935. return new Promise(function (resolve, reject) {
  59936. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  59937. resolve(scene);
  59938. }, onProgress, function (scene, message, exception) {
  59939. reject(exception || new Error(message));
  59940. }, pluginExtension);
  59941. });
  59942. };
  59943. /**
  59944. * Load a scene into an asset container
  59945. * @param rootUrl a string that defines the root url for scene and resources
  59946. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  59947. * @param scene is the instance of BABYLON.Scene to append to
  59948. * @param onSuccess a callback with the scene when import succeeds
  59949. * @param onProgress a callback with a progress event for each file being loaded
  59950. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  59951. * @param pluginExtension the extension used to determine the plugin
  59952. * @returns The loaded plugin
  59953. */
  59954. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  59955. if (onSuccess === void 0) { onSuccess = null; }
  59956. if (onProgress === void 0) { onProgress = null; }
  59957. if (onError === void 0) { onError = null; }
  59958. if (pluginExtension === void 0) { pluginExtension = null; }
  59959. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  59960. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  59961. return null;
  59962. }
  59963. var loadingToken = {};
  59964. scene._addPendingData(loadingToken);
  59965. var disposeHandler = function () {
  59966. scene._removePendingData(loadingToken);
  59967. };
  59968. var errorHandler = function (message, exception) {
  59969. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  59970. if (onError) {
  59971. onError(scene, errorMessage, exception);
  59972. }
  59973. else {
  59974. BABYLON.Tools.Error(errorMessage);
  59975. // should the exception be thrown?
  59976. }
  59977. disposeHandler();
  59978. };
  59979. var progressHandler = onProgress ? function (event) {
  59980. try {
  59981. onProgress(event);
  59982. }
  59983. catch (e) {
  59984. errorHandler("Error in onProgress callback", e);
  59985. }
  59986. } : undefined;
  59987. var successHandler = function (assets) {
  59988. if (onSuccess) {
  59989. try {
  59990. onSuccess(assets);
  59991. }
  59992. catch (e) {
  59993. errorHandler("Error in onSuccess callback", e);
  59994. }
  59995. }
  59996. scene._removePendingData(loadingToken);
  59997. };
  59998. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  59999. if (plugin.loadAssetContainer) {
  60000. var syncedPlugin = plugin;
  60001. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60002. if (!assetContainer) {
  60003. return;
  60004. }
  60005. scene.loadingPluginName = plugin.name;
  60006. successHandler(assetContainer);
  60007. }
  60008. else if (plugin.loadAssetContainerAsync) {
  60009. var asyncedPlugin = plugin;
  60010. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60011. scene.loadingPluginName = plugin.name;
  60012. successHandler(assetContainer);
  60013. }).catch(function (error) {
  60014. errorHandler(error.message, error);
  60015. });
  60016. }
  60017. else {
  60018. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60019. }
  60020. if (SceneLoader.ShowLoadingScreen) {
  60021. scene.executeWhenReady(function () {
  60022. scene.getEngine().hideLoadingUI();
  60023. });
  60024. }
  60025. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60026. };
  60027. /**
  60028. * Load a scene into an asset container
  60029. * @param rootUrl a string that defines the root url for scene and resources
  60030. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60031. * @param scene is the instance of BABYLON.Scene to append to
  60032. * @param onProgress a callback with a progress event for each file being loaded
  60033. * @param pluginExtension the extension used to determine the plugin
  60034. * @returns The loaded asset container
  60035. */
  60036. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60037. if (onProgress === void 0) { onProgress = null; }
  60038. if (pluginExtension === void 0) { pluginExtension = null; }
  60039. return new Promise(function (resolve, reject) {
  60040. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60041. resolve(assetContainer);
  60042. }, onProgress, function (scene, message, exception) {
  60043. reject(exception || new Error(message));
  60044. }, pluginExtension);
  60045. });
  60046. };
  60047. // Flags
  60048. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60049. SceneLoader._ShowLoadingScreen = true;
  60050. SceneLoader._CleanBoneMatrixWeights = false;
  60051. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60052. // Members
  60053. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60054. SceneLoader._registeredPlugins = {};
  60055. return SceneLoader;
  60056. }());
  60057. BABYLON.SceneLoader = SceneLoader;
  60058. ;
  60059. })(BABYLON || (BABYLON = {}));
  60060. //# sourceMappingURL=babylon.sceneLoader.js.map
  60061. var BABYLON;
  60062. (function (BABYLON) {
  60063. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60064. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60065. var parsedMaterial = parsedData.materials[index];
  60066. if (parsedMaterial.id === id) {
  60067. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60068. }
  60069. }
  60070. return null;
  60071. };
  60072. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60073. for (var i in names) {
  60074. if (mesh.name === names[i]) {
  60075. hierarchyIds.push(mesh.id);
  60076. return true;
  60077. }
  60078. }
  60079. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60080. hierarchyIds.push(mesh.id);
  60081. return true;
  60082. }
  60083. return false;
  60084. };
  60085. var logOperation = function (operation, producer) {
  60086. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  60087. };
  60088. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  60089. if (addToScene === void 0) { addToScene = false; }
  60090. var container = new BABYLON.AssetContainer(scene);
  60091. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60092. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60093. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60094. // and avoid problems with multiple concurrent .babylon loads.
  60095. var log = "importScene has failed JSON parse";
  60096. try {
  60097. var parsedData = JSON.parse(data);
  60098. log = "";
  60099. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60100. var index;
  60101. var cache;
  60102. // Lights
  60103. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60104. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60105. var parsedLight = parsedData.lights[index];
  60106. var light = BABYLON.Light.Parse(parsedLight, scene);
  60107. if (light) {
  60108. container.lights.push(light);
  60109. log += (index === 0 ? "\n\tLights:" : "");
  60110. log += "\n\t\t" + light.toString(fullDetails);
  60111. }
  60112. }
  60113. }
  60114. // Animations
  60115. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  60116. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  60117. var parsedAnimation = parsedData.animations[index];
  60118. var animation = BABYLON.Animation.Parse(parsedAnimation);
  60119. scene.animations.push(animation);
  60120. container.animations.push(animation);
  60121. log += (index === 0 ? "\n\tAnimations:" : "");
  60122. log += "\n\t\t" + animation.toString(fullDetails);
  60123. }
  60124. }
  60125. // Materials
  60126. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  60127. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60128. var parsedMaterial = parsedData.materials[index];
  60129. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60130. container.materials.push(mat);
  60131. log += (index === 0 ? "\n\tMaterials:" : "");
  60132. log += "\n\t\t" + mat.toString(fullDetails);
  60133. }
  60134. }
  60135. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60136. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  60137. var parsedMultiMaterial = parsedData.multiMaterials[index];
  60138. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60139. container.multiMaterials.push(mmat);
  60140. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  60141. log += "\n\t\t" + mmat.toString(fullDetails);
  60142. }
  60143. }
  60144. // Morph targets
  60145. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  60146. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  60147. var managerData = _a[_i];
  60148. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  60149. }
  60150. }
  60151. // Skeletons
  60152. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60153. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  60154. var parsedSkeleton = parsedData.skeletons[index];
  60155. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60156. container.skeletons.push(skeleton);
  60157. log += (index === 0 ? "\n\tSkeletons:" : "");
  60158. log += "\n\t\t" + skeleton.toString(fullDetails);
  60159. }
  60160. }
  60161. // Geometries
  60162. var geometries = parsedData.geometries;
  60163. if (geometries !== undefined && geometries !== null) {
  60164. var addedGeometry = new Array();
  60165. // Boxes
  60166. var boxes = geometries.boxes;
  60167. if (boxes !== undefined && boxes !== null) {
  60168. for (index = 0, cache = boxes.length; index < cache; index++) {
  60169. var parsedBox = boxes[index];
  60170. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  60171. }
  60172. }
  60173. // Spheres
  60174. var spheres = geometries.spheres;
  60175. if (spheres !== undefined && spheres !== null) {
  60176. for (index = 0, cache = spheres.length; index < cache; index++) {
  60177. var parsedSphere = spheres[index];
  60178. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60179. }
  60180. }
  60181. // Cylinders
  60182. var cylinders = geometries.cylinders;
  60183. if (cylinders !== undefined && cylinders !== null) {
  60184. for (index = 0, cache = cylinders.length; index < cache; index++) {
  60185. var parsedCylinder = cylinders[index];
  60186. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  60187. }
  60188. }
  60189. // Toruses
  60190. var toruses = geometries.toruses;
  60191. if (toruses !== undefined && toruses !== null) {
  60192. for (index = 0, cache = toruses.length; index < cache; index++) {
  60193. var parsedTorus = toruses[index];
  60194. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  60195. }
  60196. }
  60197. // Grounds
  60198. var grounds = geometries.grounds;
  60199. if (grounds !== undefined && grounds !== null) {
  60200. for (index = 0, cache = grounds.length; index < cache; index++) {
  60201. var parsedGround = grounds[index];
  60202. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60203. }
  60204. }
  60205. // Planes
  60206. var planes = geometries.planes;
  60207. if (planes !== undefined && planes !== null) {
  60208. for (index = 0, cache = planes.length; index < cache; index++) {
  60209. var parsedPlane = planes[index];
  60210. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  60211. }
  60212. }
  60213. // TorusKnots
  60214. var torusKnots = geometries.torusKnots;
  60215. if (torusKnots !== undefined && torusKnots !== null) {
  60216. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  60217. var parsedTorusKnot = torusKnots[index];
  60218. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  60219. }
  60220. }
  60221. // VertexData
  60222. var vertexData = geometries.vertexData;
  60223. if (vertexData !== undefined && vertexData !== null) {
  60224. for (index = 0, cache = vertexData.length; index < cache; index++) {
  60225. var parsedVertexData = vertexData[index];
  60226. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  60227. }
  60228. }
  60229. addedGeometry.forEach(function (g) {
  60230. if (g) {
  60231. container.geometries.push(g);
  60232. }
  60233. });
  60234. }
  60235. // Transform nodes
  60236. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  60237. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  60238. var parsedTransformNode = parsedData.transformNodes[index];
  60239. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60240. container.transformNodes.push(node);
  60241. }
  60242. }
  60243. // Meshes
  60244. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60245. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60246. var parsedMesh = parsedData.meshes[index];
  60247. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60248. container.meshes.push(mesh);
  60249. log += (index === 0 ? "\n\tMeshes:" : "");
  60250. log += "\n\t\t" + mesh.toString(fullDetails);
  60251. }
  60252. }
  60253. // Cameras
  60254. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60255. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  60256. var parsedCamera = parsedData.cameras[index];
  60257. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  60258. container.cameras.push(camera);
  60259. log += (index === 0 ? "\n\tCameras:" : "");
  60260. log += "\n\t\t" + camera.toString(fullDetails);
  60261. }
  60262. }
  60263. // Browsing all the graph to connect the dots
  60264. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  60265. var camera = scene.cameras[index];
  60266. if (camera._waitingParentId) {
  60267. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  60268. camera._waitingParentId = null;
  60269. }
  60270. }
  60271. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60272. var light_1 = scene.lights[index];
  60273. if (light_1 && light_1._waitingParentId) {
  60274. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  60275. light_1._waitingParentId = null;
  60276. }
  60277. }
  60278. // Sounds
  60279. // TODO: add sound
  60280. var loadedSounds = [];
  60281. var loadedSound;
  60282. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  60283. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  60284. var parsedSound = parsedData.sounds[index];
  60285. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60286. if (!parsedSound.url)
  60287. parsedSound.url = parsedSound.name;
  60288. if (!loadedSounds[parsedSound.url]) {
  60289. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  60290. loadedSounds[parsedSound.url] = loadedSound;
  60291. container.sounds.push(loadedSound);
  60292. }
  60293. else {
  60294. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  60295. }
  60296. }
  60297. else {
  60298. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  60299. }
  60300. }
  60301. }
  60302. loadedSounds = [];
  60303. // Connect parents & children and parse actions
  60304. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  60305. var transformNode = scene.transformNodes[index];
  60306. if (transformNode._waitingParentId) {
  60307. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  60308. transformNode._waitingParentId = null;
  60309. }
  60310. }
  60311. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60312. var mesh = scene.meshes[index];
  60313. if (mesh._waitingParentId) {
  60314. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  60315. mesh._waitingParentId = null;
  60316. }
  60317. if (mesh._waitingActions) {
  60318. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  60319. mesh._waitingActions = null;
  60320. }
  60321. }
  60322. // freeze world matrix application
  60323. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60324. var currentMesh = scene.meshes[index];
  60325. if (currentMesh._waitingFreezeWorldMatrix) {
  60326. currentMesh.freezeWorldMatrix();
  60327. currentMesh._waitingFreezeWorldMatrix = null;
  60328. }
  60329. else {
  60330. currentMesh.computeWorldMatrix(true);
  60331. }
  60332. }
  60333. // Particles Systems
  60334. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60335. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60336. var parsedParticleSystem = parsedData.particleSystems[index];
  60337. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60338. container.particleSystems.push(ps);
  60339. }
  60340. }
  60341. // Lens flares
  60342. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60343. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60344. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60345. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60346. container.lensFlareSystems.push(lf);
  60347. }
  60348. }
  60349. // Shadows
  60350. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60351. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60352. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60353. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60354. container.shadowGenerators.push(sg);
  60355. }
  60356. }
  60357. // Lights exclusions / inclusions
  60358. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60359. var light_2 = scene.lights[index];
  60360. // Excluded check
  60361. if (light_2._excludedMeshesIds.length > 0) {
  60362. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60363. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60364. if (excludedMesh) {
  60365. light_2.excludedMeshes.push(excludedMesh);
  60366. }
  60367. }
  60368. light_2._excludedMeshesIds = [];
  60369. }
  60370. // Included check
  60371. if (light_2._includedOnlyMeshesIds.length > 0) {
  60372. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60373. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60374. if (includedOnlyMesh) {
  60375. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60376. }
  60377. }
  60378. light_2._includedOnlyMeshesIds = [];
  60379. }
  60380. }
  60381. // Actions (scene)
  60382. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60383. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60384. }
  60385. if (!addToScene) {
  60386. container.removeAllFromScene();
  60387. }
  60388. }
  60389. catch (err) {
  60390. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60391. if (onError) {
  60392. onError(msg, err);
  60393. }
  60394. else {
  60395. BABYLON.Tools.Log(msg);
  60396. throw err;
  60397. }
  60398. }
  60399. finally {
  60400. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60401. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60402. }
  60403. }
  60404. return container;
  60405. };
  60406. BABYLON.SceneLoader.RegisterPlugin({
  60407. name: "babylon.js",
  60408. extensions: ".babylon",
  60409. canDirectLoad: function (data) {
  60410. if (data.indexOf("babylon") !== -1) {
  60411. return true;
  60412. }
  60413. return false;
  60414. },
  60415. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60416. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60417. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60418. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60419. // and avoid problems with multiple concurrent .babylon loads.
  60420. var log = "importMesh has failed JSON parse";
  60421. try {
  60422. var parsedData = JSON.parse(data);
  60423. log = "";
  60424. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60425. if (!meshesNames) {
  60426. meshesNames = null;
  60427. }
  60428. else if (!Array.isArray(meshesNames)) {
  60429. meshesNames = [meshesNames];
  60430. }
  60431. var hierarchyIds = new Array();
  60432. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60433. var loadedSkeletonsIds = [];
  60434. var loadedMaterialsIds = [];
  60435. var index;
  60436. var cache;
  60437. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60438. var parsedMesh = parsedData.meshes[index];
  60439. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60440. if (meshesNames !== null) {
  60441. // Remove found mesh name from list.
  60442. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60443. }
  60444. //Geometry?
  60445. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60446. //does the file contain geometries?
  60447. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60448. //find the correct geometry and add it to the scene
  60449. var found = false;
  60450. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60451. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60452. return;
  60453. }
  60454. else {
  60455. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60456. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60457. switch (geometryType) {
  60458. case "boxes":
  60459. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60460. break;
  60461. case "spheres":
  60462. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60463. break;
  60464. case "cylinders":
  60465. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60466. break;
  60467. case "toruses":
  60468. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60469. break;
  60470. case "grounds":
  60471. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60472. break;
  60473. case "planes":
  60474. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60475. break;
  60476. case "torusKnots":
  60477. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60478. break;
  60479. case "vertexData":
  60480. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60481. break;
  60482. }
  60483. found = true;
  60484. }
  60485. });
  60486. }
  60487. });
  60488. if (found === false) {
  60489. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60490. }
  60491. }
  60492. }
  60493. // Material ?
  60494. if (parsedMesh.materialId) {
  60495. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60496. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60497. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60498. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60499. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60500. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60501. var subMatId = parsedMultiMaterial.materials[matIndex];
  60502. loadedMaterialsIds.push(subMatId);
  60503. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60504. if (mat) {
  60505. log += "\n\tMaterial " + mat.toString(fullDetails);
  60506. }
  60507. }
  60508. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60509. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60510. if (mmat) {
  60511. materialFound = true;
  60512. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60513. }
  60514. break;
  60515. }
  60516. }
  60517. }
  60518. if (materialFound === false) {
  60519. loadedMaterialsIds.push(parsedMesh.materialId);
  60520. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60521. if (!mat) {
  60522. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60523. }
  60524. else {
  60525. log += "\n\tMaterial " + mat.toString(fullDetails);
  60526. }
  60527. }
  60528. }
  60529. // Skeleton ?
  60530. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60531. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60532. if (skeletonAlreadyLoaded === false) {
  60533. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60534. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60535. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60536. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60537. skeletons.push(skeleton);
  60538. loadedSkeletonsIds.push(parsedSkeleton.id);
  60539. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60540. }
  60541. }
  60542. }
  60543. }
  60544. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60545. meshes.push(mesh);
  60546. log += "\n\tMesh " + mesh.toString(fullDetails);
  60547. }
  60548. }
  60549. // Connecting parents
  60550. var currentMesh;
  60551. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60552. currentMesh = scene.meshes[index];
  60553. if (currentMesh._waitingParentId) {
  60554. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60555. currentMesh._waitingParentId = null;
  60556. }
  60557. }
  60558. // freeze and compute world matrix application
  60559. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60560. currentMesh = scene.meshes[index];
  60561. if (currentMesh._waitingFreezeWorldMatrix) {
  60562. currentMesh.freezeWorldMatrix();
  60563. currentMesh._waitingFreezeWorldMatrix = null;
  60564. }
  60565. else {
  60566. currentMesh.computeWorldMatrix(true);
  60567. }
  60568. }
  60569. }
  60570. // Particles
  60571. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60572. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60573. var parsedParticleSystem = parsedData.particleSystems[index];
  60574. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60575. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60576. }
  60577. }
  60578. }
  60579. return true;
  60580. }
  60581. catch (err) {
  60582. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  60583. if (onError) {
  60584. onError(msg, err);
  60585. }
  60586. else {
  60587. BABYLON.Tools.Log(msg);
  60588. throw err;
  60589. }
  60590. }
  60591. finally {
  60592. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60593. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60594. }
  60595. }
  60596. return false;
  60597. },
  60598. load: function (scene, data, rootUrl, onError) {
  60599. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60600. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60601. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60602. // and avoid problems with multiple concurrent .babylon loads.
  60603. var log = "importScene has failed JSON parse";
  60604. try {
  60605. var parsedData = JSON.parse(data);
  60606. log = "";
  60607. // Scene
  60608. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  60609. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  60610. }
  60611. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  60612. scene.autoClear = parsedData.autoClear;
  60613. }
  60614. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  60615. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  60616. }
  60617. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  60618. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  60619. }
  60620. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  60621. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  60622. }
  60623. // Fog
  60624. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  60625. scene.fogMode = parsedData.fogMode;
  60626. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  60627. scene.fogStart = parsedData.fogStart;
  60628. scene.fogEnd = parsedData.fogEnd;
  60629. scene.fogDensity = parsedData.fogDensity;
  60630. log += "\tFog mode for scene: ";
  60631. switch (scene.fogMode) {
  60632. // getters not compiling, so using hardcoded
  60633. case 1:
  60634. log += "exp\n";
  60635. break;
  60636. case 2:
  60637. log += "exp2\n";
  60638. break;
  60639. case 3:
  60640. log += "linear\n";
  60641. break;
  60642. }
  60643. }
  60644. //Physics
  60645. if (parsedData.physicsEnabled) {
  60646. var physicsPlugin;
  60647. if (parsedData.physicsEngine === "cannon") {
  60648. physicsPlugin = new BABYLON.CannonJSPlugin();
  60649. }
  60650. else if (parsedData.physicsEngine === "oimo") {
  60651. physicsPlugin = new BABYLON.OimoJSPlugin();
  60652. }
  60653. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  60654. //else - default engine, which is currently oimo
  60655. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  60656. scene.enablePhysics(physicsGravity, physicsPlugin);
  60657. }
  60658. // Metadata
  60659. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  60660. scene.metadata = parsedData.metadata;
  60661. }
  60662. //collisions, if defined. otherwise, default is true
  60663. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  60664. scene.collisionsEnabled = parsedData.collisionsEnabled;
  60665. }
  60666. scene.workerCollisions = !!parsedData.workerCollisions;
  60667. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  60668. if (!container) {
  60669. return false;
  60670. }
  60671. if (parsedData.autoAnimate) {
  60672. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  60673. }
  60674. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  60675. scene.setActiveCameraByID(parsedData.activeCameraID);
  60676. }
  60677. // Environment texture
  60678. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  60679. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  60680. if (parsedData.createDefaultSkybox === true) {
  60681. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  60682. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  60683. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  60684. }
  60685. }
  60686. // Finish
  60687. return true;
  60688. }
  60689. catch (err) {
  60690. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  60691. if (onError) {
  60692. onError(msg, err);
  60693. }
  60694. else {
  60695. BABYLON.Tools.Log(msg);
  60696. throw err;
  60697. }
  60698. }
  60699. finally {
  60700. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60701. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60702. }
  60703. }
  60704. return false;
  60705. },
  60706. loadAssetContainer: function (scene, data, rootUrl, onError) {
  60707. var container = loadAssetContainer(scene, data, rootUrl, onError);
  60708. return container;
  60709. }
  60710. });
  60711. })(BABYLON || (BABYLON = {}));
  60712. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  60713. var BABYLON;
  60714. (function (BABYLON) {
  60715. var FilesInput = /** @class */ (function () {
  60716. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  60717. this.onProcessFileCallback = function () { return true; };
  60718. this._engine = engine;
  60719. this._currentScene = scene;
  60720. this._sceneLoadedCallback = sceneLoadedCallback;
  60721. this._progressCallback = progressCallback;
  60722. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  60723. this._textureLoadingCallback = textureLoadingCallback;
  60724. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  60725. this._onReloadCallback = onReloadCallback;
  60726. this._errorCallback = errorCallback;
  60727. }
  60728. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  60729. var _this = this;
  60730. if (elementToMonitor) {
  60731. this._elementToMonitor = elementToMonitor;
  60732. this._dragEnterHandler = function (e) { _this.drag(e); };
  60733. this._dragOverHandler = function (e) { _this.drag(e); };
  60734. this._dropHandler = function (e) { _this.drop(e); };
  60735. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  60736. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  60737. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  60738. }
  60739. };
  60740. FilesInput.prototype.dispose = function () {
  60741. if (!this._elementToMonitor) {
  60742. return;
  60743. }
  60744. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  60745. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  60746. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  60747. };
  60748. FilesInput.prototype.renderFunction = function () {
  60749. if (this._additionalRenderLoopLogicCallback) {
  60750. this._additionalRenderLoopLogicCallback();
  60751. }
  60752. if (this._currentScene) {
  60753. if (this._textureLoadingCallback) {
  60754. var remaining = this._currentScene.getWaitingItemsCount();
  60755. if (remaining > 0) {
  60756. this._textureLoadingCallback(remaining);
  60757. }
  60758. }
  60759. this._currentScene.render();
  60760. }
  60761. };
  60762. FilesInput.prototype.drag = function (e) {
  60763. e.stopPropagation();
  60764. e.preventDefault();
  60765. };
  60766. FilesInput.prototype.drop = function (eventDrop) {
  60767. eventDrop.stopPropagation();
  60768. eventDrop.preventDefault();
  60769. this.loadFiles(eventDrop);
  60770. };
  60771. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  60772. var _this = this;
  60773. var reader = folder.createReader();
  60774. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  60775. reader.readEntries(function (entries) {
  60776. remaining.count += entries.length;
  60777. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  60778. var entry = entries_1[_i];
  60779. if (entry.isFile) {
  60780. entry.file(function (file) {
  60781. file.correctName = relativePath + file.name;
  60782. files.push(file);
  60783. if (--remaining.count === 0) {
  60784. callback();
  60785. }
  60786. });
  60787. }
  60788. else if (entry.isDirectory) {
  60789. _this._traverseFolder(entry, files, remaining, callback);
  60790. }
  60791. }
  60792. if (--remaining.count) {
  60793. callback();
  60794. }
  60795. });
  60796. };
  60797. FilesInput.prototype._processFiles = function (files) {
  60798. for (var i = 0; i < files.length; i++) {
  60799. var name = files[i].correctName.toLowerCase();
  60800. var extension = name.split('.').pop();
  60801. if (!this.onProcessFileCallback(files[i], name, extension)) {
  60802. continue;
  60803. }
  60804. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  60805. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  60806. this._sceneFileToLoad = files[i];
  60807. }
  60808. else {
  60809. FilesInput.FilesToLoad[name] = files[i];
  60810. }
  60811. }
  60812. };
  60813. FilesInput.prototype.loadFiles = function (event) {
  60814. var _this = this;
  60815. if (this._startingProcessingFilesCallback)
  60816. this._startingProcessingFilesCallback();
  60817. // Handling data transfer via drag'n'drop
  60818. if (event && event.dataTransfer && event.dataTransfer.files) {
  60819. this._filesToLoad = event.dataTransfer.files;
  60820. }
  60821. // Handling files from input files
  60822. if (event && event.target && event.target.files) {
  60823. this._filesToLoad = event.target.files;
  60824. }
  60825. if (this._filesToLoad && this._filesToLoad.length > 0) {
  60826. var files_1 = new Array();
  60827. var folders = [];
  60828. var items = event.dataTransfer ? event.dataTransfer.items : null;
  60829. for (var i = 0; i < this._filesToLoad.length; i++) {
  60830. var fileToLoad = this._filesToLoad[i];
  60831. var name_1 = fileToLoad.name.toLowerCase();
  60832. var entry = void 0;
  60833. fileToLoad.correctName = name_1;
  60834. if (items) {
  60835. var item = items[i];
  60836. if (item.getAsEntry) {
  60837. entry = item.getAsEntry();
  60838. }
  60839. else if (item.webkitGetAsEntry) {
  60840. entry = item.webkitGetAsEntry();
  60841. }
  60842. }
  60843. if (!entry) {
  60844. files_1.push(fileToLoad);
  60845. }
  60846. else {
  60847. if (entry.isDirectory) {
  60848. folders.push(entry);
  60849. }
  60850. else {
  60851. files_1.push(fileToLoad);
  60852. }
  60853. }
  60854. }
  60855. if (folders.length === 0) {
  60856. this._processFiles(files_1);
  60857. this._processReload();
  60858. }
  60859. else {
  60860. var remaining = { count: folders.length };
  60861. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  60862. var folder = folders_1[_i];
  60863. this._traverseFolder(folder, files_1, remaining, function () {
  60864. _this._processFiles(files_1);
  60865. if (remaining.count === 0) {
  60866. _this._processReload();
  60867. }
  60868. });
  60869. }
  60870. }
  60871. }
  60872. };
  60873. FilesInput.prototype._processReload = function () {
  60874. if (this._onReloadCallback) {
  60875. this._onReloadCallback(this._sceneFileToLoad);
  60876. }
  60877. else {
  60878. this.reload();
  60879. }
  60880. };
  60881. FilesInput.prototype.reload = function () {
  60882. var _this = this;
  60883. // If a scene file has been provided
  60884. if (this._sceneFileToLoad) {
  60885. if (this._currentScene) {
  60886. if (BABYLON.Tools.errorsCount > 0) {
  60887. BABYLON.Tools.ClearLogCache();
  60888. }
  60889. this._engine.stopRenderLoop();
  60890. this._currentScene.dispose();
  60891. }
  60892. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  60893. if (_this._progressCallback) {
  60894. _this._progressCallback(progress);
  60895. }
  60896. }).then(function (scene) {
  60897. _this._currentScene = scene;
  60898. if (_this._sceneLoadedCallback) {
  60899. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  60900. }
  60901. // Wait for textures and shaders to be ready
  60902. _this._currentScene.executeWhenReady(function () {
  60903. _this._engine.runRenderLoop(function () {
  60904. _this.renderFunction();
  60905. });
  60906. });
  60907. }).catch(function (error) {
  60908. if (_this._errorCallback) {
  60909. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  60910. }
  60911. });
  60912. }
  60913. else {
  60914. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  60915. }
  60916. };
  60917. FilesInput.FilesToLoad = {};
  60918. return FilesInput;
  60919. }());
  60920. BABYLON.FilesInput = FilesInput;
  60921. })(BABYLON || (BABYLON = {}));
  60922. //# sourceMappingURL=babylon.filesInput.js.map
  60923. var BABYLON;
  60924. (function (BABYLON) {
  60925. /**
  60926. * This class implement a typical dictionary using a string as key and the generic type T as value.
  60927. * The underlying implementation relies on an associative array to ensure the best performances.
  60928. * The value can be anything including 'null' but except 'undefined'
  60929. */
  60930. var StringDictionary = /** @class */ (function () {
  60931. function StringDictionary() {
  60932. this._count = 0;
  60933. this._data = {};
  60934. }
  60935. /**
  60936. * This will clear this dictionary and copy the content from the 'source' one.
  60937. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  60938. * @param source the dictionary to take the content from and copy to this dictionary
  60939. */
  60940. StringDictionary.prototype.copyFrom = function (source) {
  60941. var _this = this;
  60942. this.clear();
  60943. source.forEach(function (t, v) { return _this.add(t, v); });
  60944. };
  60945. /**
  60946. * Get a value based from its key
  60947. * @param key the given key to get the matching value from
  60948. * @return the value if found, otherwise undefined is returned
  60949. */
  60950. StringDictionary.prototype.get = function (key) {
  60951. var val = this._data[key];
  60952. if (val !== undefined) {
  60953. return val;
  60954. }
  60955. return undefined;
  60956. };
  60957. /**
  60958. * Get a value from its key or add it if it doesn't exist.
  60959. * This method will ensure you that a given key/data will be present in the dictionary.
  60960. * @param key the given key to get the matching value from
  60961. * @param factory the factory that will create the value if the key is not present in the dictionary.
  60962. * The factory will only be invoked if there's no data for the given key.
  60963. * @return the value corresponding to the key.
  60964. */
  60965. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  60966. var val = this.get(key);
  60967. if (val !== undefined) {
  60968. return val;
  60969. }
  60970. val = factory(key);
  60971. if (val) {
  60972. this.add(key, val);
  60973. }
  60974. return val;
  60975. };
  60976. /**
  60977. * Get a value from its key if present in the dictionary otherwise add it
  60978. * @param key the key to get the value from
  60979. * @param val if there's no such key/value pair in the dictionary add it with this value
  60980. * @return the value corresponding to the key
  60981. */
  60982. StringDictionary.prototype.getOrAdd = function (key, val) {
  60983. var curVal = this.get(key);
  60984. if (curVal !== undefined) {
  60985. return curVal;
  60986. }
  60987. this.add(key, val);
  60988. return val;
  60989. };
  60990. /**
  60991. * Check if there's a given key in the dictionary
  60992. * @param key the key to check for
  60993. * @return true if the key is present, false otherwise
  60994. */
  60995. StringDictionary.prototype.contains = function (key) {
  60996. return this._data[key] !== undefined;
  60997. };
  60998. /**
  60999. * Add a new key and its corresponding value
  61000. * @param key the key to add
  61001. * @param value the value corresponding to the key
  61002. * @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
  61003. */
  61004. StringDictionary.prototype.add = function (key, value) {
  61005. if (this._data[key] !== undefined) {
  61006. return false;
  61007. }
  61008. this._data[key] = value;
  61009. ++this._count;
  61010. return true;
  61011. };
  61012. StringDictionary.prototype.set = function (key, value) {
  61013. if (this._data[key] === undefined) {
  61014. return false;
  61015. }
  61016. this._data[key] = value;
  61017. return true;
  61018. };
  61019. /**
  61020. * Get the element of the given key and remove it from the dictionary
  61021. * @param key
  61022. */
  61023. StringDictionary.prototype.getAndRemove = function (key) {
  61024. var val = this.get(key);
  61025. if (val !== undefined) {
  61026. delete this._data[key];
  61027. --this._count;
  61028. return val;
  61029. }
  61030. return null;
  61031. };
  61032. /**
  61033. * Remove a key/value from the dictionary.
  61034. * @param key the key to remove
  61035. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61036. */
  61037. StringDictionary.prototype.remove = function (key) {
  61038. if (this.contains(key)) {
  61039. delete this._data[key];
  61040. --this._count;
  61041. return true;
  61042. }
  61043. return false;
  61044. };
  61045. /**
  61046. * Clear the whole content of the dictionary
  61047. */
  61048. StringDictionary.prototype.clear = function () {
  61049. this._data = {};
  61050. this._count = 0;
  61051. };
  61052. Object.defineProperty(StringDictionary.prototype, "count", {
  61053. get: function () {
  61054. return this._count;
  61055. },
  61056. enumerable: true,
  61057. configurable: true
  61058. });
  61059. /**
  61060. * Execute a callback on each key/val of the dictionary.
  61061. * Note that you can remove any element in this dictionary in the callback implementation
  61062. * @param callback the callback to execute on a given key/value pair
  61063. */
  61064. StringDictionary.prototype.forEach = function (callback) {
  61065. for (var cur in this._data) {
  61066. var val = this._data[cur];
  61067. callback(cur, val);
  61068. }
  61069. };
  61070. /**
  61071. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61072. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61073. * Note that you can remove any element in this dictionary in the callback implementation
  61074. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61075. */
  61076. StringDictionary.prototype.first = function (callback) {
  61077. for (var cur in this._data) {
  61078. var val = this._data[cur];
  61079. var res = callback(cur, val);
  61080. if (res) {
  61081. return res;
  61082. }
  61083. }
  61084. return null;
  61085. };
  61086. return StringDictionary;
  61087. }());
  61088. BABYLON.StringDictionary = StringDictionary;
  61089. })(BABYLON || (BABYLON = {}));
  61090. //# sourceMappingURL=babylon.stringDictionary.js.map
  61091. var BABYLON;
  61092. (function (BABYLON) {
  61093. var Tags = /** @class */ (function () {
  61094. function Tags() {
  61095. }
  61096. Tags.EnableFor = function (obj) {
  61097. obj._tags = obj._tags || {};
  61098. obj.hasTags = function () {
  61099. return Tags.HasTags(obj);
  61100. };
  61101. obj.addTags = function (tagsString) {
  61102. return Tags.AddTagsTo(obj, tagsString);
  61103. };
  61104. obj.removeTags = function (tagsString) {
  61105. return Tags.RemoveTagsFrom(obj, tagsString);
  61106. };
  61107. obj.matchesTagsQuery = function (tagsQuery) {
  61108. return Tags.MatchesQuery(obj, tagsQuery);
  61109. };
  61110. };
  61111. Tags.DisableFor = function (obj) {
  61112. delete obj._tags;
  61113. delete obj.hasTags;
  61114. delete obj.addTags;
  61115. delete obj.removeTags;
  61116. delete obj.matchesTagsQuery;
  61117. };
  61118. Tags.HasTags = function (obj) {
  61119. if (!obj._tags) {
  61120. return false;
  61121. }
  61122. return !BABYLON.Tools.IsEmpty(obj._tags);
  61123. };
  61124. Tags.GetTags = function (obj, asString) {
  61125. if (asString === void 0) { asString = true; }
  61126. if (!obj._tags) {
  61127. return null;
  61128. }
  61129. if (asString) {
  61130. var tagsArray = [];
  61131. for (var tag in obj._tags) {
  61132. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  61133. tagsArray.push(tag);
  61134. }
  61135. }
  61136. return tagsArray.join(" ");
  61137. }
  61138. else {
  61139. return obj._tags;
  61140. }
  61141. };
  61142. // the tags 'true' and 'false' are reserved and cannot be used as tags
  61143. // a tag cannot start with '||', '&&', and '!'
  61144. // it cannot contain whitespaces
  61145. Tags.AddTagsTo = function (obj, tagsString) {
  61146. if (!tagsString) {
  61147. return;
  61148. }
  61149. if (typeof tagsString !== "string") {
  61150. return;
  61151. }
  61152. var tags = tagsString.split(" ");
  61153. tags.forEach(function (tag, index, array) {
  61154. Tags._AddTagTo(obj, tag);
  61155. });
  61156. };
  61157. Tags._AddTagTo = function (obj, tag) {
  61158. tag = tag.trim();
  61159. if (tag === "" || tag === "true" || tag === "false") {
  61160. return;
  61161. }
  61162. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  61163. return;
  61164. }
  61165. Tags.EnableFor(obj);
  61166. obj._tags[tag] = true;
  61167. };
  61168. Tags.RemoveTagsFrom = function (obj, tagsString) {
  61169. if (!Tags.HasTags(obj)) {
  61170. return;
  61171. }
  61172. var tags = tagsString.split(" ");
  61173. for (var t in tags) {
  61174. Tags._RemoveTagFrom(obj, tags[t]);
  61175. }
  61176. };
  61177. Tags._RemoveTagFrom = function (obj, tag) {
  61178. delete obj._tags[tag];
  61179. };
  61180. Tags.MatchesQuery = function (obj, tagsQuery) {
  61181. if (tagsQuery === undefined) {
  61182. return true;
  61183. }
  61184. if (tagsQuery === "") {
  61185. return Tags.HasTags(obj);
  61186. }
  61187. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  61188. };
  61189. return Tags;
  61190. }());
  61191. BABYLON.Tags = Tags;
  61192. })(BABYLON || (BABYLON = {}));
  61193. //# sourceMappingURL=babylon.tags.js.map
  61194. var BABYLON;
  61195. (function (BABYLON) {
  61196. var AndOrNotEvaluator = /** @class */ (function () {
  61197. function AndOrNotEvaluator() {
  61198. }
  61199. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61200. if (!query.match(/\([^\(\)]*\)/g)) {
  61201. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61202. }
  61203. else {
  61204. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  61205. // remove parenthesis
  61206. r = r.slice(1, r.length - 1);
  61207. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  61208. });
  61209. }
  61210. if (query === "true") {
  61211. return true;
  61212. }
  61213. if (query === "false") {
  61214. return false;
  61215. }
  61216. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  61217. };
  61218. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  61219. evaluateCallback = evaluateCallback || (function (r) {
  61220. return r === "true" ? true : false;
  61221. });
  61222. var result;
  61223. var or = parenthesisContent.split("||");
  61224. for (var i in or) {
  61225. if (or.hasOwnProperty(i)) {
  61226. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  61227. var and = ori.split("&&");
  61228. if (and.length > 1) {
  61229. for (var j = 0; j < and.length; ++j) {
  61230. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  61231. if (andj !== "true" && andj !== "false") {
  61232. if (andj[0] === "!") {
  61233. result = !evaluateCallback(andj.substring(1));
  61234. }
  61235. else {
  61236. result = evaluateCallback(andj);
  61237. }
  61238. }
  61239. else {
  61240. result = andj === "true" ? true : false;
  61241. }
  61242. if (!result) {
  61243. ori = "false";
  61244. break;
  61245. }
  61246. }
  61247. }
  61248. if (result || ori === "true") {
  61249. result = true;
  61250. break;
  61251. }
  61252. // result equals false (or undefined)
  61253. if (ori !== "true" && ori !== "false") {
  61254. if (ori[0] === "!") {
  61255. result = !evaluateCallback(ori.substring(1));
  61256. }
  61257. else {
  61258. result = evaluateCallback(ori);
  61259. }
  61260. }
  61261. else {
  61262. result = ori === "true" ? true : false;
  61263. }
  61264. }
  61265. }
  61266. // the whole parenthesis scope is replaced by 'true' or 'false'
  61267. return result ? "true" : "false";
  61268. };
  61269. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  61270. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  61271. // remove whitespaces
  61272. r = r.replace(/[\s]/g, function () { return ""; });
  61273. return r.length % 2 ? "!" : "";
  61274. });
  61275. booleanString = booleanString.trim();
  61276. if (booleanString === "!true") {
  61277. booleanString = "false";
  61278. }
  61279. else if (booleanString === "!false") {
  61280. booleanString = "true";
  61281. }
  61282. return booleanString;
  61283. };
  61284. return AndOrNotEvaluator;
  61285. }());
  61286. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  61287. })(BABYLON || (BABYLON = {}));
  61288. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  61289. var BABYLON;
  61290. (function (BABYLON) {
  61291. var Database = /** @class */ (function () {
  61292. function Database(urlToScene, callbackManifestChecked) {
  61293. // Handling various flavors of prefixed version of IndexedDB
  61294. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  61295. this.callbackManifestChecked = callbackManifestChecked;
  61296. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  61297. this.db = null;
  61298. this._enableSceneOffline = false;
  61299. this._enableTexturesOffline = false;
  61300. this.manifestVersionFound = 0;
  61301. this.mustUpdateRessources = false;
  61302. this.hasReachedQuota = false;
  61303. if (!Database.IDBStorageEnabled) {
  61304. this.callbackManifestChecked(true);
  61305. }
  61306. else {
  61307. this.checkManifestFile();
  61308. }
  61309. }
  61310. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  61311. get: function () {
  61312. return this._enableSceneOffline;
  61313. },
  61314. enumerable: true,
  61315. configurable: true
  61316. });
  61317. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  61318. get: function () {
  61319. return this._enableTexturesOffline;
  61320. },
  61321. enumerable: true,
  61322. configurable: true
  61323. });
  61324. Database.prototype.checkManifestFile = function () {
  61325. var _this = this;
  61326. var noManifestFile = function () {
  61327. _this._enableSceneOffline = false;
  61328. _this._enableTexturesOffline = false;
  61329. _this.callbackManifestChecked(false);
  61330. };
  61331. var timeStampUsed = false;
  61332. var manifestURL = this.currentSceneUrl + ".manifest";
  61333. var xhr = new XMLHttpRequest();
  61334. if (navigator.onLine) {
  61335. // Adding a timestamp to by-pass browsers' cache
  61336. timeStampUsed = true;
  61337. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61338. }
  61339. xhr.open("GET", manifestURL, true);
  61340. xhr.addEventListener("load", function () {
  61341. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61342. try {
  61343. var manifestFile = JSON.parse(xhr.response);
  61344. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61345. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61346. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61347. _this.manifestVersionFound = manifestFile.version;
  61348. }
  61349. if (_this.callbackManifestChecked) {
  61350. _this.callbackManifestChecked(true);
  61351. }
  61352. }
  61353. catch (ex) {
  61354. noManifestFile();
  61355. }
  61356. }
  61357. else {
  61358. noManifestFile();
  61359. }
  61360. }, false);
  61361. xhr.addEventListener("error", function (event) {
  61362. if (timeStampUsed) {
  61363. timeStampUsed = false;
  61364. // Let's retry without the timeStamp
  61365. // It could fail when coupled with HTML5 Offline API
  61366. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61367. xhr.open("GET", retryManifestURL, true);
  61368. xhr.send();
  61369. }
  61370. else {
  61371. noManifestFile();
  61372. }
  61373. }, false);
  61374. try {
  61375. xhr.send();
  61376. }
  61377. catch (ex) {
  61378. BABYLON.Tools.Error("Error on XHR send request.");
  61379. this.callbackManifestChecked(false);
  61380. }
  61381. };
  61382. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61383. var _this = this;
  61384. var handleError = function () {
  61385. _this.isSupported = false;
  61386. if (errorCallback)
  61387. errorCallback();
  61388. };
  61389. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61390. // Your browser doesn't support IndexedDB
  61391. this.isSupported = false;
  61392. if (errorCallback)
  61393. errorCallback();
  61394. }
  61395. else {
  61396. // If the DB hasn't been opened or created yet
  61397. if (!this.db) {
  61398. this.hasReachedQuota = false;
  61399. this.isSupported = true;
  61400. var request = this.idbFactory.open("babylonjs", 1);
  61401. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61402. request.onerror = function (event) {
  61403. handleError();
  61404. };
  61405. // executes when a version change transaction cannot complete due to other active transactions
  61406. request.onblocked = function (event) {
  61407. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61408. handleError();
  61409. };
  61410. // DB has been opened successfully
  61411. request.onsuccess = function (event) {
  61412. _this.db = request.result;
  61413. successCallback();
  61414. };
  61415. // Initialization of the DB. Creating Scenes & Textures stores
  61416. request.onupgradeneeded = function (event) {
  61417. _this.db = (event.target).result;
  61418. if (_this.db) {
  61419. try {
  61420. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61421. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61422. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61423. }
  61424. catch (ex) {
  61425. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61426. handleError();
  61427. }
  61428. }
  61429. };
  61430. }
  61431. else {
  61432. if (successCallback)
  61433. successCallback();
  61434. }
  61435. }
  61436. };
  61437. Database.prototype.loadImageFromDB = function (url, image) {
  61438. var _this = this;
  61439. var completeURL = Database.ReturnFullUrlLocation(url);
  61440. var saveAndLoadImage = function () {
  61441. if (!_this.hasReachedQuota && _this.db !== null) {
  61442. // the texture is not yet in the DB, let's try to save it
  61443. _this._saveImageIntoDBAsync(completeURL, image);
  61444. }
  61445. else {
  61446. image.src = url;
  61447. }
  61448. };
  61449. if (!this.mustUpdateRessources) {
  61450. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61451. }
  61452. else {
  61453. saveAndLoadImage();
  61454. }
  61455. };
  61456. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61457. if (this.isSupported && this.db !== null) {
  61458. var texture;
  61459. var transaction = this.db.transaction(["textures"]);
  61460. transaction.onabort = function (event) {
  61461. image.src = url;
  61462. };
  61463. transaction.oncomplete = function (event) {
  61464. var blobTextureURL;
  61465. if (texture) {
  61466. var URL = window.URL || window.webkitURL;
  61467. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61468. image.onerror = function () {
  61469. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61470. image.src = url;
  61471. };
  61472. image.src = blobTextureURL;
  61473. }
  61474. else {
  61475. notInDBCallback();
  61476. }
  61477. };
  61478. var getRequest = transaction.objectStore("textures").get(url);
  61479. getRequest.onsuccess = function (event) {
  61480. texture = (event.target).result;
  61481. };
  61482. getRequest.onerror = function (event) {
  61483. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61484. image.src = url;
  61485. };
  61486. }
  61487. else {
  61488. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61489. image.src = url;
  61490. }
  61491. };
  61492. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61493. var _this = this;
  61494. if (this.isSupported) {
  61495. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61496. var generateBlobUrl = function () {
  61497. var blobTextureURL;
  61498. if (blob) {
  61499. var URL = window.URL || window.webkitURL;
  61500. try {
  61501. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61502. }
  61503. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61504. catch (ex) {
  61505. blobTextureURL = URL.createObjectURL(blob);
  61506. }
  61507. }
  61508. if (blobTextureURL) {
  61509. image.src = blobTextureURL;
  61510. }
  61511. };
  61512. if (Database.IsUASupportingBlobStorage) {
  61513. var xhr = new XMLHttpRequest(), blob;
  61514. xhr.open("GET", url, true);
  61515. xhr.responseType = "blob";
  61516. xhr.addEventListener("load", function () {
  61517. if (xhr.status === 200 && _this.db) {
  61518. // Blob as response (XHR2)
  61519. blob = xhr.response;
  61520. var transaction = _this.db.transaction(["textures"], "readwrite");
  61521. // the transaction could abort because of a QuotaExceededError error
  61522. transaction.onabort = function (event) {
  61523. try {
  61524. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61525. var srcElement = (event.srcElement || event.target);
  61526. var error = srcElement.error;
  61527. if (error && error.name === "QuotaExceededError") {
  61528. _this.hasReachedQuota = true;
  61529. }
  61530. }
  61531. catch (ex) { }
  61532. generateBlobUrl();
  61533. };
  61534. transaction.oncomplete = function (event) {
  61535. generateBlobUrl();
  61536. };
  61537. var newTexture = { textureUrl: url, data: blob };
  61538. try {
  61539. // Put the blob into the dabase
  61540. var addRequest = transaction.objectStore("textures").put(newTexture);
  61541. addRequest.onsuccess = function (event) {
  61542. };
  61543. addRequest.onerror = function (event) {
  61544. generateBlobUrl();
  61545. };
  61546. }
  61547. catch (ex) {
  61548. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61549. if (ex.code === 25) {
  61550. Database.IsUASupportingBlobStorage = false;
  61551. }
  61552. image.src = url;
  61553. }
  61554. }
  61555. else {
  61556. image.src = url;
  61557. }
  61558. }, false);
  61559. xhr.addEventListener("error", function (event) {
  61560. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61561. image.src = url;
  61562. }, false);
  61563. xhr.send();
  61564. }
  61565. else {
  61566. image.src = url;
  61567. }
  61568. }
  61569. else {
  61570. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61571. image.src = url;
  61572. }
  61573. };
  61574. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61575. var _this = this;
  61576. var updateVersion = function () {
  61577. // the version is not yet in the DB or we need to update it
  61578. _this._saveVersionIntoDBAsync(url, versionLoaded);
  61579. };
  61580. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  61581. };
  61582. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  61583. var _this = this;
  61584. if (this.isSupported && this.db) {
  61585. var version;
  61586. try {
  61587. var transaction = this.db.transaction(["versions"]);
  61588. transaction.oncomplete = function (event) {
  61589. if (version) {
  61590. // If the version in the JSON file is > than the version in DB
  61591. if (_this.manifestVersionFound > version.data) {
  61592. _this.mustUpdateRessources = true;
  61593. updateInDBCallback();
  61594. }
  61595. else {
  61596. callback(version.data);
  61597. }
  61598. }
  61599. else {
  61600. _this.mustUpdateRessources = true;
  61601. updateInDBCallback();
  61602. }
  61603. };
  61604. transaction.onabort = function (event) {
  61605. callback(-1);
  61606. };
  61607. var getRequest = transaction.objectStore("versions").get(url);
  61608. getRequest.onsuccess = function (event) {
  61609. version = (event.target).result;
  61610. };
  61611. getRequest.onerror = function (event) {
  61612. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  61613. callback(-1);
  61614. };
  61615. }
  61616. catch (ex) {
  61617. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  61618. callback(-1);
  61619. }
  61620. }
  61621. else {
  61622. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61623. callback(-1);
  61624. }
  61625. };
  61626. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  61627. var _this = this;
  61628. if (this.isSupported && !this.hasReachedQuota && this.db) {
  61629. try {
  61630. // Open a transaction to the database
  61631. var transaction = this.db.transaction(["versions"], "readwrite");
  61632. // the transaction could abort because of a QuotaExceededError error
  61633. transaction.onabort = function (event) {
  61634. try {
  61635. var error = event.srcElement['error'];
  61636. if (error && error.name === "QuotaExceededError") {
  61637. _this.hasReachedQuota = true;
  61638. }
  61639. }
  61640. catch (ex) { }
  61641. callback(-1);
  61642. };
  61643. transaction.oncomplete = function (event) {
  61644. callback(_this.manifestVersionFound);
  61645. };
  61646. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  61647. // Put the scene into the database
  61648. var addRequest = transaction.objectStore("versions").put(newVersion);
  61649. addRequest.onsuccess = function (event) {
  61650. };
  61651. addRequest.onerror = function (event) {
  61652. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  61653. };
  61654. }
  61655. catch (ex) {
  61656. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  61657. callback(-1);
  61658. }
  61659. }
  61660. else {
  61661. callback(-1);
  61662. }
  61663. };
  61664. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  61665. var _this = this;
  61666. var completeUrl = Database.ReturnFullUrlLocation(url);
  61667. var saveAndLoadFile = function () {
  61668. // the scene is not yet in the DB, let's try to save it
  61669. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  61670. };
  61671. this._checkVersionFromDB(completeUrl, function (version) {
  61672. if (version !== -1) {
  61673. if (!_this.mustUpdateRessources) {
  61674. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  61675. }
  61676. else {
  61677. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  61678. }
  61679. }
  61680. else {
  61681. if (errorCallback) {
  61682. errorCallback();
  61683. }
  61684. }
  61685. });
  61686. };
  61687. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  61688. if (this.isSupported && this.db) {
  61689. var targetStore;
  61690. if (url.indexOf(".babylon") !== -1) {
  61691. targetStore = "scenes";
  61692. }
  61693. else {
  61694. targetStore = "textures";
  61695. }
  61696. var file;
  61697. var transaction = this.db.transaction([targetStore]);
  61698. transaction.oncomplete = function (event) {
  61699. if (file) {
  61700. callback(file.data);
  61701. }
  61702. else {
  61703. notInDBCallback();
  61704. }
  61705. };
  61706. transaction.onabort = function (event) {
  61707. notInDBCallback();
  61708. };
  61709. var getRequest = transaction.objectStore(targetStore).get(url);
  61710. getRequest.onsuccess = function (event) {
  61711. file = (event.target).result;
  61712. };
  61713. getRequest.onerror = function (event) {
  61714. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  61715. notInDBCallback();
  61716. };
  61717. }
  61718. else {
  61719. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61720. callback();
  61721. }
  61722. };
  61723. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  61724. var _this = this;
  61725. if (this.isSupported) {
  61726. var targetStore;
  61727. if (url.indexOf(".babylon") !== -1) {
  61728. targetStore = "scenes";
  61729. }
  61730. else {
  61731. targetStore = "textures";
  61732. }
  61733. // Create XHR
  61734. var xhr = new XMLHttpRequest();
  61735. var fileData;
  61736. xhr.open("GET", url, true);
  61737. if (useArrayBuffer) {
  61738. xhr.responseType = "arraybuffer";
  61739. }
  61740. if (progressCallback) {
  61741. xhr.onprogress = progressCallback;
  61742. }
  61743. xhr.addEventListener("load", function () {
  61744. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  61745. // Blob as response (XHR2)
  61746. //fileData = xhr.responseText;
  61747. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  61748. if (!_this.hasReachedQuota && _this.db) {
  61749. // Open a transaction to the database
  61750. var transaction = _this.db.transaction([targetStore], "readwrite");
  61751. // the transaction could abort because of a QuotaExceededError error
  61752. transaction.onabort = function (event) {
  61753. try {
  61754. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61755. var error = event.srcElement['error'];
  61756. if (error && error.name === "QuotaExceededError") {
  61757. _this.hasReachedQuota = true;
  61758. }
  61759. }
  61760. catch (ex) { }
  61761. callback(fileData);
  61762. };
  61763. transaction.oncomplete = function (event) {
  61764. callback(fileData);
  61765. };
  61766. var newFile;
  61767. if (targetStore === "scenes") {
  61768. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  61769. }
  61770. else {
  61771. newFile = { textureUrl: url, data: fileData };
  61772. }
  61773. try {
  61774. // Put the scene into the database
  61775. var addRequest = transaction.objectStore(targetStore).put(newFile);
  61776. addRequest.onsuccess = function (event) {
  61777. };
  61778. addRequest.onerror = function (event) {
  61779. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  61780. };
  61781. }
  61782. catch (ex) {
  61783. callback(fileData);
  61784. }
  61785. }
  61786. else {
  61787. callback(fileData);
  61788. }
  61789. }
  61790. else {
  61791. callback();
  61792. }
  61793. }, false);
  61794. xhr.addEventListener("error", function (event) {
  61795. BABYLON.Tools.Error("error on XHR request.");
  61796. callback();
  61797. }, false);
  61798. xhr.send();
  61799. }
  61800. else {
  61801. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61802. callback();
  61803. }
  61804. };
  61805. Database.IsUASupportingBlobStorage = true;
  61806. Database.IDBStorageEnabled = true;
  61807. Database.parseURL = function (url) {
  61808. var a = document.createElement('a');
  61809. a.href = url;
  61810. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  61811. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  61812. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  61813. return absLocation;
  61814. };
  61815. Database.ReturnFullUrlLocation = function (url) {
  61816. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  61817. return (Database.parseURL(window.location.href) + url);
  61818. }
  61819. else {
  61820. return url;
  61821. }
  61822. };
  61823. return Database;
  61824. }());
  61825. BABYLON.Database = Database;
  61826. })(BABYLON || (BABYLON = {}));
  61827. //# sourceMappingURL=babylon.database.js.map
  61828. var BABYLON;
  61829. (function (BABYLON) {
  61830. var FresnelParameters = /** @class */ (function () {
  61831. function FresnelParameters() {
  61832. this._isEnabled = true;
  61833. this.leftColor = BABYLON.Color3.White();
  61834. this.rightColor = BABYLON.Color3.Black();
  61835. this.bias = 0;
  61836. this.power = 1;
  61837. }
  61838. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  61839. get: function () {
  61840. return this._isEnabled;
  61841. },
  61842. set: function (value) {
  61843. if (this._isEnabled === value) {
  61844. return;
  61845. }
  61846. this._isEnabled = value;
  61847. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  61848. },
  61849. enumerable: true,
  61850. configurable: true
  61851. });
  61852. FresnelParameters.prototype.clone = function () {
  61853. var newFresnelParameters = new FresnelParameters();
  61854. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  61855. return newFresnelParameters;
  61856. };
  61857. FresnelParameters.prototype.serialize = function () {
  61858. var serializationObject = {};
  61859. serializationObject.isEnabled = this.isEnabled;
  61860. serializationObject.leftColor = this.leftColor;
  61861. serializationObject.rightColor = this.rightColor;
  61862. serializationObject.bias = this.bias;
  61863. serializationObject.power = this.power;
  61864. return serializationObject;
  61865. };
  61866. FresnelParameters.Parse = function (parsedFresnelParameters) {
  61867. var fresnelParameters = new FresnelParameters();
  61868. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  61869. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  61870. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  61871. fresnelParameters.bias = parsedFresnelParameters.bias;
  61872. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  61873. return fresnelParameters;
  61874. };
  61875. return FresnelParameters;
  61876. }());
  61877. BABYLON.FresnelParameters = FresnelParameters;
  61878. })(BABYLON || (BABYLON = {}));
  61879. //# sourceMappingURL=babylon.fresnelParameters.js.map
  61880. var BABYLON;
  61881. (function (BABYLON) {
  61882. var MultiMaterial = /** @class */ (function (_super) {
  61883. __extends(MultiMaterial, _super);
  61884. function MultiMaterial(name, scene) {
  61885. var _this = _super.call(this, name, scene, true) || this;
  61886. scene.multiMaterials.push(_this);
  61887. _this.subMaterials = new Array();
  61888. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  61889. return _this;
  61890. }
  61891. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  61892. get: function () {
  61893. return this._subMaterials;
  61894. },
  61895. set: function (value) {
  61896. this._subMaterials = value;
  61897. this._hookArray(value);
  61898. },
  61899. enumerable: true,
  61900. configurable: true
  61901. });
  61902. MultiMaterial.prototype._hookArray = function (array) {
  61903. var _this = this;
  61904. var oldPush = array.push;
  61905. array.push = function () {
  61906. var items = [];
  61907. for (var _i = 0; _i < arguments.length; _i++) {
  61908. items[_i] = arguments[_i];
  61909. }
  61910. var result = oldPush.apply(array, items);
  61911. _this._markAllSubMeshesAsTexturesDirty();
  61912. return result;
  61913. };
  61914. var oldSplice = array.splice;
  61915. array.splice = function (index, deleteCount) {
  61916. var deleted = oldSplice.apply(array, [index, deleteCount]);
  61917. _this._markAllSubMeshesAsTexturesDirty();
  61918. return deleted;
  61919. };
  61920. };
  61921. // Properties
  61922. MultiMaterial.prototype.getSubMaterial = function (index) {
  61923. if (index < 0 || index >= this.subMaterials.length) {
  61924. return this.getScene().defaultMaterial;
  61925. }
  61926. return this.subMaterials[index];
  61927. };
  61928. MultiMaterial.prototype.getActiveTextures = function () {
  61929. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  61930. if (subMaterial) {
  61931. return subMaterial.getActiveTextures();
  61932. }
  61933. else {
  61934. return [];
  61935. }
  61936. }));
  61937. var _a;
  61938. };
  61939. // Methods
  61940. MultiMaterial.prototype.getClassName = function () {
  61941. return "MultiMaterial";
  61942. };
  61943. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  61944. for (var index = 0; index < this.subMaterials.length; index++) {
  61945. var subMaterial = this.subMaterials[index];
  61946. if (subMaterial) {
  61947. if (subMaterial.storeEffectOnSubMeshes) {
  61948. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  61949. return false;
  61950. }
  61951. continue;
  61952. }
  61953. if (!subMaterial.isReady(mesh)) {
  61954. return false;
  61955. }
  61956. }
  61957. }
  61958. return true;
  61959. };
  61960. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  61961. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  61962. for (var index = 0; index < this.subMaterials.length; index++) {
  61963. var subMaterial = null;
  61964. var current = this.subMaterials[index];
  61965. if (cloneChildren && current) {
  61966. subMaterial = current.clone(name + "-" + current.name);
  61967. }
  61968. else {
  61969. subMaterial = this.subMaterials[index];
  61970. }
  61971. newMultiMaterial.subMaterials.push(subMaterial);
  61972. }
  61973. return newMultiMaterial;
  61974. };
  61975. MultiMaterial.prototype.serialize = function () {
  61976. var serializationObject = {};
  61977. serializationObject.name = this.name;
  61978. serializationObject.id = this.id;
  61979. if (BABYLON.Tags) {
  61980. serializationObject.tags = BABYLON.Tags.GetTags(this);
  61981. }
  61982. serializationObject.materials = [];
  61983. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  61984. var subMat = this.subMaterials[matIndex];
  61985. if (subMat) {
  61986. serializationObject.materials.push(subMat.id);
  61987. }
  61988. else {
  61989. serializationObject.materials.push(null);
  61990. }
  61991. }
  61992. return serializationObject;
  61993. };
  61994. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61995. var scene = this.getScene();
  61996. if (!scene) {
  61997. return;
  61998. }
  61999. var index = scene.multiMaterials.indexOf(this);
  62000. if (index >= 0) {
  62001. scene.multiMaterials.splice(index, 1);
  62002. }
  62003. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62004. };
  62005. return MultiMaterial;
  62006. }(BABYLON.Material));
  62007. BABYLON.MultiMaterial = MultiMaterial;
  62008. })(BABYLON || (BABYLON = {}));
  62009. //# sourceMappingURL=babylon.multiMaterial.js.map
  62010. var BABYLON;
  62011. (function (BABYLON) {
  62012. var FreeCameraTouchInput = /** @class */ (function () {
  62013. function FreeCameraTouchInput() {
  62014. this._offsetX = null;
  62015. this._offsetY = null;
  62016. this._pointerPressed = new Array();
  62017. this.touchAngularSensibility = 200000.0;
  62018. this.touchMoveSensibility = 250.0;
  62019. }
  62020. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62021. var _this = this;
  62022. var previousPosition = null;
  62023. if (this._pointerInput === undefined) {
  62024. this._onLostFocus = function (evt) {
  62025. _this._offsetX = null;
  62026. _this._offsetY = null;
  62027. };
  62028. this._pointerInput = function (p, s) {
  62029. var evt = p.event;
  62030. if (evt.pointerType === "mouse") {
  62031. return;
  62032. }
  62033. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  62034. if (!noPreventDefault) {
  62035. evt.preventDefault();
  62036. }
  62037. _this._pointerPressed.push(evt.pointerId);
  62038. if (_this._pointerPressed.length !== 1) {
  62039. return;
  62040. }
  62041. previousPosition = {
  62042. x: evt.clientX,
  62043. y: evt.clientY
  62044. };
  62045. }
  62046. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62047. if (!noPreventDefault) {
  62048. evt.preventDefault();
  62049. }
  62050. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62051. if (index === -1) {
  62052. return;
  62053. }
  62054. _this._pointerPressed.splice(index, 1);
  62055. if (index != 0) {
  62056. return;
  62057. }
  62058. previousPosition = null;
  62059. _this._offsetX = null;
  62060. _this._offsetY = null;
  62061. }
  62062. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62063. if (!noPreventDefault) {
  62064. evt.preventDefault();
  62065. }
  62066. if (!previousPosition) {
  62067. return;
  62068. }
  62069. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62070. if (index != 0) {
  62071. return;
  62072. }
  62073. _this._offsetX = evt.clientX - previousPosition.x;
  62074. _this._offsetY = -(evt.clientY - previousPosition.y);
  62075. }
  62076. };
  62077. }
  62078. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62079. if (this._onLostFocus) {
  62080. element.addEventListener("blur", this._onLostFocus);
  62081. }
  62082. };
  62083. FreeCameraTouchInput.prototype.detachControl = function (element) {
  62084. if (this._pointerInput && element) {
  62085. if (this._observer) {
  62086. this.camera.getScene().onPointerObservable.remove(this._observer);
  62087. this._observer = null;
  62088. }
  62089. if (this._onLostFocus) {
  62090. element.removeEventListener("blur", this._onLostFocus);
  62091. this._onLostFocus = null;
  62092. }
  62093. this._pointerPressed = [];
  62094. this._offsetX = null;
  62095. this._offsetY = null;
  62096. }
  62097. };
  62098. FreeCameraTouchInput.prototype.checkInputs = function () {
  62099. if (this._offsetX && this._offsetY) {
  62100. var camera = this.camera;
  62101. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  62102. if (this._pointerPressed.length > 1) {
  62103. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  62104. }
  62105. else {
  62106. var speed = camera._computeLocalCameraSpeed();
  62107. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  62108. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  62109. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  62110. }
  62111. }
  62112. };
  62113. FreeCameraTouchInput.prototype.getClassName = function () {
  62114. return "FreeCameraTouchInput";
  62115. };
  62116. FreeCameraTouchInput.prototype.getSimpleName = function () {
  62117. return "touch";
  62118. };
  62119. __decorate([
  62120. BABYLON.serialize()
  62121. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  62122. __decorate([
  62123. BABYLON.serialize()
  62124. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  62125. return FreeCameraTouchInput;
  62126. }());
  62127. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  62128. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  62129. })(BABYLON || (BABYLON = {}));
  62130. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  62131. var BABYLON;
  62132. (function (BABYLON) {
  62133. // We're mainly based on the logic defined into the FreeCamera code
  62134. var TouchCamera = /** @class */ (function (_super) {
  62135. __extends(TouchCamera, _super);
  62136. //-- end properties for backward compatibility for inputs
  62137. function TouchCamera(name, position, scene) {
  62138. var _this = _super.call(this, name, position, scene) || this;
  62139. _this.inputs.addTouch();
  62140. _this._setupInputs();
  62141. return _this;
  62142. }
  62143. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  62144. //-- Begin properties for backward compatibility for inputs
  62145. get: function () {
  62146. var touch = this.inputs.attached["touch"];
  62147. if (touch)
  62148. return touch.touchAngularSensibility;
  62149. return 0;
  62150. },
  62151. set: function (value) {
  62152. var touch = this.inputs.attached["touch"];
  62153. if (touch)
  62154. touch.touchAngularSensibility = value;
  62155. },
  62156. enumerable: true,
  62157. configurable: true
  62158. });
  62159. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  62160. get: function () {
  62161. var touch = this.inputs.attached["touch"];
  62162. if (touch)
  62163. return touch.touchMoveSensibility;
  62164. return 0;
  62165. },
  62166. set: function (value) {
  62167. var touch = this.inputs.attached["touch"];
  62168. if (touch)
  62169. touch.touchMoveSensibility = value;
  62170. },
  62171. enumerable: true,
  62172. configurable: true
  62173. });
  62174. TouchCamera.prototype.getClassName = function () {
  62175. return "TouchCamera";
  62176. };
  62177. TouchCamera.prototype._setupInputs = function () {
  62178. var mouse = this.inputs.attached["mouse"];
  62179. if (mouse) {
  62180. mouse.touchEnabled = false;
  62181. }
  62182. };
  62183. return TouchCamera;
  62184. }(BABYLON.FreeCamera));
  62185. BABYLON.TouchCamera = TouchCamera;
  62186. })(BABYLON || (BABYLON = {}));
  62187. //# sourceMappingURL=babylon.touchCamera.js.map
  62188. var BABYLON;
  62189. (function (BABYLON) {
  62190. var ProceduralTexture = /** @class */ (function (_super) {
  62191. __extends(ProceduralTexture, _super);
  62192. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  62193. if (fallbackTexture === void 0) { fallbackTexture = null; }
  62194. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62195. if (isCube === void 0) { isCube = false; }
  62196. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62197. _this.isCube = isCube;
  62198. _this.isEnabled = true;
  62199. _this._currentRefreshId = -1;
  62200. _this._refreshRate = 1;
  62201. _this._vertexBuffers = {};
  62202. _this._uniforms = new Array();
  62203. _this._samplers = new Array();
  62204. _this._textures = {};
  62205. _this._floats = {};
  62206. _this._floatsArrays = {};
  62207. _this._colors3 = {};
  62208. _this._colors4 = {};
  62209. _this._vectors2 = {};
  62210. _this._vectors3 = {};
  62211. _this._matrices = {};
  62212. _this._fallbackTextureUsed = false;
  62213. scene._proceduralTextures.push(_this);
  62214. _this._engine = scene.getEngine();
  62215. _this.name = name;
  62216. _this.isRenderTarget = true;
  62217. _this._size = size;
  62218. _this._generateMipMaps = generateMipMaps;
  62219. _this.setFragment(fragment);
  62220. _this._fallbackTexture = fallbackTexture;
  62221. if (isCube) {
  62222. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  62223. _this.setFloat("face", 0);
  62224. }
  62225. else {
  62226. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  62227. }
  62228. // VBO
  62229. var vertices = [];
  62230. vertices.push(1, 1);
  62231. vertices.push(-1, 1);
  62232. vertices.push(-1, -1);
  62233. vertices.push(1, -1);
  62234. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62235. _this._createIndexBuffer();
  62236. return _this;
  62237. }
  62238. ProceduralTexture.prototype._createIndexBuffer = function () {
  62239. var engine = this._engine;
  62240. // Indices
  62241. var indices = [];
  62242. indices.push(0);
  62243. indices.push(1);
  62244. indices.push(2);
  62245. indices.push(0);
  62246. indices.push(2);
  62247. indices.push(3);
  62248. this._indexBuffer = engine.createIndexBuffer(indices);
  62249. };
  62250. ProceduralTexture.prototype._rebuild = function () {
  62251. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62252. if (vb) {
  62253. vb._rebuild();
  62254. }
  62255. this._createIndexBuffer();
  62256. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62257. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62258. }
  62259. };
  62260. ProceduralTexture.prototype.reset = function () {
  62261. if (this._effect === undefined) {
  62262. return;
  62263. }
  62264. var engine = this._engine;
  62265. engine._releaseEffect(this._effect);
  62266. };
  62267. ProceduralTexture.prototype.isReady = function () {
  62268. var _this = this;
  62269. var engine = this._engine;
  62270. var shaders;
  62271. if (!this._fragment) {
  62272. return false;
  62273. }
  62274. if (this._fallbackTextureUsed) {
  62275. return true;
  62276. }
  62277. if (this._fragment.fragmentElement !== undefined) {
  62278. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  62279. }
  62280. else {
  62281. shaders = { vertex: "procedural", fragment: this._fragment };
  62282. }
  62283. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  62284. _this.releaseInternalTexture();
  62285. if (_this._fallbackTexture) {
  62286. _this._texture = _this._fallbackTexture._texture;
  62287. if (_this._texture) {
  62288. _this._texture.incrementReferences();
  62289. }
  62290. }
  62291. _this._fallbackTextureUsed = true;
  62292. });
  62293. return this._effect.isReady();
  62294. };
  62295. ProceduralTexture.prototype.resetRefreshCounter = function () {
  62296. this._currentRefreshId = -1;
  62297. };
  62298. ProceduralTexture.prototype.setFragment = function (fragment) {
  62299. this._fragment = fragment;
  62300. };
  62301. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  62302. get: function () {
  62303. return this._refreshRate;
  62304. },
  62305. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62306. set: function (value) {
  62307. this._refreshRate = value;
  62308. this.resetRefreshCounter();
  62309. },
  62310. enumerable: true,
  62311. configurable: true
  62312. });
  62313. ProceduralTexture.prototype._shouldRender = function () {
  62314. if (!this.isEnabled || !this.isReady() || !this._texture) {
  62315. return false;
  62316. }
  62317. if (this._fallbackTextureUsed) {
  62318. return false;
  62319. }
  62320. if (this._currentRefreshId === -1) {
  62321. this._currentRefreshId = 1;
  62322. return true;
  62323. }
  62324. if (this.refreshRate === this._currentRefreshId) {
  62325. this._currentRefreshId = 1;
  62326. return true;
  62327. }
  62328. this._currentRefreshId++;
  62329. return false;
  62330. };
  62331. ProceduralTexture.prototype.getRenderSize = function () {
  62332. return this._size;
  62333. };
  62334. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62335. if (this._fallbackTextureUsed) {
  62336. return;
  62337. }
  62338. this.releaseInternalTexture();
  62339. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62340. };
  62341. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62342. if (this._uniforms.indexOf(uniformName) === -1) {
  62343. this._uniforms.push(uniformName);
  62344. }
  62345. };
  62346. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62347. if (this._samplers.indexOf(name) === -1) {
  62348. this._samplers.push(name);
  62349. }
  62350. this._textures[name] = texture;
  62351. return this;
  62352. };
  62353. ProceduralTexture.prototype.setFloat = function (name, value) {
  62354. this._checkUniform(name);
  62355. this._floats[name] = value;
  62356. return this;
  62357. };
  62358. ProceduralTexture.prototype.setFloats = function (name, value) {
  62359. this._checkUniform(name);
  62360. this._floatsArrays[name] = value;
  62361. return this;
  62362. };
  62363. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62364. this._checkUniform(name);
  62365. this._colors3[name] = value;
  62366. return this;
  62367. };
  62368. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62369. this._checkUniform(name);
  62370. this._colors4[name] = value;
  62371. return this;
  62372. };
  62373. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62374. this._checkUniform(name);
  62375. this._vectors2[name] = value;
  62376. return this;
  62377. };
  62378. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62379. this._checkUniform(name);
  62380. this._vectors3[name] = value;
  62381. return this;
  62382. };
  62383. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62384. this._checkUniform(name);
  62385. this._matrices[name] = value;
  62386. return this;
  62387. };
  62388. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62389. var scene = this.getScene();
  62390. if (!scene) {
  62391. return;
  62392. }
  62393. var engine = this._engine;
  62394. // Render
  62395. engine.enableEffect(this._effect);
  62396. engine.setState(false);
  62397. // Texture
  62398. for (var name in this._textures) {
  62399. this._effect.setTexture(name, this._textures[name]);
  62400. }
  62401. // Float
  62402. for (name in this._floats) {
  62403. this._effect.setFloat(name, this._floats[name]);
  62404. }
  62405. // Floats
  62406. for (name in this._floatsArrays) {
  62407. this._effect.setArray(name, this._floatsArrays[name]);
  62408. }
  62409. // Color3
  62410. for (name in this._colors3) {
  62411. this._effect.setColor3(name, this._colors3[name]);
  62412. }
  62413. // Color4
  62414. for (name in this._colors4) {
  62415. var color = this._colors4[name];
  62416. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62417. }
  62418. // Vector2
  62419. for (name in this._vectors2) {
  62420. this._effect.setVector2(name, this._vectors2[name]);
  62421. }
  62422. // Vector3
  62423. for (name in this._vectors3) {
  62424. this._effect.setVector3(name, this._vectors3[name]);
  62425. }
  62426. // Matrix
  62427. for (name in this._matrices) {
  62428. this._effect.setMatrix(name, this._matrices[name]);
  62429. }
  62430. if (!this._texture) {
  62431. return;
  62432. }
  62433. if (this.isCube) {
  62434. for (var face = 0; face < 6; face++) {
  62435. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62436. // VBOs
  62437. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62438. this._effect.setFloat("face", face);
  62439. // Clear
  62440. engine.clear(scene.clearColor, true, true, true);
  62441. // Draw order
  62442. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62443. // Mipmaps
  62444. if (face === 5) {
  62445. engine.generateMipMapsForCubemap(this._texture);
  62446. }
  62447. }
  62448. }
  62449. else {
  62450. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62451. // VBOs
  62452. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62453. // Clear
  62454. engine.clear(scene.clearColor, true, true, true);
  62455. // Draw order
  62456. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62457. }
  62458. // Unbind
  62459. engine.unBindFramebuffer(this._texture, this.isCube);
  62460. if (this.onGenerated) {
  62461. this.onGenerated();
  62462. }
  62463. };
  62464. ProceduralTexture.prototype.clone = function () {
  62465. var textureSize = this.getSize();
  62466. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62467. // Base texture
  62468. newTexture.hasAlpha = this.hasAlpha;
  62469. newTexture.level = this.level;
  62470. // RenderTarget Texture
  62471. newTexture.coordinatesMode = this.coordinatesMode;
  62472. return newTexture;
  62473. };
  62474. ProceduralTexture.prototype.dispose = function () {
  62475. var scene = this.getScene();
  62476. if (!scene) {
  62477. return;
  62478. }
  62479. var index = scene._proceduralTextures.indexOf(this);
  62480. if (index >= 0) {
  62481. scene._proceduralTextures.splice(index, 1);
  62482. }
  62483. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62484. if (vertexBuffer) {
  62485. vertexBuffer.dispose();
  62486. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62487. }
  62488. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62489. this._indexBuffer = null;
  62490. }
  62491. _super.prototype.dispose.call(this);
  62492. };
  62493. return ProceduralTexture;
  62494. }(BABYLON.Texture));
  62495. BABYLON.ProceduralTexture = ProceduralTexture;
  62496. })(BABYLON || (BABYLON = {}));
  62497. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62498. var BABYLON;
  62499. (function (BABYLON) {
  62500. var CustomProceduralTexture = /** @class */ (function (_super) {
  62501. __extends(CustomProceduralTexture, _super);
  62502. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62503. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62504. _this._animate = true;
  62505. _this._time = 0;
  62506. _this._texturePath = texturePath;
  62507. //Try to load json
  62508. _this.loadJson(texturePath);
  62509. _this.refreshRate = 1;
  62510. return _this;
  62511. }
  62512. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62513. var _this = this;
  62514. var noConfigFile = function () {
  62515. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62516. try {
  62517. _this.setFragment(_this._texturePath);
  62518. }
  62519. catch (ex) {
  62520. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62521. }
  62522. };
  62523. var configFileUrl = jsonUrl + "/config.json";
  62524. var xhr = new XMLHttpRequest();
  62525. xhr.open("GET", configFileUrl, true);
  62526. xhr.addEventListener("load", function () {
  62527. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62528. try {
  62529. _this._config = JSON.parse(xhr.response);
  62530. _this.updateShaderUniforms();
  62531. _this.updateTextures();
  62532. _this.setFragment(_this._texturePath + "/custom");
  62533. _this._animate = _this._config.animate;
  62534. _this.refreshRate = _this._config.refreshrate;
  62535. }
  62536. catch (ex) {
  62537. noConfigFile();
  62538. }
  62539. }
  62540. else {
  62541. noConfigFile();
  62542. }
  62543. }, false);
  62544. xhr.addEventListener("error", function () {
  62545. noConfigFile();
  62546. }, false);
  62547. try {
  62548. xhr.send();
  62549. }
  62550. catch (ex) {
  62551. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62552. }
  62553. };
  62554. CustomProceduralTexture.prototype.isReady = function () {
  62555. if (!_super.prototype.isReady.call(this)) {
  62556. return false;
  62557. }
  62558. for (var name in this._textures) {
  62559. var texture = this._textures[name];
  62560. if (!texture.isReady()) {
  62561. return false;
  62562. }
  62563. }
  62564. return true;
  62565. };
  62566. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62567. var scene = this.getScene();
  62568. if (this._animate && scene) {
  62569. this._time += scene.getAnimationRatio() * 0.03;
  62570. this.updateShaderUniforms();
  62571. }
  62572. _super.prototype.render.call(this, useCameraPostProcess);
  62573. };
  62574. CustomProceduralTexture.prototype.updateTextures = function () {
  62575. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62576. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  62577. }
  62578. };
  62579. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  62580. if (this._config) {
  62581. for (var j = 0; j < this._config.uniforms.length; j++) {
  62582. var uniform = this._config.uniforms[j];
  62583. switch (uniform.type) {
  62584. case "float":
  62585. this.setFloat(uniform.name, uniform.value);
  62586. break;
  62587. case "color3":
  62588. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  62589. break;
  62590. case "color4":
  62591. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  62592. break;
  62593. case "vector2":
  62594. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  62595. break;
  62596. case "vector3":
  62597. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  62598. break;
  62599. }
  62600. }
  62601. }
  62602. this.setFloat("time", this._time);
  62603. };
  62604. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  62605. get: function () {
  62606. return this._animate;
  62607. },
  62608. set: function (value) {
  62609. this._animate = value;
  62610. },
  62611. enumerable: true,
  62612. configurable: true
  62613. });
  62614. return CustomProceduralTexture;
  62615. }(BABYLON.ProceduralTexture));
  62616. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  62617. })(BABYLON || (BABYLON = {}));
  62618. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  62619. var BABYLON;
  62620. (function (BABYLON) {
  62621. var FreeCameraGamepadInput = /** @class */ (function () {
  62622. function FreeCameraGamepadInput() {
  62623. this.gamepadAngularSensibility = 200;
  62624. this.gamepadMoveSensibility = 40;
  62625. // private members
  62626. this._cameraTransform = BABYLON.Matrix.Identity();
  62627. this._deltaTransform = BABYLON.Vector3.Zero();
  62628. this._vector3 = BABYLON.Vector3.Zero();
  62629. this._vector2 = BABYLON.Vector2.Zero();
  62630. }
  62631. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62632. var _this = this;
  62633. var manager = this.camera.getScene().gamepadManager;
  62634. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62635. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62636. // prioritize XBOX gamepads.
  62637. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62638. _this.gamepad = gamepad;
  62639. }
  62640. }
  62641. });
  62642. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62643. if (_this.gamepad === gamepad) {
  62644. _this.gamepad = null;
  62645. }
  62646. });
  62647. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62648. };
  62649. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  62650. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62651. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62652. this.gamepad = null;
  62653. };
  62654. FreeCameraGamepadInput.prototype.checkInputs = function () {
  62655. if (this.gamepad && this.gamepad.leftStick) {
  62656. var camera = this.camera;
  62657. var LSValues = this.gamepad.leftStick;
  62658. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  62659. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62660. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  62661. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  62662. var RSValues = this.gamepad.rightStick;
  62663. if (RSValues) {
  62664. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  62665. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  62666. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  62667. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  62668. }
  62669. else {
  62670. RSValues = { x: 0, y: 0 };
  62671. }
  62672. if (!camera.rotationQuaternion) {
  62673. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  62674. }
  62675. else {
  62676. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  62677. }
  62678. var speed = camera._computeLocalCameraSpeed() * 50.0;
  62679. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  62680. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  62681. camera.cameraDirection.addInPlace(this._deltaTransform);
  62682. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  62683. camera.cameraRotation.addInPlace(this._vector2);
  62684. }
  62685. };
  62686. FreeCameraGamepadInput.prototype.getClassName = function () {
  62687. return "FreeCameraGamepadInput";
  62688. };
  62689. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  62690. return "gamepad";
  62691. };
  62692. __decorate([
  62693. BABYLON.serialize()
  62694. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  62695. __decorate([
  62696. BABYLON.serialize()
  62697. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62698. return FreeCameraGamepadInput;
  62699. }());
  62700. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  62701. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  62702. })(BABYLON || (BABYLON = {}));
  62703. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  62704. var BABYLON;
  62705. (function (BABYLON) {
  62706. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  62707. function ArcRotateCameraGamepadInput() {
  62708. this.gamepadRotationSensibility = 80;
  62709. this.gamepadMoveSensibility = 40;
  62710. }
  62711. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  62712. var _this = this;
  62713. var manager = this.camera.getScene().gamepadManager;
  62714. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  62715. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  62716. // prioritize XBOX gamepads.
  62717. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  62718. _this.gamepad = gamepad;
  62719. }
  62720. }
  62721. });
  62722. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  62723. if (_this.gamepad === gamepad) {
  62724. _this.gamepad = null;
  62725. }
  62726. });
  62727. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  62728. };
  62729. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  62730. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  62731. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  62732. this.gamepad = null;
  62733. };
  62734. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  62735. if (this.gamepad) {
  62736. var camera = this.camera;
  62737. var RSValues = this.gamepad.rightStick;
  62738. if (RSValues) {
  62739. if (RSValues.x != 0) {
  62740. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  62741. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  62742. camera.inertialAlphaOffset += normalizedRX;
  62743. }
  62744. }
  62745. if (RSValues.y != 0) {
  62746. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  62747. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  62748. camera.inertialBetaOffset += normalizedRY;
  62749. }
  62750. }
  62751. }
  62752. var LSValues = this.gamepad.leftStick;
  62753. if (LSValues && LSValues.y != 0) {
  62754. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  62755. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  62756. this.camera.inertialRadiusOffset -= normalizedLY;
  62757. }
  62758. }
  62759. }
  62760. };
  62761. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  62762. return "ArcRotateCameraGamepadInput";
  62763. };
  62764. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  62765. return "gamepad";
  62766. };
  62767. __decorate([
  62768. BABYLON.serialize()
  62769. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  62770. __decorate([
  62771. BABYLON.serialize()
  62772. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  62773. return ArcRotateCameraGamepadInput;
  62774. }());
  62775. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  62776. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  62777. })(BABYLON || (BABYLON = {}));
  62778. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  62779. var BABYLON;
  62780. (function (BABYLON) {
  62781. var GamepadManager = /** @class */ (function () {
  62782. function GamepadManager(_scene) {
  62783. var _this = this;
  62784. this._scene = _scene;
  62785. this._babylonGamepads = [];
  62786. this._oneGamepadConnected = false;
  62787. this._isMonitoring = false;
  62788. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  62789. if (!BABYLON.Tools.IsWindowObjectExist()) {
  62790. this._gamepadEventSupported = false;
  62791. }
  62792. else {
  62793. this._gamepadEventSupported = 'GamepadEvent' in window;
  62794. this._gamepadSupport = (navigator.getGamepads ||
  62795. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  62796. }
  62797. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  62798. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  62799. for (var i in _this._babylonGamepads) {
  62800. var gamepad = _this._babylonGamepads[i];
  62801. if (gamepad && gamepad._isConnected) {
  62802. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  62803. }
  62804. }
  62805. });
  62806. this._onGamepadConnectedEvent = function (evt) {
  62807. var gamepad = evt.gamepad;
  62808. if (gamepad.index in _this._babylonGamepads) {
  62809. if (_this._babylonGamepads[gamepad.index].isConnected) {
  62810. return;
  62811. }
  62812. }
  62813. var newGamepad;
  62814. if (_this._babylonGamepads[gamepad.index]) {
  62815. newGamepad = _this._babylonGamepads[gamepad.index];
  62816. newGamepad.browserGamepad = gamepad;
  62817. newGamepad._isConnected = true;
  62818. }
  62819. else {
  62820. newGamepad = _this._addNewGamepad(gamepad);
  62821. }
  62822. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62823. _this._startMonitoringGamepads();
  62824. };
  62825. this._onGamepadDisconnectedEvent = function (evt) {
  62826. var gamepad = evt.gamepad;
  62827. // Remove the gamepad from the list of gamepads to monitor.
  62828. for (var i in _this._babylonGamepads) {
  62829. if (_this._babylonGamepads[i].index === gamepad.index) {
  62830. var disconnectedGamepad = _this._babylonGamepads[i];
  62831. disconnectedGamepad._isConnected = false;
  62832. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  62833. break;
  62834. }
  62835. }
  62836. };
  62837. if (this._gamepadSupport) {
  62838. //first add already-connected gamepads
  62839. this._updateGamepadObjects();
  62840. if (this._babylonGamepads.length) {
  62841. this._startMonitoringGamepads();
  62842. }
  62843. // Checking if the gamepad connected event is supported (like in Firefox)
  62844. if (this._gamepadEventSupported) {
  62845. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  62846. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  62847. }
  62848. else {
  62849. this._startMonitoringGamepads();
  62850. }
  62851. }
  62852. }
  62853. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  62854. get: function () {
  62855. return this._babylonGamepads;
  62856. },
  62857. enumerable: true,
  62858. configurable: true
  62859. });
  62860. GamepadManager.prototype.getGamepadByType = function (type) {
  62861. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  62862. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  62863. var gamepad = _a[_i];
  62864. if (gamepad && gamepad.type === type) {
  62865. return gamepad;
  62866. }
  62867. }
  62868. return null;
  62869. };
  62870. GamepadManager.prototype.dispose = function () {
  62871. if (this._gamepadEventSupported) {
  62872. if (this._onGamepadConnectedEvent) {
  62873. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  62874. }
  62875. if (this._onGamepadDisconnectedEvent) {
  62876. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  62877. }
  62878. this._onGamepadConnectedEvent = null;
  62879. this._onGamepadDisconnectedEvent = null;
  62880. }
  62881. this._babylonGamepads.forEach(function (gamepad) {
  62882. gamepad.dispose();
  62883. });
  62884. this.onGamepadConnectedObservable.clear();
  62885. this.onGamepadDisconnectedObservable.clear();
  62886. this._oneGamepadConnected = false;
  62887. this._stopMonitoringGamepads();
  62888. this._babylonGamepads = [];
  62889. };
  62890. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  62891. if (!this._oneGamepadConnected) {
  62892. this._oneGamepadConnected = true;
  62893. }
  62894. var newGamepad;
  62895. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  62896. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  62897. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  62898. }
  62899. else if (gamepad.pose) {
  62900. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  62901. }
  62902. else {
  62903. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  62904. }
  62905. this._babylonGamepads[newGamepad.index] = newGamepad;
  62906. return newGamepad;
  62907. };
  62908. GamepadManager.prototype._startMonitoringGamepads = function () {
  62909. if (!this._isMonitoring) {
  62910. this._isMonitoring = true;
  62911. //back-comp
  62912. if (!this._scene) {
  62913. this._checkGamepadsStatus();
  62914. }
  62915. }
  62916. };
  62917. GamepadManager.prototype._stopMonitoringGamepads = function () {
  62918. this._isMonitoring = false;
  62919. };
  62920. GamepadManager.prototype._checkGamepadsStatus = function () {
  62921. var _this = this;
  62922. // Hack to be compatible Chrome
  62923. this._updateGamepadObjects();
  62924. for (var i in this._babylonGamepads) {
  62925. var gamepad = this._babylonGamepads[i];
  62926. if (!gamepad || !gamepad.isConnected) {
  62927. continue;
  62928. }
  62929. gamepad.update();
  62930. }
  62931. if (this._isMonitoring && !this._scene) {
  62932. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  62933. }
  62934. };
  62935. // This function is called only on Chrome, which does not properly support
  62936. // connection/disconnection events and forces you to recopy again the gamepad object
  62937. GamepadManager.prototype._updateGamepadObjects = function () {
  62938. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  62939. for (var i = 0; i < gamepads.length; i++) {
  62940. if (gamepads[i]) {
  62941. if (!this._babylonGamepads[gamepads[i].index]) {
  62942. var newGamepad = this._addNewGamepad(gamepads[i]);
  62943. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  62944. }
  62945. else {
  62946. // Forced to copy again this object for Chrome for unknown reason
  62947. this._babylonGamepads[i].browserGamepad = gamepads[i];
  62948. if (!this._babylonGamepads[i].isConnected) {
  62949. this._babylonGamepads[i]._isConnected = true;
  62950. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  62951. }
  62952. }
  62953. }
  62954. }
  62955. };
  62956. return GamepadManager;
  62957. }());
  62958. BABYLON.GamepadManager = GamepadManager;
  62959. })(BABYLON || (BABYLON = {}));
  62960. //# sourceMappingURL=babylon.gamepadManager.js.map
  62961. var BABYLON;
  62962. (function (BABYLON) {
  62963. var StickValues = /** @class */ (function () {
  62964. function StickValues(x, y) {
  62965. this.x = x;
  62966. this.y = y;
  62967. }
  62968. return StickValues;
  62969. }());
  62970. BABYLON.StickValues = StickValues;
  62971. var Gamepad = /** @class */ (function () {
  62972. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  62973. if (leftStickX === void 0) { leftStickX = 0; }
  62974. if (leftStickY === void 0) { leftStickY = 1; }
  62975. if (rightStickX === void 0) { rightStickX = 2; }
  62976. if (rightStickY === void 0) { rightStickY = 3; }
  62977. this.id = id;
  62978. this.index = index;
  62979. this.browserGamepad = browserGamepad;
  62980. this._isConnected = true;
  62981. this._invertLeftStickY = false;
  62982. this.type = Gamepad.GAMEPAD;
  62983. this._leftStickAxisX = leftStickX;
  62984. this._leftStickAxisY = leftStickY;
  62985. this._rightStickAxisX = rightStickX;
  62986. this._rightStickAxisY = rightStickY;
  62987. if (this.browserGamepad.axes.length >= 2) {
  62988. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  62989. }
  62990. if (this.browserGamepad.axes.length >= 4) {
  62991. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  62992. }
  62993. }
  62994. Object.defineProperty(Gamepad.prototype, "isConnected", {
  62995. get: function () {
  62996. return this._isConnected;
  62997. },
  62998. enumerable: true,
  62999. configurable: true
  63000. });
  63001. Gamepad.prototype.onleftstickchanged = function (callback) {
  63002. this._onleftstickchanged = callback;
  63003. };
  63004. Gamepad.prototype.onrightstickchanged = function (callback) {
  63005. this._onrightstickchanged = callback;
  63006. };
  63007. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63008. get: function () {
  63009. return this._leftStick;
  63010. },
  63011. set: function (newValues) {
  63012. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63013. this._onleftstickchanged(newValues);
  63014. }
  63015. this._leftStick = newValues;
  63016. },
  63017. enumerable: true,
  63018. configurable: true
  63019. });
  63020. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63021. get: function () {
  63022. return this._rightStick;
  63023. },
  63024. set: function (newValues) {
  63025. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  63026. this._onrightstickchanged(newValues);
  63027. }
  63028. this._rightStick = newValues;
  63029. },
  63030. enumerable: true,
  63031. configurable: true
  63032. });
  63033. Gamepad.prototype.update = function () {
  63034. if (this._leftStick) {
  63035. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63036. if (this._invertLeftStickY) {
  63037. this.leftStick.y *= -1;
  63038. }
  63039. }
  63040. if (this._rightStick) {
  63041. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63042. }
  63043. };
  63044. Gamepad.prototype.dispose = function () {
  63045. };
  63046. Gamepad.GAMEPAD = 0;
  63047. Gamepad.GENERIC = 1;
  63048. Gamepad.XBOX = 2;
  63049. Gamepad.POSE_ENABLED = 3;
  63050. return Gamepad;
  63051. }());
  63052. BABYLON.Gamepad = Gamepad;
  63053. var GenericPad = /** @class */ (function (_super) {
  63054. __extends(GenericPad, _super);
  63055. function GenericPad(id, index, browserGamepad) {
  63056. var _this = _super.call(this, id, index, browserGamepad) || this;
  63057. _this.onButtonDownObservable = new BABYLON.Observable();
  63058. _this.onButtonUpObservable = new BABYLON.Observable();
  63059. _this.type = Gamepad.GENERIC;
  63060. _this._buttons = new Array(browserGamepad.buttons.length);
  63061. return _this;
  63062. }
  63063. GenericPad.prototype.onbuttondown = function (callback) {
  63064. this._onbuttondown = callback;
  63065. };
  63066. GenericPad.prototype.onbuttonup = function (callback) {
  63067. this._onbuttonup = callback;
  63068. };
  63069. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63070. if (newValue !== currentValue) {
  63071. if (newValue === 1) {
  63072. if (this._onbuttondown) {
  63073. this._onbuttondown(buttonIndex);
  63074. }
  63075. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63076. }
  63077. if (newValue === 0) {
  63078. if (this._onbuttonup) {
  63079. this._onbuttonup(buttonIndex);
  63080. }
  63081. this.onButtonUpObservable.notifyObservers(buttonIndex);
  63082. }
  63083. }
  63084. return newValue;
  63085. };
  63086. GenericPad.prototype.update = function () {
  63087. _super.prototype.update.call(this);
  63088. for (var index = 0; index < this._buttons.length; index++) {
  63089. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  63090. }
  63091. };
  63092. GenericPad.prototype.dispose = function () {
  63093. _super.prototype.dispose.call(this);
  63094. this.onButtonDownObservable.clear();
  63095. this.onButtonUpObservable.clear();
  63096. };
  63097. return GenericPad;
  63098. }(Gamepad));
  63099. BABYLON.GenericPad = GenericPad;
  63100. })(BABYLON || (BABYLON = {}));
  63101. //# sourceMappingURL=babylon.gamepad.js.map
  63102. var BABYLON;
  63103. (function (BABYLON) {
  63104. var Xbox360Button;
  63105. (function (Xbox360Button) {
  63106. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  63107. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  63108. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  63109. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  63110. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  63111. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  63112. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  63113. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  63114. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  63115. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  63116. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  63117. var Xbox360Dpad;
  63118. (function (Xbox360Dpad) {
  63119. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  63120. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  63121. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  63122. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  63123. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  63124. var Xbox360Pad = /** @class */ (function (_super) {
  63125. __extends(Xbox360Pad, _super);
  63126. function Xbox360Pad(id, index, gamepad, xboxOne) {
  63127. if (xboxOne === void 0) { xboxOne = false; }
  63128. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  63129. _this._leftTrigger = 0;
  63130. _this._rightTrigger = 0;
  63131. _this.onButtonDownObservable = new BABYLON.Observable();
  63132. _this.onButtonUpObservable = new BABYLON.Observable();
  63133. _this.onPadDownObservable = new BABYLON.Observable();
  63134. _this.onPadUpObservable = new BABYLON.Observable();
  63135. _this._buttonA = 0;
  63136. _this._buttonB = 0;
  63137. _this._buttonX = 0;
  63138. _this._buttonY = 0;
  63139. _this._buttonBack = 0;
  63140. _this._buttonStart = 0;
  63141. _this._buttonLB = 0;
  63142. _this._buttonRB = 0;
  63143. _this._buttonLeftStick = 0;
  63144. _this._buttonRightStick = 0;
  63145. _this._dPadUp = 0;
  63146. _this._dPadDown = 0;
  63147. _this._dPadLeft = 0;
  63148. _this._dPadRight = 0;
  63149. _this._isXboxOnePad = false;
  63150. _this.type = BABYLON.Gamepad.XBOX;
  63151. _this._isXboxOnePad = xboxOne;
  63152. return _this;
  63153. }
  63154. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  63155. this._onlefttriggerchanged = callback;
  63156. };
  63157. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  63158. this._onrighttriggerchanged = callback;
  63159. };
  63160. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  63161. get: function () {
  63162. return this._leftTrigger;
  63163. },
  63164. set: function (newValue) {
  63165. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  63166. this._onlefttriggerchanged(newValue);
  63167. }
  63168. this._leftTrigger = newValue;
  63169. },
  63170. enumerable: true,
  63171. configurable: true
  63172. });
  63173. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  63174. get: function () {
  63175. return this._rightTrigger;
  63176. },
  63177. set: function (newValue) {
  63178. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  63179. this._onrighttriggerchanged(newValue);
  63180. }
  63181. this._rightTrigger = newValue;
  63182. },
  63183. enumerable: true,
  63184. configurable: true
  63185. });
  63186. Xbox360Pad.prototype.onbuttondown = function (callback) {
  63187. this._onbuttondown = callback;
  63188. };
  63189. Xbox360Pad.prototype.onbuttonup = function (callback) {
  63190. this._onbuttonup = callback;
  63191. };
  63192. Xbox360Pad.prototype.ondpaddown = function (callback) {
  63193. this._ondpaddown = callback;
  63194. };
  63195. Xbox360Pad.prototype.ondpadup = function (callback) {
  63196. this._ondpadup = callback;
  63197. };
  63198. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63199. if (newValue !== currentValue) {
  63200. if (newValue === 1) {
  63201. if (this._onbuttondown) {
  63202. this._onbuttondown(buttonType);
  63203. }
  63204. this.onButtonDownObservable.notifyObservers(buttonType);
  63205. }
  63206. if (newValue === 0) {
  63207. if (this._onbuttonup) {
  63208. this._onbuttonup(buttonType);
  63209. }
  63210. this.onButtonUpObservable.notifyObservers(buttonType);
  63211. }
  63212. }
  63213. return newValue;
  63214. };
  63215. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  63216. if (newValue !== currentValue) {
  63217. if (newValue === 1) {
  63218. if (this._ondpaddown) {
  63219. this._ondpaddown(buttonType);
  63220. }
  63221. this.onPadDownObservable.notifyObservers(buttonType);
  63222. }
  63223. if (newValue === 0) {
  63224. if (this._ondpadup) {
  63225. this._ondpadup(buttonType);
  63226. }
  63227. this.onPadUpObservable.notifyObservers(buttonType);
  63228. }
  63229. }
  63230. return newValue;
  63231. };
  63232. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  63233. get: function () {
  63234. return this._buttonA;
  63235. },
  63236. set: function (value) {
  63237. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  63238. },
  63239. enumerable: true,
  63240. configurable: true
  63241. });
  63242. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63243. get: function () {
  63244. return this._buttonB;
  63245. },
  63246. set: function (value) {
  63247. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63248. },
  63249. enumerable: true,
  63250. configurable: true
  63251. });
  63252. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  63253. get: function () {
  63254. return this._buttonX;
  63255. },
  63256. set: function (value) {
  63257. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  63258. },
  63259. enumerable: true,
  63260. configurable: true
  63261. });
  63262. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  63263. get: function () {
  63264. return this._buttonY;
  63265. },
  63266. set: function (value) {
  63267. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  63268. },
  63269. enumerable: true,
  63270. configurable: true
  63271. });
  63272. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  63273. get: function () {
  63274. return this._buttonStart;
  63275. },
  63276. set: function (value) {
  63277. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  63278. },
  63279. enumerable: true,
  63280. configurable: true
  63281. });
  63282. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  63283. get: function () {
  63284. return this._buttonBack;
  63285. },
  63286. set: function (value) {
  63287. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  63288. },
  63289. enumerable: true,
  63290. configurable: true
  63291. });
  63292. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  63293. get: function () {
  63294. return this._buttonLB;
  63295. },
  63296. set: function (value) {
  63297. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  63298. },
  63299. enumerable: true,
  63300. configurable: true
  63301. });
  63302. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  63303. get: function () {
  63304. return this._buttonRB;
  63305. },
  63306. set: function (value) {
  63307. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  63308. },
  63309. enumerable: true,
  63310. configurable: true
  63311. });
  63312. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  63313. get: function () {
  63314. return this._buttonLeftStick;
  63315. },
  63316. set: function (value) {
  63317. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  63318. },
  63319. enumerable: true,
  63320. configurable: true
  63321. });
  63322. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63323. get: function () {
  63324. return this._buttonRightStick;
  63325. },
  63326. set: function (value) {
  63327. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63328. },
  63329. enumerable: true,
  63330. configurable: true
  63331. });
  63332. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63333. get: function () {
  63334. return this._dPadUp;
  63335. },
  63336. set: function (value) {
  63337. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63338. },
  63339. enumerable: true,
  63340. configurable: true
  63341. });
  63342. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63343. get: function () {
  63344. return this._dPadDown;
  63345. },
  63346. set: function (value) {
  63347. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63348. },
  63349. enumerable: true,
  63350. configurable: true
  63351. });
  63352. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63353. get: function () {
  63354. return this._dPadLeft;
  63355. },
  63356. set: function (value) {
  63357. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63358. },
  63359. enumerable: true,
  63360. configurable: true
  63361. });
  63362. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63363. get: function () {
  63364. return this._dPadRight;
  63365. },
  63366. set: function (value) {
  63367. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63368. },
  63369. enumerable: true,
  63370. configurable: true
  63371. });
  63372. Xbox360Pad.prototype.update = function () {
  63373. _super.prototype.update.call(this);
  63374. if (this._isXboxOnePad) {
  63375. this.buttonA = this.browserGamepad.buttons[0].value;
  63376. this.buttonB = this.browserGamepad.buttons[1].value;
  63377. this.buttonX = this.browserGamepad.buttons[2].value;
  63378. this.buttonY = this.browserGamepad.buttons[3].value;
  63379. this.buttonLB = this.browserGamepad.buttons[4].value;
  63380. this.buttonRB = this.browserGamepad.buttons[5].value;
  63381. this.leftTrigger = this.browserGamepad.axes[2];
  63382. this.rightTrigger = this.browserGamepad.axes[5];
  63383. this.buttonBack = this.browserGamepad.buttons[9].value;
  63384. this.buttonStart = this.browserGamepad.buttons[8].value;
  63385. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63386. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63387. this.dPadUp = this.browserGamepad.buttons[11].value;
  63388. this.dPadDown = this.browserGamepad.buttons[12].value;
  63389. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63390. this.dPadRight = this.browserGamepad.buttons[14].value;
  63391. }
  63392. else {
  63393. this.buttonA = this.browserGamepad.buttons[0].value;
  63394. this.buttonB = this.browserGamepad.buttons[1].value;
  63395. this.buttonX = this.browserGamepad.buttons[2].value;
  63396. this.buttonY = this.browserGamepad.buttons[3].value;
  63397. this.buttonLB = this.browserGamepad.buttons[4].value;
  63398. this.buttonRB = this.browserGamepad.buttons[5].value;
  63399. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63400. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63401. this.buttonBack = this.browserGamepad.buttons[8].value;
  63402. this.buttonStart = this.browserGamepad.buttons[9].value;
  63403. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63404. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63405. this.dPadUp = this.browserGamepad.buttons[12].value;
  63406. this.dPadDown = this.browserGamepad.buttons[13].value;
  63407. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63408. this.dPadRight = this.browserGamepad.buttons[15].value;
  63409. }
  63410. };
  63411. Xbox360Pad.prototype.dispose = function () {
  63412. _super.prototype.dispose.call(this);
  63413. this.onButtonDownObservable.clear();
  63414. this.onButtonUpObservable.clear();
  63415. this.onPadDownObservable.clear();
  63416. this.onPadUpObservable.clear();
  63417. };
  63418. return Xbox360Pad;
  63419. }(BABYLON.Gamepad));
  63420. BABYLON.Xbox360Pad = Xbox360Pad;
  63421. })(BABYLON || (BABYLON = {}));
  63422. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63423. var BABYLON;
  63424. (function (BABYLON) {
  63425. var PoseEnabledControllerType;
  63426. (function (PoseEnabledControllerType) {
  63427. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63428. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63429. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63430. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63431. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63432. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63433. var PoseEnabledControllerHelper = /** @class */ (function () {
  63434. function PoseEnabledControllerHelper() {
  63435. }
  63436. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63437. // Oculus Touch
  63438. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63439. return new BABYLON.OculusTouchController(vrGamepad);
  63440. }
  63441. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63442. return new BABYLON.WindowsMotionController(vrGamepad);
  63443. }
  63444. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63445. return new BABYLON.ViveController(vrGamepad);
  63446. }
  63447. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63448. return new BABYLON.GearVRController(vrGamepad);
  63449. }
  63450. else {
  63451. return new BABYLON.GenericController(vrGamepad);
  63452. }
  63453. };
  63454. return PoseEnabledControllerHelper;
  63455. }());
  63456. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63457. var PoseEnabledController = /** @class */ (function (_super) {
  63458. __extends(PoseEnabledController, _super);
  63459. function PoseEnabledController(browserGamepad) {
  63460. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63461. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63462. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63463. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63464. // Represents device position and rotation in babylon space
  63465. _this.devicePosition = BABYLON.Vector3.Zero();
  63466. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63467. _this.deviceScaleFactor = 1;
  63468. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63469. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63470. _this._workingMatrix = BABYLON.Matrix.Identity();
  63471. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63472. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63473. _this.position = BABYLON.Vector3.Zero();
  63474. _this.rotationQuaternion = new BABYLON.Quaternion();
  63475. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63476. _this._calculatedRotation = new BABYLON.Quaternion();
  63477. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63478. return _this;
  63479. }
  63480. PoseEnabledController.prototype.update = function () {
  63481. _super.prototype.update.call(this);
  63482. var pose = this.browserGamepad.pose;
  63483. this.updateFromDevice(pose);
  63484. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63485. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63486. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63487. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63488. if (this._mesh) {
  63489. this._mesh.position.copyFrom(this.devicePosition);
  63490. if (this._mesh.rotationQuaternion) {
  63491. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63492. }
  63493. }
  63494. };
  63495. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63496. if (poseData) {
  63497. this.rawPose = poseData;
  63498. if (poseData.position) {
  63499. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63500. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63501. this._deviceRoomPosition.z *= -1;
  63502. }
  63503. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63504. this._calculatedPosition.addInPlace(this.position);
  63505. }
  63506. var pose = this.rawPose;
  63507. if (poseData.orientation && pose.orientation) {
  63508. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63509. if (this._mesh) {
  63510. if (this._mesh.getScene().useRightHandedSystem) {
  63511. this._deviceRoomRotationQuaternion.z *= -1;
  63512. this._deviceRoomRotationQuaternion.w *= -1;
  63513. }
  63514. else {
  63515. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63516. }
  63517. }
  63518. // if the camera is set, rotate to the camera's rotation
  63519. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63520. }
  63521. }
  63522. };
  63523. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63524. if (this._mesh) {
  63525. this._mesh.parent = null;
  63526. }
  63527. this._mesh = mesh;
  63528. if (this._poseControlledCamera) {
  63529. this._mesh.parent = this._poseControlledCamera;
  63530. }
  63531. if (!this._mesh.rotationQuaternion) {
  63532. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63533. }
  63534. };
  63535. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63536. this._poseControlledCamera = camera;
  63537. if (this._mesh) {
  63538. this._mesh.parent = this._poseControlledCamera;
  63539. }
  63540. };
  63541. PoseEnabledController.prototype.dispose = function () {
  63542. if (this._mesh) {
  63543. this._mesh.dispose();
  63544. }
  63545. this._mesh = null;
  63546. _super.prototype.dispose.call(this);
  63547. };
  63548. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63549. get: function () {
  63550. return this._mesh;
  63551. },
  63552. enumerable: true,
  63553. configurable: true
  63554. });
  63555. PoseEnabledController.prototype.getForwardRay = function (length) {
  63556. if (length === void 0) { length = 100; }
  63557. if (!this.mesh) {
  63558. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63559. }
  63560. var m = this.mesh.getWorldMatrix();
  63561. var origin = m.getTranslation();
  63562. var forward = new BABYLON.Vector3(0, 0, -1);
  63563. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63564. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63565. return new BABYLON.Ray(origin, direction, length);
  63566. };
  63567. return PoseEnabledController;
  63568. }(BABYLON.Gamepad));
  63569. BABYLON.PoseEnabledController = PoseEnabledController;
  63570. })(BABYLON || (BABYLON = {}));
  63571. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63572. var BABYLON;
  63573. (function (BABYLON) {
  63574. var WebVRController = /** @class */ (function (_super) {
  63575. __extends(WebVRController, _super);
  63576. function WebVRController(vrGamepad) {
  63577. var _this = _super.call(this, vrGamepad) || this;
  63578. // Observables
  63579. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  63580. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  63581. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  63582. _this.onPadStateChangedObservable = new BABYLON.Observable();
  63583. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  63584. _this.pad = { x: 0, y: 0 };
  63585. // avoid GC, store state in a tmp object
  63586. _this._changes = {
  63587. pressChanged: false,
  63588. touchChanged: false,
  63589. valueChanged: false,
  63590. changed: false
  63591. };
  63592. _this._buttons = new Array(vrGamepad.buttons.length);
  63593. _this.hand = vrGamepad.hand;
  63594. return _this;
  63595. }
  63596. WebVRController.prototype.onButtonStateChange = function (callback) {
  63597. this._onButtonStateChange = callback;
  63598. };
  63599. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  63600. get: function () {
  63601. return this._defaultModel;
  63602. },
  63603. enumerable: true,
  63604. configurable: true
  63605. });
  63606. WebVRController.prototype.update = function () {
  63607. _super.prototype.update.call(this);
  63608. for (var index = 0; index < this._buttons.length; index++) {
  63609. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  63610. }
  63611. ;
  63612. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  63613. this.pad.x = this.leftStick.x;
  63614. this.pad.y = this.leftStick.y;
  63615. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  63616. }
  63617. };
  63618. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  63619. if (!newState) {
  63620. newState = {
  63621. pressed: false,
  63622. touched: false,
  63623. value: 0
  63624. };
  63625. }
  63626. if (!currentState) {
  63627. this._buttons[buttonIndex] = {
  63628. pressed: newState.pressed,
  63629. touched: newState.touched,
  63630. value: newState.value
  63631. };
  63632. return;
  63633. }
  63634. this._checkChanges(newState, currentState);
  63635. if (this._changes.changed) {
  63636. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  63637. this.handleButtonChange(buttonIndex, newState, this._changes);
  63638. }
  63639. this._buttons[buttonIndex].pressed = newState.pressed;
  63640. this._buttons[buttonIndex].touched = newState.touched;
  63641. // oculus triggers are never 0, thou not touched.
  63642. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  63643. };
  63644. WebVRController.prototype._checkChanges = function (newState, currentState) {
  63645. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  63646. this._changes.touchChanged = newState.touched !== currentState.touched;
  63647. this._changes.valueChanged = newState.value !== currentState.value;
  63648. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  63649. return this._changes;
  63650. };
  63651. WebVRController.prototype.dispose = function () {
  63652. _super.prototype.dispose.call(this);
  63653. this.onTriggerStateChangedObservable.clear();
  63654. this.onMainButtonStateChangedObservable.clear();
  63655. this.onSecondaryButtonStateChangedObservable.clear();
  63656. this.onPadStateChangedObservable.clear();
  63657. this.onPadValuesChangedObservable.clear();
  63658. };
  63659. return WebVRController;
  63660. }(BABYLON.PoseEnabledController));
  63661. BABYLON.WebVRController = WebVRController;
  63662. })(BABYLON || (BABYLON = {}));
  63663. //# sourceMappingURL=babylon.webVRController.js.map
  63664. var BABYLON;
  63665. (function (BABYLON) {
  63666. var OculusTouchController = /** @class */ (function (_super) {
  63667. __extends(OculusTouchController, _super);
  63668. function OculusTouchController(vrGamepad) {
  63669. var _this = _super.call(this, vrGamepad) || this;
  63670. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  63671. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  63672. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  63673. return _this;
  63674. }
  63675. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63676. var _this = this;
  63677. var meshName;
  63678. // Hand
  63679. if (this.hand === 'left') {
  63680. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  63681. }
  63682. else {
  63683. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  63684. }
  63685. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  63686. /*
  63687. Parent Mesh name: oculus_touch_left
  63688. - body
  63689. - trigger
  63690. - thumbstick
  63691. - grip
  63692. - button_y
  63693. - button_x
  63694. - button_enter
  63695. */
  63696. _this._defaultModel = newMeshes[1];
  63697. _this.attachToMesh(_this._defaultModel);
  63698. if (meshLoaded) {
  63699. meshLoaded(_this._defaultModel);
  63700. }
  63701. });
  63702. };
  63703. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  63704. // helper getters for left and right hand.
  63705. get: function () {
  63706. if (this.hand === 'right') {
  63707. return this.onMainButtonStateChangedObservable;
  63708. }
  63709. else {
  63710. throw new Error('No A button on left hand');
  63711. }
  63712. },
  63713. enumerable: true,
  63714. configurable: true
  63715. });
  63716. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  63717. get: function () {
  63718. if (this.hand === 'right') {
  63719. return this.onSecondaryButtonStateChangedObservable;
  63720. }
  63721. else {
  63722. throw new Error('No B button on left hand');
  63723. }
  63724. },
  63725. enumerable: true,
  63726. configurable: true
  63727. });
  63728. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  63729. get: function () {
  63730. if (this.hand === 'left') {
  63731. return this.onMainButtonStateChangedObservable;
  63732. }
  63733. else {
  63734. throw new Error('No X button on right hand');
  63735. }
  63736. },
  63737. enumerable: true,
  63738. configurable: true
  63739. });
  63740. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  63741. get: function () {
  63742. if (this.hand === 'left') {
  63743. return this.onSecondaryButtonStateChangedObservable;
  63744. }
  63745. else {
  63746. throw new Error('No Y button on right hand');
  63747. }
  63748. },
  63749. enumerable: true,
  63750. configurable: true
  63751. });
  63752. /*
  63753. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  63754. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  63755. 2) secondary trigger (same)
  63756. 3) A (right) X (left), touch, pressed = value
  63757. 4) B / Y
  63758. 5) thumb rest
  63759. */
  63760. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63761. var notifyObject = state; //{ state: state, changes: changes };
  63762. var triggerDirection = this.hand === 'right' ? -1 : 1;
  63763. switch (buttonIdx) {
  63764. case 0:
  63765. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63766. return;
  63767. case 1:// index trigger
  63768. if (this._defaultModel) {
  63769. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  63770. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  63771. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  63772. }
  63773. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63774. return;
  63775. case 2:// secondary trigger
  63776. if (this._defaultModel) {
  63777. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  63778. }
  63779. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  63780. return;
  63781. case 3:
  63782. if (this._defaultModel) {
  63783. if (notifyObject.pressed) {
  63784. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  63785. }
  63786. else {
  63787. (this._defaultModel.getChildren()[1]).position.y = 0;
  63788. }
  63789. }
  63790. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63791. return;
  63792. case 4:
  63793. if (this._defaultModel) {
  63794. if (notifyObject.pressed) {
  63795. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63796. }
  63797. else {
  63798. (this._defaultModel.getChildren()[2]).position.y = 0;
  63799. }
  63800. }
  63801. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63802. return;
  63803. case 5:
  63804. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  63805. return;
  63806. }
  63807. };
  63808. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  63809. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  63810. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  63811. return OculusTouchController;
  63812. }(BABYLON.WebVRController));
  63813. BABYLON.OculusTouchController = OculusTouchController;
  63814. })(BABYLON || (BABYLON = {}));
  63815. //# sourceMappingURL=babylon.oculusTouchController.js.map
  63816. var BABYLON;
  63817. (function (BABYLON) {
  63818. var ViveController = /** @class */ (function (_super) {
  63819. __extends(ViveController, _super);
  63820. function ViveController(vrGamepad) {
  63821. var _this = _super.call(this, vrGamepad) || this;
  63822. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  63823. _this._invertLeftStickY = true;
  63824. return _this;
  63825. }
  63826. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63827. var _this = this;
  63828. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  63829. /*
  63830. Parent Mesh name: ViveWand
  63831. - body
  63832. - r_gripper
  63833. - l_gripper
  63834. - menu_button
  63835. - system_button
  63836. - trackpad
  63837. - trigger
  63838. - LED
  63839. */
  63840. _this._defaultModel = newMeshes[1];
  63841. _this.attachToMesh(_this._defaultModel);
  63842. if (meshLoaded) {
  63843. meshLoaded(_this._defaultModel);
  63844. }
  63845. });
  63846. };
  63847. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  63848. get: function () {
  63849. return this.onMainButtonStateChangedObservable;
  63850. },
  63851. enumerable: true,
  63852. configurable: true
  63853. });
  63854. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  63855. get: function () {
  63856. return this.onMainButtonStateChangedObservable;
  63857. },
  63858. enumerable: true,
  63859. configurable: true
  63860. });
  63861. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  63862. get: function () {
  63863. return this.onSecondaryButtonStateChangedObservable;
  63864. },
  63865. enumerable: true,
  63866. configurable: true
  63867. });
  63868. /**
  63869. * Vive mapping:
  63870. * 0: touchpad
  63871. * 1: trigger
  63872. * 2: left AND right buttons
  63873. * 3: menu button
  63874. */
  63875. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63876. var notifyObject = state; //{ state: state, changes: changes };
  63877. switch (buttonIdx) {
  63878. case 0:
  63879. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  63880. return;
  63881. case 1:// index trigger
  63882. if (this._defaultModel) {
  63883. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  63884. }
  63885. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  63886. return;
  63887. case 2:// left AND right button
  63888. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  63889. return;
  63890. case 3:
  63891. if (this._defaultModel) {
  63892. if (notifyObject.pressed) {
  63893. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  63894. }
  63895. else {
  63896. (this._defaultModel.getChildren()[2]).position.y = 0;
  63897. }
  63898. }
  63899. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  63900. return;
  63901. }
  63902. };
  63903. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  63904. ViveController.MODEL_FILENAME = 'wand.babylon';
  63905. return ViveController;
  63906. }(BABYLON.WebVRController));
  63907. BABYLON.ViveController = ViveController;
  63908. })(BABYLON || (BABYLON = {}));
  63909. //# sourceMappingURL=babylon.viveController.js.map
  63910. var BABYLON;
  63911. (function (BABYLON) {
  63912. var GenericController = /** @class */ (function (_super) {
  63913. __extends(GenericController, _super);
  63914. function GenericController(vrGamepad) {
  63915. return _super.call(this, vrGamepad) || this;
  63916. }
  63917. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  63918. var _this = this;
  63919. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  63920. _this._defaultModel = newMeshes[1];
  63921. _this.attachToMesh(_this._defaultModel);
  63922. if (meshLoaded) {
  63923. meshLoaded(_this._defaultModel);
  63924. }
  63925. });
  63926. };
  63927. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  63928. console.log("Button id: " + buttonIdx + "state: ");
  63929. console.dir(state);
  63930. };
  63931. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  63932. GenericController.MODEL_FILENAME = 'generic.babylon';
  63933. return GenericController;
  63934. }(BABYLON.WebVRController));
  63935. BABYLON.GenericController = GenericController;
  63936. })(BABYLON || (BABYLON = {}));
  63937. //# sourceMappingURL=babylon.genericController.js.map
  63938. var BABYLON;
  63939. (function (BABYLON) {
  63940. var LoadedMeshInfo = /** @class */ (function () {
  63941. function LoadedMeshInfo() {
  63942. this.buttonMeshes = {};
  63943. this.axisMeshes = {};
  63944. }
  63945. return LoadedMeshInfo;
  63946. }());
  63947. var WindowsMotionController = /** @class */ (function (_super) {
  63948. __extends(WindowsMotionController, _super);
  63949. function WindowsMotionController(vrGamepad) {
  63950. var _this = _super.call(this, vrGamepad) || this;
  63951. _this._mapping = {
  63952. // Semantic button names
  63953. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  63954. // A mapping of the button name to glTF model node name
  63955. // that should be transformed by button value.
  63956. buttonMeshNames: {
  63957. 'trigger': 'SELECT',
  63958. 'menu': 'MENU',
  63959. 'grip': 'GRASP',
  63960. 'thumbstick': 'THUMBSTICK_PRESS',
  63961. 'trackpad': 'TOUCHPAD_PRESS'
  63962. },
  63963. // This mapping is used to translate from the Motion Controller to Babylon semantics
  63964. buttonObservableNames: {
  63965. 'trigger': 'onTriggerStateChangedObservable',
  63966. 'menu': 'onSecondaryButtonStateChangedObservable',
  63967. 'grip': 'onMainButtonStateChangedObservable',
  63968. 'thumbstick': 'onPadStateChangedObservable',
  63969. 'trackpad': 'onTrackpadChangedObservable'
  63970. },
  63971. // A mapping of the axis name to glTF model node name
  63972. // that should be transformed by axis value.
  63973. // This array mirrors the browserGamepad.axes array, such that
  63974. // the mesh corresponding to axis 0 is in this array index 0.
  63975. axisMeshNames: [
  63976. 'THUMBSTICK_X',
  63977. 'THUMBSTICK_Y',
  63978. 'TOUCHPAD_TOUCH_X',
  63979. 'TOUCHPAD_TOUCH_Y'
  63980. ],
  63981. pointingPoseMeshName: 'POINTING_POSE'
  63982. };
  63983. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  63984. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  63985. _this.trackpad = { x: 0, y: 0 };
  63986. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  63987. _this._loadedMeshInfo = null;
  63988. return _this;
  63989. }
  63990. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  63991. get: function () {
  63992. return this.onTriggerStateChangedObservable;
  63993. },
  63994. enumerable: true,
  63995. configurable: true
  63996. });
  63997. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  63998. get: function () {
  63999. return this.onSecondaryButtonStateChangedObservable;
  64000. },
  64001. enumerable: true,
  64002. configurable: true
  64003. });
  64004. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64005. get: function () {
  64006. return this.onMainButtonStateChangedObservable;
  64007. },
  64008. enumerable: true,
  64009. configurable: true
  64010. });
  64011. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64012. get: function () {
  64013. return this.onPadStateChangedObservable;
  64014. },
  64015. enumerable: true,
  64016. configurable: true
  64017. });
  64018. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64019. get: function () {
  64020. return this.onTrackpadChangedObservable;
  64021. },
  64022. enumerable: true,
  64023. configurable: true
  64024. });
  64025. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  64026. get: function () {
  64027. return this.onTrackpadValuesChangedObservable;
  64028. },
  64029. enumerable: true,
  64030. configurable: true
  64031. });
  64032. /**
  64033. * Called once per frame by the engine.
  64034. */
  64035. WindowsMotionController.prototype.update = function () {
  64036. _super.prototype.update.call(this);
  64037. // Only need to animate axes if there is a loaded mesh
  64038. if (this._loadedMeshInfo) {
  64039. if (this.browserGamepad.axes) {
  64040. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64041. this.trackpad.x = this.browserGamepad["axes"][2];
  64042. this.trackpad.y = this.browserGamepad["axes"][3];
  64043. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64044. }
  64045. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64046. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64047. }
  64048. }
  64049. }
  64050. };
  64051. /**
  64052. * Called once for each button that changed state since the last frame
  64053. * @param buttonIdx Which button index changed
  64054. * @param state New state of the button
  64055. * @param changes Which properties on the state changed since last frame
  64056. */
  64057. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64058. var buttonName = this._mapping.buttons[buttonIdx];
  64059. if (!buttonName) {
  64060. return;
  64061. }
  64062. // Only emit events for buttons that we know how to map from index to name
  64063. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64064. if (observable) {
  64065. observable.notifyObservers(state);
  64066. }
  64067. this.lerpButtonTransform(buttonName, state.value);
  64068. };
  64069. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  64070. // If there is no loaded mesh, there is nothing to transform.
  64071. if (!this._loadedMeshInfo) {
  64072. return;
  64073. }
  64074. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  64075. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64076. return;
  64077. }
  64078. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  64079. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  64080. };
  64081. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  64082. if (!this._loadedMeshInfo) {
  64083. return;
  64084. }
  64085. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  64086. if (!meshInfo) {
  64087. return;
  64088. }
  64089. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64090. return;
  64091. }
  64092. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  64093. var lerpValue = axisValue * 0.5 + 0.5;
  64094. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  64095. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  64096. };
  64097. /**
  64098. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  64099. * @param scene scene in which to add meshes
  64100. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  64101. */
  64102. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  64103. var _this = this;
  64104. if (forceDefault === void 0) { forceDefault = false; }
  64105. var path;
  64106. var filename;
  64107. // Checking if GLB loader is present
  64108. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  64109. // Determine the device specific folder based on the ID suffix
  64110. var device = 'default';
  64111. if (this.id && !forceDefault) {
  64112. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  64113. device = ((match && match[0]) || device);
  64114. }
  64115. // Hand
  64116. if (this.hand === 'left') {
  64117. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  64118. }
  64119. else {
  64120. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  64121. }
  64122. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  64123. }
  64124. else {
  64125. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  64126. path = BABYLON.GenericController.MODEL_BASE_URL;
  64127. filename = BABYLON.GenericController.MODEL_FILENAME;
  64128. }
  64129. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  64130. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  64131. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  64132. if (!_this._loadedMeshInfo) {
  64133. return;
  64134. }
  64135. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  64136. _this.attachToMesh(_this._defaultModel);
  64137. if (meshLoaded) {
  64138. meshLoaded(_this._defaultModel);
  64139. }
  64140. }, null, function (scene, message) {
  64141. BABYLON.Tools.Log(message);
  64142. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  64143. if (!forceDefault) {
  64144. _this.initControllerMesh(scene, meshLoaded, true);
  64145. }
  64146. });
  64147. };
  64148. /**
  64149. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  64150. * can be transformed by button presses and axes values, based on this._mapping.
  64151. *
  64152. * @param scene scene in which the meshes exist
  64153. * @param meshes list of meshes that make up the controller model to process
  64154. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  64155. */
  64156. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  64157. var loadedMeshInfo = null;
  64158. // Create a new mesh to contain the glTF hierarchy
  64159. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  64160. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  64161. var childMesh = null;
  64162. for (var i = 0; i < meshes.length; i++) {
  64163. var mesh = meshes[i];
  64164. if (!mesh.parent) {
  64165. // Exclude controller meshes from picking results
  64166. mesh.isPickable = false;
  64167. // Handle root node, attach to the new parentMesh
  64168. childMesh = mesh;
  64169. break;
  64170. }
  64171. }
  64172. if (childMesh) {
  64173. childMesh.setParent(parentMesh);
  64174. // Create our mesh info. Note that this method will always return non-null.
  64175. loadedMeshInfo = this.createMeshInfo(parentMesh);
  64176. }
  64177. else {
  64178. BABYLON.Tools.Warn('Could not find root node in model file.');
  64179. }
  64180. return loadedMeshInfo;
  64181. };
  64182. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  64183. var loadedMeshInfo = new LoadedMeshInfo();
  64184. var i;
  64185. loadedMeshInfo.rootNode = rootNode;
  64186. // Reset the caches
  64187. loadedMeshInfo.buttonMeshes = {};
  64188. loadedMeshInfo.axisMeshes = {};
  64189. // Button Meshes
  64190. for (i = 0; i < this._mapping.buttons.length; i++) {
  64191. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  64192. if (!buttonMeshName) {
  64193. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  64194. continue;
  64195. }
  64196. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  64197. if (!buttonMesh) {
  64198. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  64199. continue;
  64200. }
  64201. var buttonMeshInfo = {
  64202. index: i,
  64203. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  64204. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  64205. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  64206. };
  64207. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  64208. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  64209. }
  64210. else {
  64211. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  64212. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  64213. '(VALUE: ' + !!buttonMeshInfo.value +
  64214. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  64215. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  64216. ')');
  64217. }
  64218. }
  64219. // Axis Meshes
  64220. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  64221. var axisMeshName = this._mapping.axisMeshNames[i];
  64222. if (!axisMeshName) {
  64223. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  64224. continue;
  64225. }
  64226. var axisMesh = getChildByName(rootNode, axisMeshName);
  64227. if (!axisMesh) {
  64228. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  64229. continue;
  64230. }
  64231. var axisMeshInfo = {
  64232. index: i,
  64233. value: getImmediateChildByName(axisMesh, 'VALUE'),
  64234. min: getImmediateChildByName(axisMesh, 'MIN'),
  64235. max: getImmediateChildByName(axisMesh, 'MAX')
  64236. };
  64237. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  64238. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  64239. }
  64240. else {
  64241. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64242. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  64243. '(VALUE: ' + !!axisMeshInfo.value +
  64244. ', MIN: ' + !!axisMeshInfo.min +
  64245. ', MAX:' + !!axisMeshInfo.max +
  64246. ')');
  64247. }
  64248. }
  64249. // Pointing Ray
  64250. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  64251. if (!loadedMeshInfo.pointingPoseNode) {
  64252. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  64253. }
  64254. return loadedMeshInfo;
  64255. // Look through all children recursively. This will return null if no mesh exists with the given name.
  64256. function getChildByName(node, name) {
  64257. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  64258. }
  64259. // Look through only immediate children. This will return null if no mesh exists with the given name.
  64260. function getImmediateChildByName(node, name) {
  64261. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  64262. }
  64263. };
  64264. WindowsMotionController.prototype.getForwardRay = function (length) {
  64265. if (length === void 0) { length = 100; }
  64266. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  64267. return _super.prototype.getForwardRay.call(this, length);
  64268. }
  64269. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  64270. var origin = m.getTranslation();
  64271. var forward = new BABYLON.Vector3(0, 0, -1);
  64272. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64273. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64274. return new BABYLON.Ray(origin, direction, length);
  64275. };
  64276. WindowsMotionController.prototype.dispose = function () {
  64277. _super.prototype.dispose.call(this);
  64278. this.onTrackpadChangedObservable.clear();
  64279. };
  64280. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  64281. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  64282. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  64283. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  64284. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  64285. return WindowsMotionController;
  64286. }(BABYLON.WebVRController));
  64287. BABYLON.WindowsMotionController = WindowsMotionController;
  64288. })(BABYLON || (BABYLON = {}));
  64289. //# sourceMappingURL=babylon.windowsMotionController.js.map
  64290. var BABYLON;
  64291. (function (BABYLON) {
  64292. var GearVRController = /** @class */ (function (_super) {
  64293. __extends(GearVRController, _super);
  64294. function GearVRController(vrGamepad) {
  64295. var _this = _super.call(this, vrGamepad) || this;
  64296. _this._buttonIndexToObservableNameMap = [
  64297. 'onTrackpadChangedObservable',
  64298. 'onTriggerStateChangedObservable' // Trigger
  64299. ];
  64300. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  64301. return _this;
  64302. }
  64303. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64304. var _this = this;
  64305. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  64306. _this._defaultModel = newMeshes[1];
  64307. _this.attachToMesh(_this._defaultModel);
  64308. if (meshLoaded) {
  64309. meshLoaded(_this._defaultModel);
  64310. }
  64311. });
  64312. };
  64313. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64314. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  64315. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  64316. // Only emit events for buttons that we know how to map from index to observable
  64317. var observable = this[observableName];
  64318. if (observable) {
  64319. observable.notifyObservers(state);
  64320. }
  64321. }
  64322. };
  64323. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64324. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64325. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64326. return GearVRController;
  64327. }(BABYLON.WebVRController));
  64328. BABYLON.GearVRController = GearVRController;
  64329. })(BABYLON || (BABYLON = {}));
  64330. //# sourceMappingURL=babylon.gearVRController.js.map
  64331. var BABYLON;
  64332. (function (BABYLON) {
  64333. var FollowCamera = /** @class */ (function (_super) {
  64334. __extends(FollowCamera, _super);
  64335. function FollowCamera(name, position, scene, lockedTarget) {
  64336. if (lockedTarget === void 0) { lockedTarget = null; }
  64337. var _this = _super.call(this, name, position, scene) || this;
  64338. _this.radius = 12;
  64339. _this.rotationOffset = 0;
  64340. _this.heightOffset = 4;
  64341. _this.cameraAcceleration = 0.05;
  64342. _this.maxCameraSpeed = 20;
  64343. _this.lockedTarget = lockedTarget;
  64344. return _this;
  64345. }
  64346. FollowCamera.prototype.getRadians = function (degrees) {
  64347. return degrees * Math.PI / 180;
  64348. };
  64349. FollowCamera.prototype.follow = function (cameraTarget) {
  64350. if (!cameraTarget)
  64351. return;
  64352. var yRotation;
  64353. if (cameraTarget.rotationQuaternion) {
  64354. var rotMatrix = new BABYLON.Matrix();
  64355. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64356. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64357. }
  64358. else {
  64359. yRotation = cameraTarget.rotation.y;
  64360. }
  64361. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64362. var targetPosition = cameraTarget.getAbsolutePosition();
  64363. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64364. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64365. var dx = targetX - this.position.x;
  64366. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64367. var dz = (targetZ) - this.position.z;
  64368. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64369. var vy = dy * this.cameraAcceleration;
  64370. var vz = dz * this.cameraAcceleration * 2;
  64371. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64372. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64373. }
  64374. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64375. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64376. }
  64377. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64378. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64379. }
  64380. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64381. this.setTarget(targetPosition);
  64382. };
  64383. FollowCamera.prototype._checkInputs = function () {
  64384. _super.prototype._checkInputs.call(this);
  64385. if (this.lockedTarget) {
  64386. this.follow(this.lockedTarget);
  64387. }
  64388. };
  64389. FollowCamera.prototype.getClassName = function () {
  64390. return "FollowCamera";
  64391. };
  64392. __decorate([
  64393. BABYLON.serialize()
  64394. ], FollowCamera.prototype, "radius", void 0);
  64395. __decorate([
  64396. BABYLON.serialize()
  64397. ], FollowCamera.prototype, "rotationOffset", void 0);
  64398. __decorate([
  64399. BABYLON.serialize()
  64400. ], FollowCamera.prototype, "heightOffset", void 0);
  64401. __decorate([
  64402. BABYLON.serialize()
  64403. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64404. __decorate([
  64405. BABYLON.serialize()
  64406. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64407. __decorate([
  64408. BABYLON.serializeAsMeshReference("lockedTargetId")
  64409. ], FollowCamera.prototype, "lockedTarget", void 0);
  64410. return FollowCamera;
  64411. }(BABYLON.TargetCamera));
  64412. BABYLON.FollowCamera = FollowCamera;
  64413. var ArcFollowCamera = /** @class */ (function (_super) {
  64414. __extends(ArcFollowCamera, _super);
  64415. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64416. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64417. _this.alpha = alpha;
  64418. _this.beta = beta;
  64419. _this.radius = radius;
  64420. _this.target = target;
  64421. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64422. _this.follow();
  64423. return _this;
  64424. }
  64425. ArcFollowCamera.prototype.follow = function () {
  64426. if (!this.target) {
  64427. return;
  64428. }
  64429. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64430. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64431. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64432. var targetPosition = this.target.getAbsolutePosition();
  64433. this.position = targetPosition.add(this._cartesianCoordinates);
  64434. this.setTarget(targetPosition);
  64435. };
  64436. ArcFollowCamera.prototype._checkInputs = function () {
  64437. _super.prototype._checkInputs.call(this);
  64438. this.follow();
  64439. };
  64440. ArcFollowCamera.prototype.getClassName = function () {
  64441. return "ArcFollowCamera";
  64442. };
  64443. return ArcFollowCamera;
  64444. }(BABYLON.TargetCamera));
  64445. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64446. })(BABYLON || (BABYLON = {}));
  64447. //# sourceMappingURL=babylon.followCamera.js.map
  64448. var BABYLON;
  64449. (function (BABYLON) {
  64450. // We're mainly based on the logic defined into the FreeCamera code
  64451. var UniversalCamera = /** @class */ (function (_super) {
  64452. __extends(UniversalCamera, _super);
  64453. //-- end properties for backward compatibility for inputs
  64454. function UniversalCamera(name, position, scene) {
  64455. var _this = _super.call(this, name, position, scene) || this;
  64456. _this.inputs.addGamepad();
  64457. return _this;
  64458. }
  64459. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64460. //-- Begin properties for backward compatibility for inputs
  64461. get: function () {
  64462. var gamepad = this.inputs.attached["gamepad"];
  64463. if (gamepad)
  64464. return gamepad.gamepadAngularSensibility;
  64465. return 0;
  64466. },
  64467. set: function (value) {
  64468. var gamepad = this.inputs.attached["gamepad"];
  64469. if (gamepad)
  64470. gamepad.gamepadAngularSensibility = value;
  64471. },
  64472. enumerable: true,
  64473. configurable: true
  64474. });
  64475. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64476. get: function () {
  64477. var gamepad = this.inputs.attached["gamepad"];
  64478. if (gamepad)
  64479. return gamepad.gamepadMoveSensibility;
  64480. return 0;
  64481. },
  64482. set: function (value) {
  64483. var gamepad = this.inputs.attached["gamepad"];
  64484. if (gamepad)
  64485. gamepad.gamepadMoveSensibility = value;
  64486. },
  64487. enumerable: true,
  64488. configurable: true
  64489. });
  64490. UniversalCamera.prototype.getClassName = function () {
  64491. return "UniversalCamera";
  64492. };
  64493. return UniversalCamera;
  64494. }(BABYLON.TouchCamera));
  64495. BABYLON.UniversalCamera = UniversalCamera;
  64496. })(BABYLON || (BABYLON = {}));
  64497. //# sourceMappingURL=babylon.universalCamera.js.map
  64498. var BABYLON;
  64499. (function (BABYLON) {
  64500. // We're mainly based on the logic defined into the FreeCamera code
  64501. var GamepadCamera = /** @class */ (function (_super) {
  64502. __extends(GamepadCamera, _super);
  64503. //-- end properties for backward compatibility for inputs
  64504. function GamepadCamera(name, position, scene) {
  64505. return _super.call(this, name, position, scene) || this;
  64506. }
  64507. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64508. //-- Begin properties for backward compatibility for inputs
  64509. get: function () {
  64510. var gamepad = this.inputs.attached["gamepad"];
  64511. if (gamepad)
  64512. return gamepad.gamepadAngularSensibility;
  64513. return 0;
  64514. },
  64515. set: function (value) {
  64516. var gamepad = this.inputs.attached["gamepad"];
  64517. if (gamepad)
  64518. gamepad.gamepadAngularSensibility = value;
  64519. },
  64520. enumerable: true,
  64521. configurable: true
  64522. });
  64523. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64524. get: function () {
  64525. var gamepad = this.inputs.attached["gamepad"];
  64526. if (gamepad)
  64527. return gamepad.gamepadMoveSensibility;
  64528. return 0;
  64529. },
  64530. set: function (value) {
  64531. var gamepad = this.inputs.attached["gamepad"];
  64532. if (gamepad)
  64533. gamepad.gamepadMoveSensibility = value;
  64534. },
  64535. enumerable: true,
  64536. configurable: true
  64537. });
  64538. GamepadCamera.prototype.getClassName = function () {
  64539. return "GamepadCamera";
  64540. };
  64541. return GamepadCamera;
  64542. }(BABYLON.UniversalCamera));
  64543. BABYLON.GamepadCamera = GamepadCamera;
  64544. })(BABYLON || (BABYLON = {}));
  64545. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64546. var BABYLON;
  64547. (function (BABYLON) {
  64548. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64549. function PostProcessRenderPipelineManager() {
  64550. this._renderPipelines = {};
  64551. }
  64552. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64553. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64554. };
  64555. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64556. if (unique === void 0) { unique = false; }
  64557. var renderPipeline = this._renderPipelines[renderPipelineName];
  64558. if (!renderPipeline) {
  64559. return;
  64560. }
  64561. renderPipeline._attachCameras(cameras, unique);
  64562. };
  64563. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64564. var renderPipeline = this._renderPipelines[renderPipelineName];
  64565. if (!renderPipeline) {
  64566. return;
  64567. }
  64568. renderPipeline._detachCameras(cameras);
  64569. };
  64570. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64571. var renderPipeline = this._renderPipelines[renderPipelineName];
  64572. if (!renderPipeline) {
  64573. return;
  64574. }
  64575. renderPipeline._enableEffect(renderEffectName, cameras);
  64576. };
  64577. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64578. var renderPipeline = this._renderPipelines[renderPipelineName];
  64579. if (!renderPipeline) {
  64580. return;
  64581. }
  64582. renderPipeline._disableEffect(renderEffectName, cameras);
  64583. };
  64584. PostProcessRenderPipelineManager.prototype.update = function () {
  64585. for (var renderPipelineName in this._renderPipelines) {
  64586. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64587. var pipeline = this._renderPipelines[renderPipelineName];
  64588. if (!pipeline.isSupported) {
  64589. pipeline.dispose();
  64590. delete this._renderPipelines[renderPipelineName];
  64591. }
  64592. else {
  64593. pipeline._update();
  64594. }
  64595. }
  64596. }
  64597. };
  64598. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  64599. for (var renderPipelineName in this._renderPipelines) {
  64600. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64601. var pipeline = this._renderPipelines[renderPipelineName];
  64602. pipeline._rebuild();
  64603. }
  64604. }
  64605. };
  64606. PostProcessRenderPipelineManager.prototype.dispose = function () {
  64607. for (var renderPipelineName in this._renderPipelines) {
  64608. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  64609. var pipeline = this._renderPipelines[renderPipelineName];
  64610. pipeline.dispose();
  64611. }
  64612. }
  64613. };
  64614. return PostProcessRenderPipelineManager;
  64615. }());
  64616. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  64617. })(BABYLON || (BABYLON = {}));
  64618. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  64619. var BABYLON;
  64620. (function (BABYLON) {
  64621. /**
  64622. * This represents a set of one or more post processes in Babylon.
  64623. * A post process can be used to apply a shader to a texture after it is rendered.
  64624. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  64625. */
  64626. var PostProcessRenderEffect = /** @class */ (function () {
  64627. /**
  64628. * Instantiates a post process render effect.
  64629. * A post process can be used to apply a shader to a texture after it is rendered.
  64630. * @param engine The engine the effect is tied to
  64631. * @param name The name of the effect
  64632. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  64633. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  64634. */
  64635. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  64636. this._name = name;
  64637. this._singleInstance = singleInstance || true;
  64638. this._getPostProcesses = getPostProcesses;
  64639. this._cameras = {};
  64640. this._indicesForCamera = {};
  64641. this._postProcesses = {};
  64642. }
  64643. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  64644. /**
  64645. * Checks if all the post processes in the effect are supported.
  64646. */
  64647. get: function () {
  64648. for (var index in this._postProcesses) {
  64649. for (var ppIndex in this._postProcesses[index]) {
  64650. if (!this._postProcesses[index][ppIndex].isSupported) {
  64651. return false;
  64652. }
  64653. }
  64654. }
  64655. return true;
  64656. },
  64657. enumerable: true,
  64658. configurable: true
  64659. });
  64660. /**
  64661. * Updates the current state of the effect
  64662. */
  64663. PostProcessRenderEffect.prototype._update = function () {
  64664. };
  64665. /**
  64666. * Attaches the effect on cameras
  64667. * @param cameras The camera to attach to.
  64668. */
  64669. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  64670. var _this = this;
  64671. var cameraKey;
  64672. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64673. if (!cams) {
  64674. return;
  64675. }
  64676. for (var i = 0; i < cams.length; i++) {
  64677. var camera = cams[i];
  64678. var cameraName = camera.name;
  64679. if (this._singleInstance) {
  64680. cameraKey = 0;
  64681. }
  64682. else {
  64683. cameraKey = cameraName;
  64684. }
  64685. if (!this._postProcesses[cameraKey]) {
  64686. var postProcess = this._getPostProcesses();
  64687. if (postProcess) {
  64688. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  64689. }
  64690. }
  64691. if (!this._indicesForCamera[cameraName]) {
  64692. this._indicesForCamera[cameraName] = [];
  64693. }
  64694. this._postProcesses[cameraKey].forEach(function (postProcess) {
  64695. var index = camera.attachPostProcess(postProcess);
  64696. _this._indicesForCamera[cameraName].push(index);
  64697. });
  64698. if (!this._cameras[cameraName]) {
  64699. this._cameras[cameraName] = camera;
  64700. }
  64701. }
  64702. };
  64703. /**
  64704. * Detatches the effect on cameras
  64705. * @param cameras The camera to detatch from.
  64706. */
  64707. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  64708. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64709. if (!cams) {
  64710. return;
  64711. }
  64712. for (var i = 0; i < cams.length; i++) {
  64713. var camera = cams[i];
  64714. var cameraName = camera.name;
  64715. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64716. camera.detachPostProcess(postProcess);
  64717. });
  64718. if (this._cameras[cameraName]) {
  64719. //this._indicesForCamera.splice(index, 1);
  64720. this._cameras[cameraName] = null;
  64721. }
  64722. }
  64723. };
  64724. /**
  64725. * Enables the effect on given cameras
  64726. * @param cameras The camera to enable.
  64727. */
  64728. PostProcessRenderEffect.prototype._enable = function (cameras) {
  64729. var _this = this;
  64730. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64731. if (!cams) {
  64732. return;
  64733. }
  64734. for (var i = 0; i < cams.length; i++) {
  64735. var camera = cams[i];
  64736. var cameraName = camera.name;
  64737. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  64738. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  64739. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64740. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  64741. });
  64742. }
  64743. }
  64744. }
  64745. };
  64746. /**
  64747. * Disables the effect on the given cameras
  64748. * @param cameras The camera to disable.
  64749. */
  64750. PostProcessRenderEffect.prototype._disable = function (cameras) {
  64751. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64752. if (!cams) {
  64753. return;
  64754. }
  64755. for (var i = 0; i < cams.length; i++) {
  64756. var camera = cams[i];
  64757. var cameraName = camera.name;
  64758. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  64759. camera.detachPostProcess(postProcess);
  64760. });
  64761. }
  64762. };
  64763. /**
  64764. * Gets a list of the post processes contained in the effect.
  64765. * @param camera The camera to get the post processes on.
  64766. * @returns The list of the post processes in the effect.
  64767. */
  64768. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  64769. if (this._singleInstance) {
  64770. return this._postProcesses[0];
  64771. }
  64772. else {
  64773. if (!camera) {
  64774. return null;
  64775. }
  64776. return this._postProcesses[camera.name];
  64777. }
  64778. };
  64779. return PostProcessRenderEffect;
  64780. }());
  64781. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  64782. })(BABYLON || (BABYLON = {}));
  64783. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  64784. var BABYLON;
  64785. (function (BABYLON) {
  64786. var PostProcessRenderPipeline = /** @class */ (function () {
  64787. function PostProcessRenderPipeline(engine, name) {
  64788. this._name = name;
  64789. this._renderEffects = {};
  64790. this._renderEffectsForIsolatedPass = new Array();
  64791. this._cameras = [];
  64792. }
  64793. PostProcessRenderPipeline.prototype.getClassName = function () {
  64794. return "PostProcessRenderPipeline";
  64795. };
  64796. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  64797. get: function () {
  64798. for (var renderEffectName in this._renderEffects) {
  64799. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64800. if (!this._renderEffects[renderEffectName].isSupported) {
  64801. return false;
  64802. }
  64803. }
  64804. }
  64805. return true;
  64806. },
  64807. enumerable: true,
  64808. configurable: true
  64809. });
  64810. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  64811. this._renderEffects[renderEffect._name] = renderEffect;
  64812. };
  64813. // private
  64814. PostProcessRenderPipeline.prototype._rebuild = function () {
  64815. };
  64816. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  64817. var renderEffects = this._renderEffects[renderEffectName];
  64818. if (!renderEffects) {
  64819. return;
  64820. }
  64821. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64822. };
  64823. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  64824. var renderEffects = this._renderEffects[renderEffectName];
  64825. if (!renderEffects) {
  64826. return;
  64827. }
  64828. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  64829. };
  64830. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  64831. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64832. if (!cams) {
  64833. return;
  64834. }
  64835. var indicesToDelete = [];
  64836. var i;
  64837. for (i = 0; i < cams.length; i++) {
  64838. var camera = cams[i];
  64839. var cameraName = camera.name;
  64840. if (this._cameras.indexOf(camera) === -1) {
  64841. this._cameras[cameraName] = camera;
  64842. }
  64843. else if (unique) {
  64844. indicesToDelete.push(i);
  64845. }
  64846. }
  64847. for (i = 0; i < indicesToDelete.length; i++) {
  64848. cameras.splice(indicesToDelete[i], 1);
  64849. }
  64850. for (var renderEffectName in this._renderEffects) {
  64851. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64852. this._renderEffects[renderEffectName]._attachCameras(cams);
  64853. }
  64854. }
  64855. };
  64856. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  64857. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  64858. if (!cams) {
  64859. return;
  64860. }
  64861. for (var renderEffectName in this._renderEffects) {
  64862. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64863. this._renderEffects[renderEffectName]._detachCameras(cams);
  64864. }
  64865. }
  64866. for (var i = 0; i < cams.length; i++) {
  64867. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  64868. }
  64869. };
  64870. PostProcessRenderPipeline.prototype._update = function () {
  64871. for (var renderEffectName in this._renderEffects) {
  64872. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  64873. this._renderEffects[renderEffectName]._update();
  64874. }
  64875. }
  64876. for (var i = 0; i < this._cameras.length; i++) {
  64877. var cameraName = this._cameras[i].name;
  64878. if (this._renderEffectsForIsolatedPass[cameraName]) {
  64879. this._renderEffectsForIsolatedPass[cameraName]._update();
  64880. }
  64881. }
  64882. };
  64883. PostProcessRenderPipeline.prototype._reset = function () {
  64884. this._renderEffects = {};
  64885. this._renderEffectsForIsolatedPass = new Array();
  64886. };
  64887. PostProcessRenderPipeline.prototype.dispose = function () {
  64888. // Must be implemented by children
  64889. };
  64890. __decorate([
  64891. BABYLON.serialize()
  64892. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  64893. return PostProcessRenderPipeline;
  64894. }());
  64895. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  64896. })(BABYLON || (BABYLON = {}));
  64897. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  64898. var BABYLON;
  64899. (function (BABYLON) {
  64900. var DepthRenderer = /** @class */ (function () {
  64901. function DepthRenderer(scene, type) {
  64902. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64903. var _this = this;
  64904. this._scene = scene;
  64905. var engine = scene.getEngine();
  64906. // Render target
  64907. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  64908. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64909. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64910. this._depthMap.refreshRate = 1;
  64911. this._depthMap.renderParticles = false;
  64912. this._depthMap.renderList = null;
  64913. // set default depth value to 1.0 (far away)
  64914. this._depthMap.onClearObservable.add(function (engine) {
  64915. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  64916. });
  64917. // Custom render function
  64918. var renderSubMesh = function (subMesh) {
  64919. var mesh = subMesh.getRenderingMesh();
  64920. var scene = _this._scene;
  64921. var engine = scene.getEngine();
  64922. var material = subMesh.getMaterial();
  64923. if (!material) {
  64924. return;
  64925. }
  64926. // Culling and reverse (right handed system)
  64927. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  64928. // Managing instances
  64929. var batch = mesh._getInstancesRenderList(subMesh._id);
  64930. if (batch.mustReturn) {
  64931. return;
  64932. }
  64933. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  64934. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  64935. engine.enableEffect(_this._effect);
  64936. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  64937. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  64938. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  64939. // Alpha test
  64940. if (material && material.needAlphaTesting()) {
  64941. var alphaTexture = material.getAlphaTestTexture();
  64942. if (alphaTexture) {
  64943. _this._effect.setTexture("diffuseSampler", alphaTexture);
  64944. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  64945. }
  64946. }
  64947. // Bones
  64948. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  64949. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  64950. }
  64951. // Draw
  64952. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  64953. }
  64954. };
  64955. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  64956. var index;
  64957. if (depthOnlySubMeshes.length) {
  64958. engine.setColorWrite(false);
  64959. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  64960. renderSubMesh(depthOnlySubMeshes.data[index]);
  64961. }
  64962. engine.setColorWrite(true);
  64963. }
  64964. for (index = 0; index < opaqueSubMeshes.length; index++) {
  64965. renderSubMesh(opaqueSubMeshes.data[index]);
  64966. }
  64967. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  64968. renderSubMesh(alphaTestSubMeshes.data[index]);
  64969. }
  64970. };
  64971. }
  64972. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  64973. var material = subMesh.getMaterial();
  64974. if (material.disableDepthWrite) {
  64975. return false;
  64976. }
  64977. var defines = [];
  64978. var attribs = [BABYLON.VertexBuffer.PositionKind];
  64979. var mesh = subMesh.getMesh();
  64980. // Alpha test
  64981. if (material && material.needAlphaTesting()) {
  64982. defines.push("#define ALPHATEST");
  64983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  64984. attribs.push(BABYLON.VertexBuffer.UVKind);
  64985. defines.push("#define UV1");
  64986. }
  64987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  64988. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  64989. defines.push("#define UV2");
  64990. }
  64991. }
  64992. // Bones
  64993. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  64994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  64995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  64996. if (mesh.numBoneInfluencers > 4) {
  64997. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  64998. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  64999. }
  65000. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65001. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65002. }
  65003. else {
  65004. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65005. }
  65006. // Instances
  65007. if (useInstances) {
  65008. defines.push("#define INSTANCES");
  65009. attribs.push("world0");
  65010. attribs.push("world1");
  65011. attribs.push("world2");
  65012. attribs.push("world3");
  65013. }
  65014. // Get correct effect
  65015. var join = defines.join("\n");
  65016. if (this._cachedDefines !== join) {
  65017. this._cachedDefines = join;
  65018. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  65019. }
  65020. return this._effect.isReady();
  65021. };
  65022. DepthRenderer.prototype.getDepthMap = function () {
  65023. return this._depthMap;
  65024. };
  65025. // Methods
  65026. DepthRenderer.prototype.dispose = function () {
  65027. this._depthMap.dispose();
  65028. };
  65029. return DepthRenderer;
  65030. }());
  65031. BABYLON.DepthRenderer = DepthRenderer;
  65032. })(BABYLON || (BABYLON = {}));
  65033. //# sourceMappingURL=babylon.depthRenderer.js.map
  65034. var BABYLON;
  65035. (function (BABYLON) {
  65036. var SSAORenderingPipeline = /** @class */ (function (_super) {
  65037. __extends(SSAORenderingPipeline, _super);
  65038. /**
  65039. * @constructor
  65040. * @param {string} name - The rendering pipeline name
  65041. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65042. * @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 }
  65043. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65044. */
  65045. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  65046. var _this = _super.call(this, scene.getEngine(), name) || this;
  65047. // Members
  65048. /**
  65049. * The PassPostProcess id in the pipeline that contains the original scene color
  65050. * @type {string}
  65051. */
  65052. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65053. /**
  65054. * The SSAO PostProcess id in the pipeline
  65055. * @type {string}
  65056. */
  65057. _this.SSAORenderEffect = "SSAORenderEffect";
  65058. /**
  65059. * The horizontal blur PostProcess id in the pipeline
  65060. * @type {string}
  65061. */
  65062. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65063. /**
  65064. * The vertical blur PostProcess id in the pipeline
  65065. * @type {string}
  65066. */
  65067. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65068. /**
  65069. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65070. * @type {string}
  65071. */
  65072. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65073. /**
  65074. * The output strength of the SSAO post-process. Default value is 1.0.
  65075. * @type {number}
  65076. */
  65077. _this.totalStrength = 1.0;
  65078. /**
  65079. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  65080. * @type {number}
  65081. */
  65082. _this.radius = 0.0001;
  65083. /**
  65084. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  65085. * Must not be equal to fallOff and superior to fallOff.
  65086. * Default value is 0.975
  65087. * @type {number}
  65088. */
  65089. _this.area = 0.0075;
  65090. /**
  65091. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  65092. * Must not be equal to area and inferior to area.
  65093. * Default value is 0.0
  65094. * @type {number}
  65095. */
  65096. _this.fallOff = 0.000001;
  65097. /**
  65098. * The base color of the SSAO post-process
  65099. * The final result is "base + ssao" between [0, 1]
  65100. * @type {number}
  65101. */
  65102. _this.base = 0.5;
  65103. _this._firstUpdate = true;
  65104. _this._scene = scene;
  65105. // Set up assets
  65106. _this._createRandomTexture();
  65107. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65108. var ssaoRatio = ratio.ssaoRatio || ratio;
  65109. var combineRatio = ratio.combineRatio || ratio;
  65110. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65111. _this._createSSAOPostProcess(ssaoRatio);
  65112. _this._createBlurPostProcess(ssaoRatio);
  65113. _this._createSSAOCombinePostProcess(combineRatio);
  65114. // Set up pipeline
  65115. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65116. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65117. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65118. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65119. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65120. // Finish
  65121. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65122. if (cameras)
  65123. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65124. return _this;
  65125. }
  65126. // Public Methods
  65127. /**
  65128. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65129. */
  65130. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65131. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65132. for (var i = 0; i < this._scene.cameras.length; i++) {
  65133. var camera = this._scene.cameras[i];
  65134. this._originalColorPostProcess.dispose(camera);
  65135. this._ssaoPostProcess.dispose(camera);
  65136. this._blurHPostProcess.dispose(camera);
  65137. this._blurVPostProcess.dispose(camera);
  65138. this._ssaoCombinePostProcess.dispose(camera);
  65139. }
  65140. this._randomTexture.dispose();
  65141. if (disableDepthRender)
  65142. this._scene.disableDepthRenderer();
  65143. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65144. _super.prototype.dispose.call(this);
  65145. };
  65146. // Private Methods
  65147. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  65148. var _this = this;
  65149. var size = 16;
  65150. 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);
  65151. 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);
  65152. this._blurHPostProcess.onActivateObservable.add(function () {
  65153. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  65154. _this._blurHPostProcess.kernel = size * dw;
  65155. });
  65156. this._blurVPostProcess.onActivateObservable.add(function () {
  65157. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  65158. _this._blurVPostProcess.kernel = size * dw;
  65159. });
  65160. };
  65161. SSAORenderingPipeline.prototype._rebuild = function () {
  65162. this._firstUpdate = true;
  65163. _super.prototype._rebuild.call(this);
  65164. };
  65165. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65166. var _this = this;
  65167. var numSamples = 16;
  65168. var sampleSphere = [
  65169. 0.5381, 0.1856, -0.4319,
  65170. 0.1379, 0.2486, 0.4430,
  65171. 0.3371, 0.5679, -0.0057,
  65172. -0.6999, -0.0451, -0.0019,
  65173. 0.0689, -0.1598, -0.8547,
  65174. 0.0560, 0.0069, -0.1843,
  65175. -0.0146, 0.1402, 0.0762,
  65176. 0.0100, -0.1924, -0.0344,
  65177. -0.3577, -0.5301, -0.4358,
  65178. -0.3169, 0.1063, 0.0158,
  65179. 0.0103, -0.5869, 0.0046,
  65180. -0.0897, -0.4940, 0.3287,
  65181. 0.7119, -0.0154, -0.0918,
  65182. -0.0533, 0.0596, -0.5411,
  65183. 0.0352, -0.0631, 0.5460,
  65184. -0.4776, 0.2847, -0.0271
  65185. ];
  65186. var samplesFactor = 1.0 / numSamples;
  65187. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  65188. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65189. "area", "fallOff", "base", "range", "viewport"
  65190. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65191. this._ssaoPostProcess.onApply = function (effect) {
  65192. if (_this._firstUpdate) {
  65193. effect.setArray3("sampleSphere", sampleSphere);
  65194. effect.setFloat("samplesFactor", samplesFactor);
  65195. effect.setFloat("randTextureTiles", 4.0);
  65196. }
  65197. effect.setFloat("totalStrength", _this.totalStrength);
  65198. effect.setFloat("radius", _this.radius);
  65199. effect.setFloat("area", _this.area);
  65200. effect.setFloat("fallOff", _this.fallOff);
  65201. effect.setFloat("base", _this.base);
  65202. effect.setTexture("textureSampler", _this._depthTexture);
  65203. effect.setTexture("randomSampler", _this._randomTexture);
  65204. };
  65205. };
  65206. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65207. var _this = this;
  65208. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65209. this._ssaoCombinePostProcess.onApply = function (effect) {
  65210. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65211. };
  65212. };
  65213. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  65214. var size = 512;
  65215. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65216. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65217. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65218. var context = this._randomTexture.getContext();
  65219. var rand = function (min, max) {
  65220. return Math.random() * (max - min) + min;
  65221. };
  65222. var randVector = BABYLON.Vector3.Zero();
  65223. for (var x = 0; x < size; x++) {
  65224. for (var y = 0; y < size; y++) {
  65225. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  65226. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  65227. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  65228. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65229. context.fillRect(x, y, 1, 1);
  65230. }
  65231. }
  65232. this._randomTexture.update(false);
  65233. };
  65234. __decorate([
  65235. BABYLON.serialize()
  65236. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  65237. __decorate([
  65238. BABYLON.serialize()
  65239. ], SSAORenderingPipeline.prototype, "radius", void 0);
  65240. __decorate([
  65241. BABYLON.serialize()
  65242. ], SSAORenderingPipeline.prototype, "area", void 0);
  65243. __decorate([
  65244. BABYLON.serialize()
  65245. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  65246. __decorate([
  65247. BABYLON.serialize()
  65248. ], SSAORenderingPipeline.prototype, "base", void 0);
  65249. return SSAORenderingPipeline;
  65250. }(BABYLON.PostProcessRenderPipeline));
  65251. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  65252. })(BABYLON || (BABYLON = {}));
  65253. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  65254. var BABYLON;
  65255. (function (BABYLON) {
  65256. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  65257. __extends(SSAO2RenderingPipeline, _super);
  65258. /**
  65259. * @constructor
  65260. * @param {string} name - The rendering pipeline name
  65261. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65262. * @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 }
  65263. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65264. */
  65265. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  65266. var _this = _super.call(this, scene.getEngine(), name) || this;
  65267. // Members
  65268. /**
  65269. * The PassPostProcess id in the pipeline that contains the original scene color
  65270. * @type {string}
  65271. */
  65272. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65273. /**
  65274. * The SSAO PostProcess id in the pipeline
  65275. * @type {string}
  65276. */
  65277. _this.SSAORenderEffect = "SSAORenderEffect";
  65278. /**
  65279. * The horizontal blur PostProcess id in the pipeline
  65280. * @type {string}
  65281. */
  65282. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65283. /**
  65284. * The vertical blur PostProcess id in the pipeline
  65285. * @type {string}
  65286. */
  65287. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65288. /**
  65289. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65290. * @type {string}
  65291. */
  65292. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65293. /**
  65294. * The output strength of the SSAO post-process. Default value is 1.0.
  65295. * @type {number}
  65296. */
  65297. _this.totalStrength = 1.0;
  65298. /**
  65299. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  65300. * @type {number}
  65301. */
  65302. _this.maxZ = 100.0;
  65303. /**
  65304. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  65305. * @type {number}
  65306. */
  65307. _this.minZAspect = 0.2;
  65308. /**
  65309. * Number of samples used for the SSAO calculations. Default value is 8
  65310. * @type {number}
  65311. */
  65312. _this._samples = 8;
  65313. /**
  65314. * Are we using bilateral blur ?
  65315. * @type {boolean}
  65316. */
  65317. _this._expensiveBlur = true;
  65318. /**
  65319. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65320. * @type {number}
  65321. */
  65322. _this.radius = 2.0;
  65323. /**
  65324. * The base color of the SSAO post-process
  65325. * The final result is "base + ssao" between [0, 1]
  65326. * @type {number}
  65327. */
  65328. _this.base = 0.1;
  65329. _this._firstUpdate = true;
  65330. _this._scene = scene;
  65331. if (!_this.isSupported) {
  65332. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65333. return _this;
  65334. }
  65335. var ssaoRatio = ratio.ssaoRatio || ratio;
  65336. var blurRatio = ratio.blurRatio || ratio;
  65337. // Set up assets
  65338. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65339. _this._createRandomTexture();
  65340. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65341. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65342. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65343. _this._createSSAOPostProcess(1.0);
  65344. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65345. _this._createSSAOCombinePostProcess(blurRatio);
  65346. // Set up pipeline
  65347. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65348. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65349. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65350. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65351. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65352. // Finish
  65353. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65354. if (cameras)
  65355. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65356. return _this;
  65357. }
  65358. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65359. get: function () {
  65360. return this._samples;
  65361. },
  65362. set: function (n) {
  65363. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65364. this._samples = n;
  65365. this._sampleSphere = this._generateHemisphere();
  65366. this._firstUpdate = true;
  65367. },
  65368. enumerable: true,
  65369. configurable: true
  65370. });
  65371. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65372. get: function () {
  65373. return this._expensiveBlur;
  65374. },
  65375. set: function (b) {
  65376. 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"]);
  65377. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65378. this._expensiveBlur = b;
  65379. this._firstUpdate = true;
  65380. },
  65381. enumerable: true,
  65382. configurable: true
  65383. });
  65384. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65385. /**
  65386. * Support test.
  65387. * @type {boolean}
  65388. */
  65389. get: function () {
  65390. var engine = BABYLON.Engine.LastCreatedEngine;
  65391. if (!engine) {
  65392. return false;
  65393. }
  65394. return engine.getCaps().drawBuffersExtension;
  65395. },
  65396. enumerable: true,
  65397. configurable: true
  65398. });
  65399. // Public Methods
  65400. /**
  65401. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65402. */
  65403. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65404. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65405. for (var i = 0; i < this._scene.cameras.length; i++) {
  65406. var camera = this._scene.cameras[i];
  65407. this._originalColorPostProcess.dispose(camera);
  65408. this._ssaoPostProcess.dispose(camera);
  65409. this._blurHPostProcess.dispose(camera);
  65410. this._blurVPostProcess.dispose(camera);
  65411. this._ssaoCombinePostProcess.dispose(camera);
  65412. }
  65413. this._randomTexture.dispose();
  65414. if (disableGeometryBufferRenderer)
  65415. this._scene.disableGeometryBufferRenderer();
  65416. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65417. _super.prototype.dispose.call(this);
  65418. };
  65419. // Private Methods
  65420. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65421. var _this = this;
  65422. this._samplerOffsets = [];
  65423. var expensive = this.expensiveBlur;
  65424. for (var i = -8; i < 8; i++) {
  65425. this._samplerOffsets.push(i * 2 + 0.5);
  65426. }
  65427. 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");
  65428. this._blurHPostProcess.onApply = function (effect) {
  65429. if (!_this._scene.activeCamera) {
  65430. return;
  65431. }
  65432. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65433. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65434. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65435. effect.setFloat("radius", _this.radius);
  65436. effect.setTexture("depthSampler", _this._depthTexture);
  65437. if (_this._firstUpdate) {
  65438. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65439. }
  65440. };
  65441. 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");
  65442. this._blurVPostProcess.onApply = function (effect) {
  65443. if (!_this._scene.activeCamera) {
  65444. return;
  65445. }
  65446. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65447. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65448. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65449. effect.setFloat("radius", _this.radius);
  65450. effect.setTexture("depthSampler", _this._depthTexture);
  65451. if (_this._firstUpdate) {
  65452. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65453. _this._firstUpdate = false;
  65454. }
  65455. };
  65456. };
  65457. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65458. this._firstUpdate = true;
  65459. _super.prototype._rebuild.call(this);
  65460. };
  65461. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65462. var numSamples = this.samples;
  65463. var result = [];
  65464. var vector, scale;
  65465. var rand = function (min, max) {
  65466. return Math.random() * (max - min) + min;
  65467. };
  65468. var i = 0;
  65469. while (i < numSamples) {
  65470. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65471. vector.normalize();
  65472. scale = i / numSamples;
  65473. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65474. vector.scaleInPlace(scale);
  65475. result.push(vector.x, vector.y, vector.z);
  65476. i++;
  65477. }
  65478. return result;
  65479. };
  65480. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65481. var _this = this;
  65482. var numSamples = this.samples;
  65483. this._sampleSphere = this._generateHemisphere();
  65484. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65485. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65486. "base", "range", "projection", "near", "far", "texelSize",
  65487. "xViewport", "yViewport", "maxZ", "minZAspect"
  65488. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65489. this._ssaoPostProcess.onApply = function (effect) {
  65490. if (_this._firstUpdate) {
  65491. effect.setArray3("sampleSphere", _this._sampleSphere);
  65492. effect.setFloat("randTextureTiles", 4.0);
  65493. }
  65494. if (!_this._scene.activeCamera) {
  65495. return;
  65496. }
  65497. effect.setFloat("samplesFactor", 1 / _this.samples);
  65498. effect.setFloat("totalStrength", _this.totalStrength);
  65499. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65500. effect.setFloat("radius", _this.radius);
  65501. effect.setFloat("maxZ", _this.maxZ);
  65502. effect.setFloat("minZAspect", _this.minZAspect);
  65503. effect.setFloat("base", _this.base);
  65504. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65505. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65506. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65507. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65508. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65509. effect.setTexture("textureSampler", _this._depthTexture);
  65510. effect.setTexture("normalSampler", _this._normalTexture);
  65511. effect.setTexture("randomSampler", _this._randomTexture);
  65512. };
  65513. };
  65514. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65515. var _this = this;
  65516. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65517. this._ssaoCombinePostProcess.onApply = function (effect) {
  65518. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65519. };
  65520. };
  65521. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65522. var size = 512;
  65523. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65524. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65525. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65526. var context = this._randomTexture.getContext();
  65527. var rand = function (min, max) {
  65528. return Math.random() * (max - min) + min;
  65529. };
  65530. var randVector = BABYLON.Vector3.Zero();
  65531. for (var x = 0; x < size; x++) {
  65532. for (var y = 0; y < size; y++) {
  65533. randVector.x = rand(0.0, 1.0);
  65534. randVector.y = rand(0.0, 1.0);
  65535. randVector.z = 0.0;
  65536. randVector.normalize();
  65537. randVector.scaleInPlace(255);
  65538. randVector.x = Math.floor(randVector.x);
  65539. randVector.y = Math.floor(randVector.y);
  65540. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65541. context.fillRect(x, y, 1, 1);
  65542. }
  65543. }
  65544. this._randomTexture.update(false);
  65545. };
  65546. __decorate([
  65547. BABYLON.serialize()
  65548. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65549. __decorate([
  65550. BABYLON.serialize()
  65551. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65552. __decorate([
  65553. BABYLON.serialize()
  65554. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65555. __decorate([
  65556. BABYLON.serialize("samples")
  65557. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65558. __decorate([
  65559. BABYLON.serialize("expensiveBlur")
  65560. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65561. __decorate([
  65562. BABYLON.serialize()
  65563. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65564. __decorate([
  65565. BABYLON.serialize()
  65566. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65567. return SSAO2RenderingPipeline;
  65568. }(BABYLON.PostProcessRenderPipeline));
  65569. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65570. })(BABYLON || (BABYLON = {}));
  65571. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65572. // BABYLON.JS Chromatic Aberration GLSL Shader
  65573. // Author: Olivier Guyot
  65574. // Separates very slightly R, G and B colors on the edges of the screen
  65575. // Inspired by Francois Tarlier & Martins Upitis
  65576. var BABYLON;
  65577. (function (BABYLON) {
  65578. var LensRenderingPipeline = /** @class */ (function (_super) {
  65579. __extends(LensRenderingPipeline, _super);
  65580. /**
  65581. * @constructor
  65582. *
  65583. * Effect parameters are as follow:
  65584. * {
  65585. * chromatic_aberration: number; // from 0 to x (1 for realism)
  65586. * edge_blur: number; // from 0 to x (1 for realism)
  65587. * distortion: number; // from 0 to x (1 for realism)
  65588. * grain_amount: number; // from 0 to 1
  65589. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  65590. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  65591. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  65592. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  65593. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  65594. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  65595. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  65596. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  65597. * }
  65598. * Note: if an effect parameter is unset, effect is disabled
  65599. *
  65600. * @param {string} name - The rendering pipeline name
  65601. * @param {object} parameters - An object containing all parameters (see above)
  65602. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65603. * @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)
  65604. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65605. */
  65606. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  65607. if (ratio === void 0) { ratio = 1.0; }
  65608. var _this = _super.call(this, scene.getEngine(), name) || this;
  65609. // Lens effects can be of the following:
  65610. // - chromatic aberration (slight shift of RGB colors)
  65611. // - blur on the edge of the lens
  65612. // - lens distortion
  65613. // - depth-of-field blur & highlights enhancing
  65614. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  65615. // - grain effect (noise or custom texture)
  65616. // Two additional texture samplers are needed:
  65617. // - depth map (for depth-of-field)
  65618. // - grain texture
  65619. /**
  65620. * The chromatic aberration PostProcess id in the pipeline
  65621. * @type {string}
  65622. */
  65623. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  65624. /**
  65625. * The highlights enhancing PostProcess id in the pipeline
  65626. * @type {string}
  65627. */
  65628. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  65629. /**
  65630. * The depth-of-field PostProcess id in the pipeline
  65631. * @type {string}
  65632. */
  65633. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  65634. _this._scene = scene;
  65635. // Fetch texture samplers
  65636. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65637. if (parameters.grain_texture) {
  65638. _this._grainTexture = parameters.grain_texture;
  65639. }
  65640. else {
  65641. _this._createGrainTexture();
  65642. }
  65643. // save parameters
  65644. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  65645. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  65646. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  65647. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  65648. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  65649. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  65650. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  65651. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  65652. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  65653. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  65654. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  65655. // Create effects
  65656. _this._createChromaticAberrationPostProcess(ratio);
  65657. _this._createHighlightsPostProcess(ratio);
  65658. _this._createDepthOfFieldPostProcess(ratio / 4);
  65659. // Set up pipeline
  65660. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  65661. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  65662. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  65663. if (_this._highlightsGain === -1) {
  65664. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  65665. }
  65666. // Finish
  65667. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65668. if (cameras) {
  65669. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65670. }
  65671. return _this;
  65672. }
  65673. // public methods (self explanatory)
  65674. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  65675. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  65676. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  65677. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  65678. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  65679. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  65680. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  65681. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  65682. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  65683. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  65684. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  65685. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  65686. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  65687. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  65688. };
  65689. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  65690. this._highlightsPostProcess.updateEffect();
  65691. };
  65692. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  65693. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  65694. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  65695. this._highlightsGain = amount;
  65696. };
  65697. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  65698. if (this._highlightsGain === -1) {
  65699. this._highlightsGain = 1.0;
  65700. }
  65701. this._highlightsThreshold = amount;
  65702. };
  65703. LensRenderingPipeline.prototype.disableHighlights = function () {
  65704. this._highlightsGain = -1;
  65705. };
  65706. /**
  65707. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  65708. */
  65709. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65710. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65711. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65712. this._chromaticAberrationPostProcess = null;
  65713. this._highlightsPostProcess = null;
  65714. this._depthOfFieldPostProcess = null;
  65715. this._grainTexture.dispose();
  65716. if (disableDepthRender)
  65717. this._scene.disableDepthRenderer();
  65718. };
  65719. // colors shifting and distortion
  65720. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  65721. var _this = this;
  65722. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  65723. [], // samplers
  65724. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65725. this._chromaticAberrationPostProcess.onApply = function (effect) {
  65726. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  65727. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65728. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65729. };
  65730. };
  65731. // highlights enhancing
  65732. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  65733. var _this = this;
  65734. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  65735. [], // samplers
  65736. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  65737. this._highlightsPostProcess.onApply = function (effect) {
  65738. effect.setFloat('gain', _this._highlightsGain);
  65739. effect.setFloat('threshold', _this._highlightsThreshold);
  65740. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  65741. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65742. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65743. };
  65744. };
  65745. // colors shifting and distortion
  65746. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  65747. var _this = this;
  65748. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  65749. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  65750. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  65751. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65752. this._depthOfFieldPostProcess.onApply = function (effect) {
  65753. effect.setTexture("depthSampler", _this._depthTexture);
  65754. effect.setTexture("grainSampler", _this._grainTexture);
  65755. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  65756. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  65757. effect.setFloat('grain_amount', _this._grainAmount);
  65758. effect.setBool('blur_noise', _this._blurNoise);
  65759. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  65760. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  65761. effect.setFloat('distortion', _this._distortion);
  65762. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  65763. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  65764. effect.setFloat('aperture', _this._dofAperture);
  65765. effect.setFloat('darken', _this._dofDarken);
  65766. effect.setFloat('edge_blur', _this._edgeBlur);
  65767. effect.setBool('highlights', (_this._highlightsGain !== -1));
  65768. if (_this._scene.activeCamera) {
  65769. effect.setFloat('near', _this._scene.activeCamera.minZ);
  65770. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  65771. }
  65772. };
  65773. };
  65774. // creates a black and white random noise texture, 512x512
  65775. LensRenderingPipeline.prototype._createGrainTexture = function () {
  65776. var size = 512;
  65777. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65778. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65779. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65780. var context = this._grainTexture.getContext();
  65781. var rand = function (min, max) {
  65782. return Math.random() * (max - min) + min;
  65783. };
  65784. var value;
  65785. for (var x = 0; x < size; x++) {
  65786. for (var y = 0; y < size; y++) {
  65787. value = Math.floor(rand(0.42, 0.58) * 255);
  65788. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  65789. context.fillRect(x, y, 1, 1);
  65790. }
  65791. }
  65792. this._grainTexture.update(false);
  65793. };
  65794. return LensRenderingPipeline;
  65795. }(BABYLON.PostProcessRenderPipeline));
  65796. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  65797. })(BABYLON || (BABYLON = {}));
  65798. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  65799. var BABYLON;
  65800. (function (BABYLON) {
  65801. var StandardRenderingPipeline = /** @class */ (function (_super) {
  65802. __extends(StandardRenderingPipeline, _super);
  65803. /**
  65804. * @constructor
  65805. * @param {string} name - The rendering pipeline name
  65806. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65807. * @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)
  65808. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  65809. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65810. */
  65811. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  65812. if (originalPostProcess === void 0) { originalPostProcess = null; }
  65813. var _this = _super.call(this, scene.getEngine(), name) || this;
  65814. _this.downSampleX4PostProcess = null;
  65815. _this.brightPassPostProcess = null;
  65816. _this.blurHPostProcesses = [];
  65817. _this.blurVPostProcesses = [];
  65818. _this.textureAdderPostProcess = null;
  65819. _this.volumetricLightPostProcess = null;
  65820. _this.volumetricLightSmoothXPostProcess = null;
  65821. _this.volumetricLightSmoothYPostProcess = null;
  65822. _this.volumetricLightMergePostProces = null;
  65823. _this.volumetricLightFinalPostProcess = null;
  65824. _this.luminancePostProcess = null;
  65825. _this.luminanceDownSamplePostProcesses = [];
  65826. _this.hdrPostProcess = null;
  65827. _this.textureAdderFinalPostProcess = null;
  65828. _this.lensFlareFinalPostProcess = null;
  65829. _this.hdrFinalPostProcess = null;
  65830. _this.lensFlarePostProcess = null;
  65831. _this.lensFlareComposePostProcess = null;
  65832. _this.motionBlurPostProcess = null;
  65833. _this.depthOfFieldPostProcess = null;
  65834. // Values
  65835. _this.brightThreshold = 1.0;
  65836. _this.blurWidth = 512.0;
  65837. _this.horizontalBlur = false;
  65838. _this.exposure = 1.0;
  65839. _this.lensTexture = null;
  65840. _this.volumetricLightCoefficient = 0.2;
  65841. _this.volumetricLightPower = 4.0;
  65842. _this.volumetricLightBlurScale = 64.0;
  65843. _this.sourceLight = null;
  65844. _this.hdrMinimumLuminance = 1.0;
  65845. _this.hdrDecreaseRate = 0.5;
  65846. _this.hdrIncreaseRate = 0.5;
  65847. _this.lensColorTexture = null;
  65848. _this.lensFlareStrength = 20.0;
  65849. _this.lensFlareGhostDispersal = 1.4;
  65850. _this.lensFlareHaloWidth = 0.7;
  65851. _this.lensFlareDistortionStrength = 16.0;
  65852. _this.lensStarTexture = null;
  65853. _this.lensFlareDirtTexture = null;
  65854. _this.depthOfFieldDistance = 10.0;
  65855. _this.depthOfFieldBlurWidth = 64.0;
  65856. _this.motionStrength = 1.0;
  65857. // IAnimatable
  65858. _this.animations = [];
  65859. _this._currentDepthOfFieldSource = null;
  65860. _this._hdrCurrentLuminance = 1.0;
  65861. // Getters and setters
  65862. _this._bloomEnabled = true;
  65863. _this._depthOfFieldEnabled = false;
  65864. _this._vlsEnabled = false;
  65865. _this._lensFlareEnabled = false;
  65866. _this._hdrEnabled = false;
  65867. _this._motionBlurEnabled = false;
  65868. _this._motionBlurSamples = 64.0;
  65869. _this._volumetricLightStepsCount = 50.0;
  65870. _this._cameras = cameras || [];
  65871. // Initialize
  65872. _this._scene = scene;
  65873. _this._basePostProcess = originalPostProcess;
  65874. _this._ratio = ratio;
  65875. // Misc
  65876. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65877. // Finish
  65878. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65879. _this._buildPipeline();
  65880. return _this;
  65881. }
  65882. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  65883. get: function () {
  65884. return this._bloomEnabled;
  65885. },
  65886. set: function (enabled) {
  65887. if (this._bloomEnabled === enabled) {
  65888. return;
  65889. }
  65890. this._bloomEnabled = enabled;
  65891. this._buildPipeline();
  65892. },
  65893. enumerable: true,
  65894. configurable: true
  65895. });
  65896. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  65897. get: function () {
  65898. return this._depthOfFieldEnabled;
  65899. },
  65900. set: function (enabled) {
  65901. if (this._depthOfFieldEnabled === enabled) {
  65902. return;
  65903. }
  65904. this._depthOfFieldEnabled = enabled;
  65905. this._buildPipeline();
  65906. },
  65907. enumerable: true,
  65908. configurable: true
  65909. });
  65910. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  65911. get: function () {
  65912. return this._lensFlareEnabled;
  65913. },
  65914. set: function (enabled) {
  65915. if (this._lensFlareEnabled === enabled) {
  65916. return;
  65917. }
  65918. this._lensFlareEnabled = enabled;
  65919. this._buildPipeline();
  65920. },
  65921. enumerable: true,
  65922. configurable: true
  65923. });
  65924. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  65925. get: function () {
  65926. return this._hdrEnabled;
  65927. },
  65928. set: function (enabled) {
  65929. if (this._hdrEnabled === enabled) {
  65930. return;
  65931. }
  65932. this._hdrEnabled = enabled;
  65933. this._buildPipeline();
  65934. },
  65935. enumerable: true,
  65936. configurable: true
  65937. });
  65938. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  65939. get: function () {
  65940. return this._vlsEnabled;
  65941. },
  65942. set: function (enabled) {
  65943. if (this._vlsEnabled === enabled) {
  65944. return;
  65945. }
  65946. if (enabled) {
  65947. var geometry = this._scene.enableGeometryBufferRenderer();
  65948. if (!geometry) {
  65949. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  65950. return;
  65951. }
  65952. }
  65953. this._vlsEnabled = enabled;
  65954. this._buildPipeline();
  65955. },
  65956. enumerable: true,
  65957. configurable: true
  65958. });
  65959. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  65960. get: function () {
  65961. return this._motionBlurEnabled;
  65962. },
  65963. set: function (enabled) {
  65964. if (this._motionBlurEnabled === enabled) {
  65965. return;
  65966. }
  65967. this._motionBlurEnabled = enabled;
  65968. this._buildPipeline();
  65969. },
  65970. enumerable: true,
  65971. configurable: true
  65972. });
  65973. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  65974. get: function () {
  65975. return this._volumetricLightStepsCount;
  65976. },
  65977. set: function (count) {
  65978. if (this.volumetricLightPostProcess) {
  65979. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  65980. }
  65981. this._volumetricLightStepsCount = count;
  65982. },
  65983. enumerable: true,
  65984. configurable: true
  65985. });
  65986. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  65987. get: function () {
  65988. return this._motionBlurSamples;
  65989. },
  65990. set: function (samples) {
  65991. if (this.motionBlurPostProcess) {
  65992. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  65993. }
  65994. this._motionBlurSamples = samples;
  65995. },
  65996. enumerable: true,
  65997. configurable: true
  65998. });
  65999. StandardRenderingPipeline.prototype._buildPipeline = function () {
  66000. var _this = this;
  66001. var ratio = this._ratio;
  66002. var scene = this._scene;
  66003. this._disposePostProcesses();
  66004. this._reset();
  66005. // Create pass post-process
  66006. if (!this._basePostProcess) {
  66007. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  66008. this.originalPostProcess.onApply = function (effect) {
  66009. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  66010. };
  66011. }
  66012. else {
  66013. this.originalPostProcess = this._basePostProcess;
  66014. }
  66015. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  66016. this._currentDepthOfFieldSource = this.originalPostProcess;
  66017. if (this._vlsEnabled) {
  66018. // Create volumetric light
  66019. this._createVolumetricLightPostProcess(scene, ratio);
  66020. // Create volumetric light final post-process
  66021. 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);
  66022. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  66023. }
  66024. if (this._bloomEnabled) {
  66025. // Create down sample X4 post-process
  66026. this._createDownSampleX4PostProcess(scene, ratio / 2);
  66027. // Create bright pass post-process
  66028. this._createBrightPassPostProcess(scene, ratio / 2);
  66029. // Create gaussian blur post-processes (down sampling blurs)
  66030. this._createBlurPostProcesses(scene, ratio / 4, 1);
  66031. // Create texture adder post-process
  66032. this._createTextureAdderPostProcess(scene, ratio);
  66033. // Create depth-of-field source post-process
  66034. 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);
  66035. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  66036. }
  66037. if (this._lensFlareEnabled) {
  66038. // Create lens flare post-process
  66039. this._createLensFlarePostProcess(scene, ratio);
  66040. // Create depth-of-field source post-process post lens-flare and disable it now
  66041. 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);
  66042. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  66043. }
  66044. if (this._hdrEnabled) {
  66045. // Create luminance
  66046. this._createLuminancePostProcesses(scene, this._floatTextureType);
  66047. // Create HDR
  66048. this._createHdrPostProcess(scene, ratio);
  66049. // Create depth-of-field source post-process post hdr and disable it now
  66050. 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);
  66051. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  66052. }
  66053. if (this._depthOfFieldEnabled) {
  66054. // Create gaussian blur used by depth-of-field
  66055. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  66056. // Create depth-of-field post-process
  66057. this._createDepthOfFieldPostProcess(scene, ratio);
  66058. }
  66059. if (this._motionBlurEnabled) {
  66060. // Create motion blur post-process
  66061. this._createMotionBlurPostProcess(scene, ratio);
  66062. }
  66063. if (this._cameras !== null) {
  66064. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66065. }
  66066. };
  66067. // Down Sample X4 Post-Processs
  66068. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  66069. var _this = this;
  66070. var downSampleX4Offsets = new Array(32);
  66071. 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);
  66072. this.downSampleX4PostProcess.onApply = function (effect) {
  66073. var id = 0;
  66074. var width = _this.downSampleX4PostProcess.width;
  66075. var height = _this.downSampleX4PostProcess.height;
  66076. for (var i = -2; i < 2; i++) {
  66077. for (var j = -2; j < 2; j++) {
  66078. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  66079. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  66080. id += 2;
  66081. }
  66082. }
  66083. effect.setArray2("dsOffsets", downSampleX4Offsets);
  66084. };
  66085. // Add to pipeline
  66086. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  66087. };
  66088. // Brightpass Post-Process
  66089. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  66090. var _this = this;
  66091. var brightOffsets = new Array(8);
  66092. 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);
  66093. this.brightPassPostProcess.onApply = function (effect) {
  66094. var sU = (1.0 / _this.brightPassPostProcess.width);
  66095. var sV = (1.0 / _this.brightPassPostProcess.height);
  66096. brightOffsets[0] = -0.5 * sU;
  66097. brightOffsets[1] = 0.5 * sV;
  66098. brightOffsets[2] = 0.5 * sU;
  66099. brightOffsets[3] = 0.5 * sV;
  66100. brightOffsets[4] = -0.5 * sU;
  66101. brightOffsets[5] = -0.5 * sV;
  66102. brightOffsets[6] = 0.5 * sU;
  66103. brightOffsets[7] = -0.5 * sV;
  66104. effect.setArray2("dsOffsets", brightOffsets);
  66105. effect.setFloat("brightThreshold", _this.brightThreshold);
  66106. };
  66107. // Add to pipeline
  66108. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  66109. };
  66110. // Create blur H&V post-processes
  66111. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  66112. var _this = this;
  66113. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  66114. var engine = scene.getEngine();
  66115. 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);
  66116. 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);
  66117. blurX.onActivateObservable.add(function () {
  66118. var dw = blurX.width / engine.getRenderWidth();
  66119. blurX.kernel = _this[blurWidthKey] * dw;
  66120. });
  66121. blurY.onActivateObservable.add(function () {
  66122. var dw = blurY.height / engine.getRenderHeight();
  66123. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  66124. });
  66125. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  66126. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  66127. this.blurHPostProcesses.push(blurX);
  66128. this.blurVPostProcesses.push(blurY);
  66129. };
  66130. // Create texture adder post-process
  66131. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  66132. var _this = this;
  66133. 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);
  66134. this.textureAdderPostProcess.onApply = function (effect) {
  66135. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  66136. effect.setTexture("lensSampler", _this.lensTexture);
  66137. effect.setFloat("exposure", _this.exposure);
  66138. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  66139. };
  66140. // Add to pipeline
  66141. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  66142. };
  66143. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  66144. var _this = this;
  66145. var geometryRenderer = scene.enableGeometryBufferRenderer();
  66146. geometryRenderer.enablePosition = true;
  66147. var geometry = geometryRenderer.getGBuffer();
  66148. // Base post-process
  66149. 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));
  66150. var depthValues = BABYLON.Vector2.Zero();
  66151. this.volumetricLightPostProcess.onApply = function (effect) {
  66152. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  66153. var generator = _this.sourceLight.getShadowGenerator();
  66154. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  66155. effect.setTexture("positionSampler", geometry.textures[2]);
  66156. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  66157. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  66158. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  66159. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  66160. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  66161. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  66162. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  66163. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  66164. effect.setVector2("depthValues", depthValues);
  66165. }
  66166. };
  66167. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  66168. // Smooth
  66169. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  66170. // Merge
  66171. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  66172. this.volumetricLightMergePostProces.onApply = function (effect) {
  66173. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  66174. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  66175. };
  66176. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  66177. };
  66178. // Create luminance
  66179. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  66180. var _this = this;
  66181. // Create luminance
  66182. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  66183. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  66184. var offsets = [];
  66185. this.luminancePostProcess.onApply = function (effect) {
  66186. var sU = (1.0 / _this.luminancePostProcess.width);
  66187. var sV = (1.0 / _this.luminancePostProcess.height);
  66188. offsets[0] = -0.5 * sU;
  66189. offsets[1] = 0.5 * sV;
  66190. offsets[2] = 0.5 * sU;
  66191. offsets[3] = 0.5 * sV;
  66192. offsets[4] = -0.5 * sU;
  66193. offsets[5] = -0.5 * sV;
  66194. offsets[6] = 0.5 * sU;
  66195. offsets[7] = -0.5 * sV;
  66196. effect.setArray2("lumOffsets", offsets);
  66197. };
  66198. // Add to pipeline
  66199. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  66200. // Create down sample luminance
  66201. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  66202. var size = Math.pow(3, i);
  66203. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  66204. if (i === 0) {
  66205. defines += "#define FINAL_DOWN_SAMPLER";
  66206. }
  66207. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  66208. this.luminanceDownSamplePostProcesses.push(postProcess);
  66209. }
  66210. // Create callbacks and add effects
  66211. var lastLuminance = this.luminancePostProcess;
  66212. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  66213. var downSampleOffsets = new Array(18);
  66214. pp.onApply = function (effect) {
  66215. if (!lastLuminance) {
  66216. return;
  66217. }
  66218. var id = 0;
  66219. for (var x = -1; x < 2; x++) {
  66220. for (var y = -1; y < 2; y++) {
  66221. downSampleOffsets[id] = x / lastLuminance.width;
  66222. downSampleOffsets[id + 1] = y / lastLuminance.height;
  66223. id += 2;
  66224. }
  66225. }
  66226. effect.setArray2("dsOffsets", downSampleOffsets);
  66227. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  66228. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66229. lastLuminance = _this.luminancePostProcess;
  66230. }
  66231. else {
  66232. lastLuminance = pp;
  66233. }
  66234. };
  66235. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66236. pp.onAfterRender = function (effect) {
  66237. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  66238. 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);
  66239. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  66240. };
  66241. }
  66242. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  66243. });
  66244. };
  66245. // Create HDR post-process
  66246. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  66247. var _this = this;
  66248. 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);
  66249. var outputLiminance = 1;
  66250. var time = 0;
  66251. var lastTime = 0;
  66252. this.hdrPostProcess.onApply = function (effect) {
  66253. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  66254. time += scene.getEngine().getDeltaTime();
  66255. if (outputLiminance < 0) {
  66256. outputLiminance = _this._hdrCurrentLuminance;
  66257. }
  66258. else {
  66259. var dt = (lastTime - time) / 1000.0;
  66260. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  66261. outputLiminance += _this.hdrDecreaseRate * dt;
  66262. }
  66263. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  66264. outputLiminance -= _this.hdrIncreaseRate * dt;
  66265. }
  66266. else {
  66267. outputLiminance = _this._hdrCurrentLuminance;
  66268. }
  66269. }
  66270. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  66271. effect.setFloat("averageLuminance", outputLiminance);
  66272. lastTime = time;
  66273. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  66274. };
  66275. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  66276. };
  66277. // Create lens flare post-process
  66278. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  66279. var _this = this;
  66280. 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);
  66281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  66282. this._createBlurPostProcesses(scene, ratio / 4, 2);
  66283. 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);
  66284. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  66285. var resolution = new BABYLON.Vector2(0, 0);
  66286. // Lens flare
  66287. this.lensFlarePostProcess.onApply = function (effect) {
  66288. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  66289. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  66290. effect.setFloat("strength", _this.lensFlareStrength);
  66291. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  66292. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  66293. // Shift
  66294. resolution.x = _this.lensFlarePostProcess.width;
  66295. resolution.y = _this.lensFlarePostProcess.height;
  66296. effect.setVector2("resolution", resolution);
  66297. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  66298. };
  66299. // Compose
  66300. 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);
  66301. 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);
  66302. this.lensFlareComposePostProcess.onApply = function (effect) {
  66303. if (!_this._scene.activeCamera) {
  66304. return;
  66305. }
  66306. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66307. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  66308. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  66309. // Lens start rotation matrix
  66310. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  66311. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  66312. 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));
  66313. camRot *= 4.0;
  66314. 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);
  66315. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  66316. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  66317. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  66318. };
  66319. };
  66320. // Create depth-of-field post-process
  66321. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66322. var _this = this;
  66323. 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);
  66324. this.depthOfFieldPostProcess.onApply = function (effect) {
  66325. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66326. effect.setTexture("depthSampler", _this._getDepthTexture());
  66327. effect.setFloat("distance", _this.depthOfFieldDistance);
  66328. };
  66329. // Add to pipeline
  66330. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66331. };
  66332. // Create motion blur post-process
  66333. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66334. var _this = this;
  66335. 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);
  66336. var motionScale = 0;
  66337. var prevViewProjection = BABYLON.Matrix.Identity();
  66338. var invViewProjection = BABYLON.Matrix.Identity();
  66339. var viewProjection = BABYLON.Matrix.Identity();
  66340. var screenSize = BABYLON.Vector2.Zero();
  66341. this.motionBlurPostProcess.onApply = function (effect) {
  66342. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66343. viewProjection.invertToRef(invViewProjection);
  66344. effect.setMatrix("inverseViewProjection", invViewProjection);
  66345. effect.setMatrix("prevViewProjection", prevViewProjection);
  66346. prevViewProjection = viewProjection;
  66347. screenSize.x = _this.motionBlurPostProcess.width;
  66348. screenSize.y = _this.motionBlurPostProcess.height;
  66349. effect.setVector2("screenSize", screenSize);
  66350. motionScale = scene.getEngine().getFps() / 60.0;
  66351. effect.setFloat("motionScale", motionScale);
  66352. effect.setFloat("motionStrength", _this.motionStrength);
  66353. effect.setTexture("depthSampler", _this._getDepthTexture());
  66354. };
  66355. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66356. };
  66357. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66358. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66359. var renderer = this._scene.enableGeometryBufferRenderer();
  66360. return renderer.getGBuffer().textures[0];
  66361. }
  66362. return this._scene.enableDepthRenderer().getDepthMap();
  66363. };
  66364. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66365. for (var i = 0; i < this._cameras.length; i++) {
  66366. var camera = this._cameras[i];
  66367. if (this.originalPostProcess) {
  66368. this.originalPostProcess.dispose(camera);
  66369. }
  66370. if (this.downSampleX4PostProcess) {
  66371. this.downSampleX4PostProcess.dispose(camera);
  66372. }
  66373. if (this.brightPassPostProcess) {
  66374. this.brightPassPostProcess.dispose(camera);
  66375. }
  66376. if (this.textureAdderPostProcess) {
  66377. this.textureAdderPostProcess.dispose(camera);
  66378. }
  66379. if (this.textureAdderFinalPostProcess) {
  66380. this.textureAdderFinalPostProcess.dispose(camera);
  66381. }
  66382. if (this.volumetricLightPostProcess) {
  66383. this.volumetricLightPostProcess.dispose(camera);
  66384. }
  66385. if (this.volumetricLightSmoothXPostProcess) {
  66386. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66387. }
  66388. if (this.volumetricLightSmoothYPostProcess) {
  66389. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66390. }
  66391. if (this.volumetricLightMergePostProces) {
  66392. this.volumetricLightMergePostProces.dispose(camera);
  66393. }
  66394. if (this.volumetricLightFinalPostProcess) {
  66395. this.volumetricLightFinalPostProcess.dispose(camera);
  66396. }
  66397. if (this.lensFlarePostProcess) {
  66398. this.lensFlarePostProcess.dispose(camera);
  66399. }
  66400. if (this.lensFlareComposePostProcess) {
  66401. this.lensFlareComposePostProcess.dispose(camera);
  66402. }
  66403. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66404. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66405. }
  66406. if (this.luminancePostProcess) {
  66407. this.luminancePostProcess.dispose(camera);
  66408. }
  66409. if (this.hdrPostProcess) {
  66410. this.hdrPostProcess.dispose(camera);
  66411. }
  66412. if (this.hdrFinalPostProcess) {
  66413. this.hdrFinalPostProcess.dispose(camera);
  66414. }
  66415. if (this.depthOfFieldPostProcess) {
  66416. this.depthOfFieldPostProcess.dispose(camera);
  66417. }
  66418. if (this.motionBlurPostProcess) {
  66419. this.motionBlurPostProcess.dispose(camera);
  66420. }
  66421. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66422. this.blurHPostProcesses[j].dispose(camera);
  66423. }
  66424. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66425. this.blurVPostProcesses[j].dispose(camera);
  66426. }
  66427. }
  66428. this.originalPostProcess = null;
  66429. this.downSampleX4PostProcess = null;
  66430. this.brightPassPostProcess = null;
  66431. this.textureAdderPostProcess = null;
  66432. this.textureAdderFinalPostProcess = null;
  66433. this.volumetricLightPostProcess = null;
  66434. this.volumetricLightSmoothXPostProcess = null;
  66435. this.volumetricLightSmoothYPostProcess = null;
  66436. this.volumetricLightMergePostProces = null;
  66437. this.volumetricLightFinalPostProcess = null;
  66438. this.lensFlarePostProcess = null;
  66439. this.lensFlareComposePostProcess = null;
  66440. this.luminancePostProcess = null;
  66441. this.hdrPostProcess = null;
  66442. this.hdrFinalPostProcess = null;
  66443. this.depthOfFieldPostProcess = null;
  66444. this.motionBlurPostProcess = null;
  66445. this.luminanceDownSamplePostProcesses = [];
  66446. this.blurHPostProcesses = [];
  66447. this.blurVPostProcesses = [];
  66448. };
  66449. // Dispose
  66450. StandardRenderingPipeline.prototype.dispose = function () {
  66451. this._disposePostProcesses();
  66452. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66453. _super.prototype.dispose.call(this);
  66454. };
  66455. // Serialize rendering pipeline
  66456. StandardRenderingPipeline.prototype.serialize = function () {
  66457. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66458. serializationObject.customType = "StandardRenderingPipeline";
  66459. return serializationObject;
  66460. };
  66461. /**
  66462. * Static members
  66463. */
  66464. // Parse serialized pipeline
  66465. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66466. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66467. };
  66468. // Luminance steps
  66469. StandardRenderingPipeline.LuminanceSteps = 6;
  66470. __decorate([
  66471. BABYLON.serialize()
  66472. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66473. __decorate([
  66474. BABYLON.serialize()
  66475. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66476. __decorate([
  66477. BABYLON.serialize()
  66478. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66479. __decorate([
  66480. BABYLON.serialize()
  66481. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66482. __decorate([
  66483. BABYLON.serializeAsTexture("lensTexture")
  66484. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66485. __decorate([
  66486. BABYLON.serialize()
  66487. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66488. __decorate([
  66489. BABYLON.serialize()
  66490. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66491. __decorate([
  66492. BABYLON.serialize()
  66493. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66494. __decorate([
  66495. BABYLON.serialize()
  66496. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66497. __decorate([
  66498. BABYLON.serialize()
  66499. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66500. __decorate([
  66501. BABYLON.serialize()
  66502. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66503. __decorate([
  66504. BABYLON.serializeAsTexture("lensColorTexture")
  66505. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66506. __decorate([
  66507. BABYLON.serialize()
  66508. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66509. __decorate([
  66510. BABYLON.serialize()
  66511. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66512. __decorate([
  66513. BABYLON.serialize()
  66514. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66515. __decorate([
  66516. BABYLON.serialize()
  66517. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66518. __decorate([
  66519. BABYLON.serializeAsTexture("lensStarTexture")
  66520. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66521. __decorate([
  66522. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66523. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66524. __decorate([
  66525. BABYLON.serialize()
  66526. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66527. __decorate([
  66528. BABYLON.serialize()
  66529. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66530. __decorate([
  66531. BABYLON.serialize()
  66532. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66533. __decorate([
  66534. BABYLON.serialize()
  66535. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66536. __decorate([
  66537. BABYLON.serialize()
  66538. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66539. __decorate([
  66540. BABYLON.serialize()
  66541. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66542. __decorate([
  66543. BABYLON.serialize()
  66544. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66545. __decorate([
  66546. BABYLON.serialize()
  66547. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66548. __decorate([
  66549. BABYLON.serialize()
  66550. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66551. __decorate([
  66552. BABYLON.serialize()
  66553. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66554. __decorate([
  66555. BABYLON.serialize()
  66556. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66557. __decorate([
  66558. BABYLON.serialize()
  66559. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66560. return StandardRenderingPipeline;
  66561. }(BABYLON.PostProcessRenderPipeline));
  66562. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66563. })(BABYLON || (BABYLON = {}));
  66564. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66565. var BABYLON;
  66566. (function (BABYLON) {
  66567. var FxaaPostProcess = /** @class */ (function (_super) {
  66568. __extends(FxaaPostProcess, _super);
  66569. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66570. if (camera === void 0) { camera = null; }
  66571. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66572. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66573. _this.onApplyObservable.add(function (effect) {
  66574. var texelSize = _this.texelSize;
  66575. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66576. });
  66577. return _this;
  66578. }
  66579. return FxaaPostProcess;
  66580. }(BABYLON.PostProcess));
  66581. BABYLON.FxaaPostProcess = FxaaPostProcess;
  66582. })(BABYLON || (BABYLON = {}));
  66583. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  66584. var BABYLON;
  66585. (function (BABYLON) {
  66586. /**
  66587. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  66588. */
  66589. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  66590. __extends(CircleOfConfusionPostProcess, _super);
  66591. /**
  66592. * Creates a new instance of @see CircleOfConfusionPostProcess
  66593. * @param name The name of the effect.
  66594. * @param scene The scene the effect belongs to.
  66595. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  66596. * @param options The required width/height ratio to downsize to before computing the render pass.
  66597. * @param camera The camera to apply the render pass to.
  66598. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66599. * @param engine The engine which the post process will be applied. (default: current engine)
  66600. * @param reusable If the post process can be reused on the same frame. (default: false)
  66601. * @param textureType Type of textures used when performing the post process. (default: 0)
  66602. */
  66603. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  66604. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66605. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  66606. /**
  66607. * 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.
  66608. */
  66609. _this.lensSize = 50;
  66610. /**
  66611. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66612. */
  66613. _this.fStop = 1.4;
  66614. /**
  66615. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66616. */
  66617. _this.focusDistance = 2000;
  66618. /**
  66619. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  66620. */
  66621. _this.focalLength = 50;
  66622. _this.onApplyObservable.add(function (effect) {
  66623. effect.setTexture("depthSampler", depthTexture);
  66624. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  66625. var aperture = _this.lensSize / _this.fStop;
  66626. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  66627. effect.setFloat('focusDistance', _this.focusDistance);
  66628. effect.setFloat('cocPrecalculation', cocPrecalculation);
  66629. if (scene.activeCamera) {
  66630. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  66631. }
  66632. });
  66633. return _this;
  66634. }
  66635. return CircleOfConfusionPostProcess;
  66636. }(BABYLON.PostProcess));
  66637. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  66638. })(BABYLON || (BABYLON = {}));
  66639. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  66640. var BABYLON;
  66641. (function (BABYLON) {
  66642. /**
  66643. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  66644. */
  66645. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  66646. __extends(DepthOfFieldMergePostProcess, _super);
  66647. /**
  66648. * Creates a new instance of @see CircleOfConfusionPostProcess
  66649. * @param name The name of the effect.
  66650. * @param original The non-blurred image to be modified
  66651. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  66652. * @param blurSteps Incrimental bluring post processes.
  66653. * @param options The required width/height ratio to downsize to before computing the render pass.
  66654. * @param camera The camera to apply the render pass to.
  66655. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  66656. * @param engine The engine which the post process will be applied. (default: current engine)
  66657. * @param reusable If the post process can be reused on the same frame. (default: false)
  66658. * @param textureType Type of textures used when performing the post process. (default: 0)
  66659. */
  66660. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  66661. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66662. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  66663. _this.onApplyObservable.add(function (effect) {
  66664. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  66665. effect.setTextureFromPostProcess("originalSampler", original);
  66666. blurSteps.forEach(function (step, index) {
  66667. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  66668. });
  66669. });
  66670. return _this;
  66671. }
  66672. return DepthOfFieldMergePostProcess;
  66673. }(BABYLON.PostProcess));
  66674. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  66675. })(BABYLON || (BABYLON = {}));
  66676. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  66677. var BABYLON;
  66678. (function (BABYLON) {
  66679. /**
  66680. * Specifies the level of max blur that should be applied when using the depth of field effect
  66681. */
  66682. var DepthOfFieldEffectBlurLevel;
  66683. (function (DepthOfFieldEffectBlurLevel) {
  66684. /**
  66685. * Subtle blur
  66686. */
  66687. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  66688. /**
  66689. * Medium blur
  66690. */
  66691. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  66692. /**
  66693. * Large blur
  66694. */
  66695. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  66696. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  66697. ;
  66698. /**
  66699. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  66700. */
  66701. var DepthOfFieldEffect = /** @class */ (function (_super) {
  66702. __extends(DepthOfFieldEffect, _super);
  66703. /**
  66704. * Creates a new instance of @see DepthOfFieldEffect
  66705. * @param scene The scene the effect belongs to.
  66706. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  66707. */
  66708. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  66709. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  66710. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  66711. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  66712. // Enable and get current depth map
  66713. var depthMap = scene.enableDepthRenderer().getDepthMap();
  66714. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  66715. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66716. // Capture circle of confusion texture
  66717. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66718. _this._depthOfFieldPass.autoClear = false;
  66719. // 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)
  66720. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  66721. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  66722. _this._depthOfFieldBlurY = [];
  66723. _this._depthOfFieldBlurX = [];
  66724. var blurCount = 1;
  66725. var kernelSize = 15;
  66726. switch (blurLevel) {
  66727. case DepthOfFieldEffectBlurLevel.High: {
  66728. blurCount = 3;
  66729. kernelSize = 51;
  66730. break;
  66731. }
  66732. case DepthOfFieldEffectBlurLevel.Medium: {
  66733. blurCount = 2;
  66734. kernelSize = 31;
  66735. break;
  66736. }
  66737. default: {
  66738. kernelSize = 15;
  66739. blurCount = 1;
  66740. break;
  66741. }
  66742. }
  66743. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  66744. for (var i = 0; i < blurCount; i++) {
  66745. 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);
  66746. blurY.autoClear = false;
  66747. 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);
  66748. blurX.autoClear = false;
  66749. _this._depthOfFieldBlurY.push(blurY);
  66750. _this._depthOfFieldBlurX.push(blurX);
  66751. }
  66752. // Merge blurred images with original image based on circleOfConfusion
  66753. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  66754. _this._depthOfFieldMerge.autoClear = false;
  66755. // Set all post processes on the effect.
  66756. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  66757. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  66758. effects.push(_this._depthOfFieldBlurY[i]);
  66759. effects.push(_this._depthOfFieldBlurX[i]);
  66760. }
  66761. effects.push(_this._depthOfFieldMerge);
  66762. return effects;
  66763. }, true) || this;
  66764. return _this;
  66765. }
  66766. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  66767. get: function () {
  66768. return this._circleOfConfusion.focalLength;
  66769. },
  66770. /**
  66771. * The focal the length of the camera used in the effect
  66772. */
  66773. set: function (value) {
  66774. this._circleOfConfusion.focalLength = value;
  66775. },
  66776. enumerable: true,
  66777. configurable: true
  66778. });
  66779. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  66780. get: function () {
  66781. return this._circleOfConfusion.fStop;
  66782. },
  66783. /**
  66784. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  66785. */
  66786. set: function (value) {
  66787. this._circleOfConfusion.fStop = value;
  66788. },
  66789. enumerable: true,
  66790. configurable: true
  66791. });
  66792. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  66793. get: function () {
  66794. return this._circleOfConfusion.focusDistance;
  66795. },
  66796. /**
  66797. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  66798. */
  66799. set: function (value) {
  66800. this._circleOfConfusion.focusDistance = value;
  66801. },
  66802. enumerable: true,
  66803. configurable: true
  66804. });
  66805. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  66806. get: function () {
  66807. return this._circleOfConfusion.lensSize;
  66808. },
  66809. /**
  66810. * 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.
  66811. */
  66812. set: function (value) {
  66813. this._circleOfConfusion.lensSize = value;
  66814. },
  66815. enumerable: true,
  66816. configurable: true
  66817. });
  66818. /**
  66819. * Disposes each of the internal effects for a given camera.
  66820. * @param camera The camera to dispose the effect on.
  66821. */
  66822. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  66823. this._depthOfFieldPass.dispose(camera);
  66824. this._circleOfConfusion.dispose(camera);
  66825. this._depthOfFieldBlurX.forEach(function (element) {
  66826. element.dispose(camera);
  66827. });
  66828. this._depthOfFieldBlurY.forEach(function (element) {
  66829. element.dispose(camera);
  66830. });
  66831. this._depthOfFieldMerge.dispose(camera);
  66832. };
  66833. return DepthOfFieldEffect;
  66834. }(BABYLON.PostProcessRenderEffect));
  66835. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  66836. })(BABYLON || (BABYLON = {}));
  66837. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  66838. var BABYLON;
  66839. (function (BABYLON) {
  66840. /**
  66841. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  66842. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  66843. */
  66844. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  66845. __extends(DefaultRenderingPipeline, _super);
  66846. /**
  66847. * @constructor
  66848. * @param {string} name - The rendering pipeline name
  66849. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66850. * @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)
  66851. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66852. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  66853. */
  66854. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  66855. if (automaticBuild === void 0) { automaticBuild = true; }
  66856. var _this = _super.call(this, scene.getEngine(), name) || this;
  66857. /**
  66858. * ID of the pass post process used for bloom,
  66859. */
  66860. _this.PassPostProcessId = "PassPostProcessEffect";
  66861. /**
  66862. * ID of the highlight post process used for bloom,
  66863. */
  66864. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  66865. /**
  66866. * ID of the blurX post process used for bloom,
  66867. */
  66868. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  66869. /**
  66870. * ID of the blurY post process used for bloom,
  66871. */
  66872. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  66873. /**
  66874. * ID of the copy back post process used for bloom,
  66875. */
  66876. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  66877. /**
  66878. * ID of the image processing post process;
  66879. */
  66880. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  66881. /**
  66882. * ID of the Fast Approximate Anti-Aliasing post process;
  66883. */
  66884. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  66885. /**
  66886. * ID of the final merge post process;
  66887. */
  66888. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  66889. /**
  66890. * Animations which can be used to tweak settings over a period of time
  66891. */
  66892. _this.animations = [];
  66893. // Values
  66894. _this._bloomEnabled = false;
  66895. _this._depthOfFieldEnabled = false;
  66896. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  66897. _this._fxaaEnabled = false;
  66898. _this._imageProcessingEnabled = true;
  66899. _this._bloomScale = 0.6;
  66900. _this._buildAllowed = true;
  66901. /**
  66902. * Specifies the size of the bloom blur kernel, relative to the final output size
  66903. */
  66904. _this.bloomKernel = 64;
  66905. /**
  66906. * Specifies the weight of the bloom in the final rendering
  66907. */
  66908. _this._bloomWeight = 0.15;
  66909. _this._cameras = cameras || [];
  66910. _this._buildAllowed = automaticBuild;
  66911. // Initialize
  66912. _this._scene = scene;
  66913. var caps = _this._scene.getEngine().getCaps();
  66914. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  66915. // Misc
  66916. if (_this._hdr) {
  66917. if (caps.textureHalfFloatRender) {
  66918. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66919. }
  66920. else if (caps.textureFloatRender) {
  66921. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66922. }
  66923. }
  66924. else {
  66925. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66926. }
  66927. // Attach
  66928. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66929. _this._buildPipeline();
  66930. return _this;
  66931. }
  66932. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  66933. get: function () {
  66934. return this._bloomWeight;
  66935. },
  66936. /**
  66937. * The strength of the bloom.
  66938. */
  66939. set: function (value) {
  66940. if (this._bloomWeight === value) {
  66941. return;
  66942. }
  66943. this._bloomWeight = value;
  66944. if (this._hdr && this.copyBack) {
  66945. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  66946. }
  66947. },
  66948. enumerable: true,
  66949. configurable: true
  66950. });
  66951. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  66952. get: function () {
  66953. return this._bloomScale;
  66954. },
  66955. /**
  66956. * The scale of the bloom, lower value will provide better performance.
  66957. */
  66958. set: function (value) {
  66959. if (this._bloomScale === value) {
  66960. return;
  66961. }
  66962. this._bloomScale = value;
  66963. this._buildPipeline();
  66964. },
  66965. enumerable: true,
  66966. configurable: true
  66967. });
  66968. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  66969. get: function () {
  66970. return this._bloomEnabled;
  66971. },
  66972. /**
  66973. * Enable or disable the bloom from the pipeline
  66974. */
  66975. set: function (enabled) {
  66976. if (this._bloomEnabled === enabled) {
  66977. return;
  66978. }
  66979. this._bloomEnabled = enabled;
  66980. this._buildPipeline();
  66981. },
  66982. enumerable: true,
  66983. configurable: true
  66984. });
  66985. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  66986. /**
  66987. * If the depth of field is enabled.
  66988. */
  66989. get: function () {
  66990. return this._depthOfFieldEnabled;
  66991. },
  66992. set: function (enabled) {
  66993. if (this._depthOfFieldEnabled === enabled) {
  66994. return;
  66995. }
  66996. this._depthOfFieldEnabled = enabled;
  66997. this._buildPipeline();
  66998. },
  66999. enumerable: true,
  67000. configurable: true
  67001. });
  67002. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  67003. /**
  67004. * Blur level of the depth of field effect. (Higher blur will effect performance)
  67005. */
  67006. get: function () {
  67007. return this._depthOfFieldBlurLevel;
  67008. },
  67009. set: function (value) {
  67010. if (this._depthOfFieldBlurLevel === value) {
  67011. return;
  67012. }
  67013. this._depthOfFieldBlurLevel = value;
  67014. this._buildPipeline();
  67015. },
  67016. enumerable: true,
  67017. configurable: true
  67018. });
  67019. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  67020. get: function () {
  67021. return this._fxaaEnabled;
  67022. },
  67023. /**
  67024. * If the anti aliasing is enabled.
  67025. */
  67026. set: function (enabled) {
  67027. if (this._fxaaEnabled === enabled) {
  67028. return;
  67029. }
  67030. this._fxaaEnabled = enabled;
  67031. this._buildPipeline();
  67032. },
  67033. enumerable: true,
  67034. configurable: true
  67035. });
  67036. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  67037. get: function () {
  67038. return this._imageProcessingEnabled;
  67039. },
  67040. /**
  67041. * If image processing is enabled.
  67042. */
  67043. set: function (enabled) {
  67044. if (this._imageProcessingEnabled === enabled) {
  67045. return;
  67046. }
  67047. this._imageProcessingEnabled = enabled;
  67048. this._buildPipeline();
  67049. },
  67050. enumerable: true,
  67051. configurable: true
  67052. });
  67053. /**
  67054. * Force the compilation of the entire pipeline.
  67055. */
  67056. DefaultRenderingPipeline.prototype.prepare = function () {
  67057. var previousState = this._buildAllowed;
  67058. this._buildAllowed = true;
  67059. this._buildPipeline();
  67060. this._buildAllowed = previousState;
  67061. };
  67062. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  67063. var _this = this;
  67064. if (!this._buildAllowed) {
  67065. return;
  67066. }
  67067. var engine = this._scene.getEngine();
  67068. this._disposePostProcesses();
  67069. this._reset();
  67070. if (this.depthOfFieldEnabled) {
  67071. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  67072. this.addEffect(this.depthOfField);
  67073. }
  67074. if (this.bloomEnabled) {
  67075. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67076. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  67077. if (!this._hdr) {
  67078. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67079. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  67080. this.highlights.autoClear = false;
  67081. this.highlights.alwaysForcePOT = true;
  67082. }
  67083. 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);
  67084. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  67085. this.blurX.alwaysForcePOT = true;
  67086. this.blurX.autoClear = false;
  67087. this.blurX.onActivateObservable.add(function () {
  67088. var dw = _this.blurX.width / engine.getRenderWidth(true);
  67089. _this.blurX.kernel = _this.bloomKernel * dw;
  67090. });
  67091. 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);
  67092. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  67093. this.blurY.alwaysForcePOT = true;
  67094. this.blurY.autoClear = false;
  67095. this.blurY.onActivateObservable.add(function () {
  67096. var dh = _this.blurY.height / engine.getRenderHeight(true);
  67097. _this.blurY.kernel = _this.bloomKernel * dh;
  67098. });
  67099. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67100. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  67101. this.copyBack.alwaysForcePOT = true;
  67102. if (this._hdr) {
  67103. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  67104. var w = this.bloomWeight;
  67105. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  67106. }
  67107. else {
  67108. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  67109. }
  67110. this.copyBack.autoClear = false;
  67111. }
  67112. if (this._imageProcessingEnabled) {
  67113. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67114. if (this._hdr) {
  67115. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  67116. }
  67117. else {
  67118. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  67119. }
  67120. }
  67121. if (this.fxaaEnabled) {
  67122. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67123. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  67124. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67125. }
  67126. else if (this._hdr && this.imageProcessing) {
  67127. this.finalMerge = this.imageProcessing;
  67128. }
  67129. else {
  67130. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67131. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  67132. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67133. }
  67134. if (this.bloomEnabled) {
  67135. if (this._hdr) {
  67136. this.copyBack.shareOutputWith(this.blurX);
  67137. if (this.imageProcessing) {
  67138. this.imageProcessing.shareOutputWith(this.pass);
  67139. this.imageProcessing.autoClear = false;
  67140. }
  67141. else if (this.fxaa) {
  67142. this.fxaa.shareOutputWith(this.pass);
  67143. }
  67144. else {
  67145. this.finalMerge.shareOutputWith(this.pass);
  67146. }
  67147. }
  67148. else {
  67149. if (this.fxaa) {
  67150. this.fxaa.shareOutputWith(this.pass);
  67151. }
  67152. else {
  67153. this.finalMerge.shareOutputWith(this.pass);
  67154. }
  67155. }
  67156. }
  67157. if (this._cameras !== null) {
  67158. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67159. }
  67160. };
  67161. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  67162. for (var i = 0; i < this._cameras.length; i++) {
  67163. var camera = this._cameras[i];
  67164. if (this.pass) {
  67165. this.pass.dispose(camera);
  67166. }
  67167. if (this.highlights) {
  67168. this.highlights.dispose(camera);
  67169. }
  67170. if (this.blurX) {
  67171. this.blurX.dispose(camera);
  67172. }
  67173. if (this.blurY) {
  67174. this.blurY.dispose(camera);
  67175. }
  67176. if (this.copyBack) {
  67177. this.copyBack.dispose(camera);
  67178. }
  67179. if (this.imageProcessing) {
  67180. this.imageProcessing.dispose(camera);
  67181. }
  67182. if (this.fxaa) {
  67183. this.fxaa.dispose(camera);
  67184. }
  67185. if (this.finalMerge) {
  67186. this.finalMerge.dispose(camera);
  67187. }
  67188. if (this.depthOfField) {
  67189. this.depthOfField.disposeEffects(camera);
  67190. }
  67191. }
  67192. this.pass = null;
  67193. this.highlights = null;
  67194. this.blurX = null;
  67195. this.blurY = null;
  67196. this.copyBack = null;
  67197. this.imageProcessing = null;
  67198. this.fxaa = null;
  67199. this.finalMerge = null;
  67200. this.depthOfField = null;
  67201. };
  67202. /**
  67203. * Dispose of the pipeline and stop all post processes
  67204. */
  67205. DefaultRenderingPipeline.prototype.dispose = function () {
  67206. this._disposePostProcesses();
  67207. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67208. _super.prototype.dispose.call(this);
  67209. };
  67210. /**
  67211. * Serialize the rendering pipeline (Used when exporting)
  67212. * @returns the serialized object
  67213. */
  67214. DefaultRenderingPipeline.prototype.serialize = function () {
  67215. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67216. serializationObject.customType = "DefaultRenderingPipeline";
  67217. return serializationObject;
  67218. };
  67219. /**
  67220. * Parse the serialized pipeline
  67221. * @param source Source pipeline.
  67222. * @param scene The scene to load the pipeline to.
  67223. * @param rootUrl The URL of the serialized pipeline.
  67224. * @returns An instantiated pipeline from the serialized object.
  67225. */
  67226. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67227. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  67228. };
  67229. __decorate([
  67230. BABYLON.serialize()
  67231. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  67232. __decorate([
  67233. BABYLON.serialize()
  67234. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  67235. __decorate([
  67236. BABYLON.serialize()
  67237. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  67238. __decorate([
  67239. BABYLON.serialize()
  67240. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  67241. __decorate([
  67242. BABYLON.serialize()
  67243. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  67244. __decorate([
  67245. BABYLON.serialize()
  67246. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  67247. __decorate([
  67248. BABYLON.serialize()
  67249. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  67250. __decorate([
  67251. BABYLON.serialize()
  67252. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  67253. __decorate([
  67254. BABYLON.serialize()
  67255. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  67256. __decorate([
  67257. BABYLON.serialize()
  67258. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  67259. return DefaultRenderingPipeline;
  67260. }(BABYLON.PostProcessRenderPipeline));
  67261. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  67262. })(BABYLON || (BABYLON = {}));
  67263. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  67264. var BABYLON;
  67265. (function (BABYLON) {
  67266. /**
  67267. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  67268. */
  67269. var GeometryBufferRenderer = /** @class */ (function () {
  67270. /**
  67271. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  67272. * @param scene The scene the buffer belongs to
  67273. * @param ratio How big is the buffer related to the main canvas.
  67274. */
  67275. function GeometryBufferRenderer(scene, ratio) {
  67276. if (ratio === void 0) { ratio = 1; }
  67277. this._enablePosition = false;
  67278. this._scene = scene;
  67279. this._ratio = ratio;
  67280. // Render target
  67281. this._createRenderTargets();
  67282. }
  67283. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  67284. /**
  67285. * Set the render list (meshes to be rendered) used in the G buffer.
  67286. */
  67287. set: function (meshes) {
  67288. this._multiRenderTarget.renderList = meshes;
  67289. },
  67290. enumerable: true,
  67291. configurable: true
  67292. });
  67293. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  67294. /**
  67295. * Gets wether or not G buffer are supported by the running hardware.
  67296. * This requires draw buffer supports
  67297. */
  67298. get: function () {
  67299. return this._multiRenderTarget.isSupported;
  67300. },
  67301. enumerable: true,
  67302. configurable: true
  67303. });
  67304. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  67305. /**
  67306. * Gets wether or not position are enabled for the G buffer.
  67307. */
  67308. get: function () {
  67309. return this._enablePosition;
  67310. },
  67311. /**
  67312. * Sets wether or not position are enabled for the G buffer.
  67313. */
  67314. set: function (enable) {
  67315. this._enablePosition = enable;
  67316. this.dispose();
  67317. this._createRenderTargets();
  67318. },
  67319. enumerable: true,
  67320. configurable: true
  67321. });
  67322. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67323. /**
  67324. * Gets the scene associated with the buffer.
  67325. */
  67326. get: function () {
  67327. return this._scene;
  67328. },
  67329. enumerable: true,
  67330. configurable: true
  67331. });
  67332. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67333. /**
  67334. * Gets the ratio used by the buffer during its creation.
  67335. * How big is the buffer related to the main canvas.
  67336. */
  67337. get: function () {
  67338. return this._ratio;
  67339. },
  67340. enumerable: true,
  67341. configurable: true
  67342. });
  67343. /**
  67344. * Checks wether everything is ready to render a submesh to the G buffer.
  67345. * @param subMesh the submesh to check readiness for
  67346. * @param useInstances is the mesh drawn using instance or not
  67347. * @returns true if ready otherwise false
  67348. */
  67349. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67350. var material = subMesh.getMaterial();
  67351. if (material && material.disableDepthWrite) {
  67352. return false;
  67353. }
  67354. var defines = [];
  67355. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67356. var mesh = subMesh.getMesh();
  67357. // Alpha test
  67358. if (material && material.needAlphaTesting()) {
  67359. defines.push("#define ALPHATEST");
  67360. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67361. attribs.push(BABYLON.VertexBuffer.UVKind);
  67362. defines.push("#define UV1");
  67363. }
  67364. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67365. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67366. defines.push("#define UV2");
  67367. }
  67368. }
  67369. // Buffers
  67370. if (this._enablePosition) {
  67371. defines.push("#define POSITION");
  67372. }
  67373. // Bones
  67374. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67375. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67376. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67377. if (mesh.numBoneInfluencers > 4) {
  67378. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67379. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67380. }
  67381. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67382. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67383. }
  67384. else {
  67385. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67386. }
  67387. // Instances
  67388. if (useInstances) {
  67389. defines.push("#define INSTANCES");
  67390. attribs.push("world0");
  67391. attribs.push("world1");
  67392. attribs.push("world2");
  67393. attribs.push("world3");
  67394. }
  67395. // Get correct effect
  67396. var join = defines.join("\n");
  67397. if (this._cachedDefines !== join) {
  67398. this._cachedDefines = join;
  67399. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67400. }
  67401. return this._effect.isReady();
  67402. };
  67403. /**
  67404. * Gets the current underlying G Buffer.
  67405. * @returns the buffer
  67406. */
  67407. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67408. return this._multiRenderTarget;
  67409. };
  67410. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67411. /**
  67412. * Gets the number of samples used to render the buffer (anti aliasing).
  67413. */
  67414. get: function () {
  67415. return this._multiRenderTarget.samples;
  67416. },
  67417. /**
  67418. * Sets the number of samples used to render the buffer (anti aliasing).
  67419. */
  67420. set: function (value) {
  67421. this._multiRenderTarget.samples = value;
  67422. },
  67423. enumerable: true,
  67424. configurable: true
  67425. });
  67426. /**
  67427. * Disposes the renderer and frees up associated resources.
  67428. */
  67429. GeometryBufferRenderer.prototype.dispose = function () {
  67430. this.getGBuffer().dispose();
  67431. };
  67432. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67433. var _this = this;
  67434. var engine = this._scene.getEngine();
  67435. var count = this._enablePosition ? 3 : 2;
  67436. 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 });
  67437. if (!this.isSupported) {
  67438. return;
  67439. }
  67440. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67441. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67442. this._multiRenderTarget.refreshRate = 1;
  67443. this._multiRenderTarget.renderParticles = false;
  67444. this._multiRenderTarget.renderList = null;
  67445. // set default depth value to 1.0 (far away)
  67446. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67447. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67448. });
  67449. // Custom render function
  67450. var renderSubMesh = function (subMesh) {
  67451. var mesh = subMesh.getRenderingMesh();
  67452. var scene = _this._scene;
  67453. var engine = scene.getEngine();
  67454. var material = subMesh.getMaterial();
  67455. if (!material) {
  67456. return;
  67457. }
  67458. // Culling
  67459. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67460. // Managing instances
  67461. var batch = mesh._getInstancesRenderList(subMesh._id);
  67462. if (batch.mustReturn) {
  67463. return;
  67464. }
  67465. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67466. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67467. engine.enableEffect(_this._effect);
  67468. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67469. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67470. _this._effect.setMatrix("view", scene.getViewMatrix());
  67471. // Alpha test
  67472. if (material && material.needAlphaTesting()) {
  67473. var alphaTexture = material.getAlphaTestTexture();
  67474. if (alphaTexture) {
  67475. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67476. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67477. }
  67478. }
  67479. // Bones
  67480. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67481. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67482. }
  67483. // Draw
  67484. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67485. }
  67486. };
  67487. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67488. var index;
  67489. if (depthOnlySubMeshes.length) {
  67490. engine.setColorWrite(false);
  67491. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67492. renderSubMesh(depthOnlySubMeshes.data[index]);
  67493. }
  67494. engine.setColorWrite(true);
  67495. }
  67496. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67497. renderSubMesh(opaqueSubMeshes.data[index]);
  67498. }
  67499. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67500. renderSubMesh(alphaTestSubMeshes.data[index]);
  67501. }
  67502. };
  67503. };
  67504. return GeometryBufferRenderer;
  67505. }());
  67506. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67507. })(BABYLON || (BABYLON = {}));
  67508. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67509. var BABYLON;
  67510. (function (BABYLON) {
  67511. var RefractionPostProcess = /** @class */ (function (_super) {
  67512. __extends(RefractionPostProcess, _super);
  67513. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67514. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67515. _this.color = color;
  67516. _this.depth = depth;
  67517. _this.colorLevel = colorLevel;
  67518. _this._ownRefractionTexture = true;
  67519. _this.onActivateObservable.add(function (cam) {
  67520. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67521. });
  67522. _this.onApplyObservable.add(function (effect) {
  67523. effect.setColor3("baseColor", _this.color);
  67524. effect.setFloat("depth", _this.depth);
  67525. effect.setFloat("colorLevel", _this.colorLevel);
  67526. effect.setTexture("refractionSampler", _this._refTexture);
  67527. });
  67528. return _this;
  67529. }
  67530. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  67531. /**
  67532. * Gets or sets the refraction texture
  67533. * Please note that you are responsible for disposing the texture if you set it manually
  67534. */
  67535. get: function () {
  67536. return this._refTexture;
  67537. },
  67538. set: function (value) {
  67539. if (this._refTexture && this._ownRefractionTexture) {
  67540. this._refTexture.dispose();
  67541. }
  67542. this._refTexture = value;
  67543. this._ownRefractionTexture = false;
  67544. },
  67545. enumerable: true,
  67546. configurable: true
  67547. });
  67548. // Methods
  67549. RefractionPostProcess.prototype.dispose = function (camera) {
  67550. if (this._refTexture && this._ownRefractionTexture) {
  67551. this._refTexture.dispose();
  67552. this._refTexture = null;
  67553. }
  67554. _super.prototype.dispose.call(this, camera);
  67555. };
  67556. return RefractionPostProcess;
  67557. }(BABYLON.PostProcess));
  67558. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67559. })(BABYLON || (BABYLON = {}));
  67560. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67561. var BABYLON;
  67562. (function (BABYLON) {
  67563. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67564. __extends(BlackAndWhitePostProcess, _super);
  67565. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67566. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67567. _this.degree = 1;
  67568. _this.onApplyObservable.add(function (effect) {
  67569. effect.setFloat("degree", _this.degree);
  67570. });
  67571. return _this;
  67572. }
  67573. return BlackAndWhitePostProcess;
  67574. }(BABYLON.PostProcess));
  67575. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67576. })(BABYLON || (BABYLON = {}));
  67577. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  67578. var BABYLON;
  67579. (function (BABYLON) {
  67580. var ConvolutionPostProcess = /** @class */ (function (_super) {
  67581. __extends(ConvolutionPostProcess, _super);
  67582. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  67583. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  67584. _this.kernel = kernel;
  67585. _this.onApply = function (effect) {
  67586. effect.setFloat2("screenSize", _this.width, _this.height);
  67587. effect.setArray("kernel", _this.kernel);
  67588. };
  67589. return _this;
  67590. }
  67591. // Statics
  67592. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  67593. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  67594. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  67595. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  67596. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  67597. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  67598. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  67599. return ConvolutionPostProcess;
  67600. }(BABYLON.PostProcess));
  67601. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  67602. })(BABYLON || (BABYLON = {}));
  67603. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  67604. var BABYLON;
  67605. (function (BABYLON) {
  67606. var FilterPostProcess = /** @class */ (function (_super) {
  67607. __extends(FilterPostProcess, _super);
  67608. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  67609. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  67610. _this.kernelMatrix = kernelMatrix;
  67611. _this.onApply = function (effect) {
  67612. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  67613. };
  67614. return _this;
  67615. }
  67616. return FilterPostProcess;
  67617. }(BABYLON.PostProcess));
  67618. BABYLON.FilterPostProcess = FilterPostProcess;
  67619. })(BABYLON || (BABYLON = {}));
  67620. //# sourceMappingURL=babylon.filterPostProcess.js.map
  67621. var BABYLON;
  67622. (function (BABYLON) {
  67623. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  67624. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  67625. __extends(VolumetricLightScatteringPostProcess, _super);
  67626. /**
  67627. * @constructor
  67628. * @param {string} name - The post-process name
  67629. * @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)
  67630. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  67631. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  67632. * @param {number} samples - The post-process quality, default 100
  67633. * @param {number} samplingMode - The post-process filtering mode
  67634. * @param {BABYLON.Engine} engine - The babylon engine
  67635. * @param {boolean} reusable - If the post-process is reusable
  67636. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  67637. */
  67638. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  67639. if (samples === void 0) { samples = 100; }
  67640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67641. 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;
  67642. _this._screenCoordinates = BABYLON.Vector2.Zero();
  67643. /**
  67644. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  67645. * @type {Vector3}
  67646. */
  67647. _this.customMeshPosition = BABYLON.Vector3.Zero();
  67648. /**
  67649. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  67650. * @type {boolean}
  67651. */
  67652. _this.useCustomMeshPosition = false;
  67653. /**
  67654. * If the post-process should inverse the light scattering direction
  67655. * @type {boolean}
  67656. */
  67657. _this.invert = true;
  67658. /**
  67659. * Array containing the excluded meshes not rendered in the internal pass
  67660. */
  67661. _this.excludedMeshes = new Array();
  67662. /**
  67663. * Controls the overall intensity of the post-process
  67664. * @type {number}
  67665. */
  67666. _this.exposure = 0.3;
  67667. /**
  67668. * Dissipates each sample's contribution in range [0, 1]
  67669. * @type {number}
  67670. */
  67671. _this.decay = 0.96815;
  67672. /**
  67673. * Controls the overall intensity of each sample
  67674. * @type {number}
  67675. */
  67676. _this.weight = 0.58767;
  67677. /**
  67678. * Controls the density of each sample
  67679. * @type {number}
  67680. */
  67681. _this.density = 0.926;
  67682. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  67683. engine = scene.getEngine();
  67684. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  67685. // Configure mesh
  67686. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  67687. // Configure
  67688. _this._createPass(scene, ratio.passRatio || ratio);
  67689. _this.onActivate = function (camera) {
  67690. if (!_this.isSupported) {
  67691. _this.dispose(camera);
  67692. }
  67693. _this.onActivate = null;
  67694. };
  67695. _this.onApplyObservable.add(function (effect) {
  67696. _this._updateMeshScreenCoordinates(scene);
  67697. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  67698. effect.setFloat("exposure", _this.exposure);
  67699. effect.setFloat("decay", _this.decay);
  67700. effect.setFloat("weight", _this.weight);
  67701. effect.setFloat("density", _this.density);
  67702. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  67703. });
  67704. return _this;
  67705. }
  67706. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  67707. get: function () {
  67708. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67709. return false;
  67710. },
  67711. set: function (useDiffuseColor) {
  67712. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  67713. },
  67714. enumerable: true,
  67715. configurable: true
  67716. });
  67717. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  67718. return "VolumetricLightScatteringPostProcess";
  67719. };
  67720. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  67721. var mesh = subMesh.getMesh();
  67722. // Render this.mesh as default
  67723. if (mesh === this.mesh && mesh.material) {
  67724. return mesh.material.isReady(mesh);
  67725. }
  67726. var defines = [];
  67727. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67728. var material = subMesh.getMaterial();
  67729. // Alpha test
  67730. if (material) {
  67731. if (material.needAlphaTesting()) {
  67732. defines.push("#define ALPHATEST");
  67733. }
  67734. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67735. attribs.push(BABYLON.VertexBuffer.UVKind);
  67736. defines.push("#define UV1");
  67737. }
  67738. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67739. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67740. defines.push("#define UV2");
  67741. }
  67742. }
  67743. // Bones
  67744. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67745. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67746. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67747. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67748. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  67749. }
  67750. else {
  67751. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67752. }
  67753. // Instances
  67754. if (useInstances) {
  67755. defines.push("#define INSTANCES");
  67756. attribs.push("world0");
  67757. attribs.push("world1");
  67758. attribs.push("world2");
  67759. attribs.push("world3");
  67760. }
  67761. // Get correct effect
  67762. var join = defines.join("\n");
  67763. if (this._cachedDefines !== join) {
  67764. this._cachedDefines = join;
  67765. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  67766. }
  67767. return this._volumetricLightScatteringPass.isReady();
  67768. };
  67769. /**
  67770. * Sets the new light position for light scattering effect
  67771. * @param {BABYLON.Vector3} The new custom light position
  67772. */
  67773. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  67774. this.customMeshPosition = position;
  67775. };
  67776. /**
  67777. * Returns the light position for light scattering effect
  67778. * @return {BABYLON.Vector3} The custom light position
  67779. */
  67780. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  67781. return this.customMeshPosition;
  67782. };
  67783. /**
  67784. * Disposes the internal assets and detaches the post-process from the camera
  67785. */
  67786. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  67787. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  67788. if (rttIndex !== -1) {
  67789. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  67790. }
  67791. this._volumetricLightScatteringRTT.dispose();
  67792. _super.prototype.dispose.call(this, camera);
  67793. };
  67794. /**
  67795. * Returns the render target texture used by the post-process
  67796. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  67797. */
  67798. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  67799. return this._volumetricLightScatteringRTT;
  67800. };
  67801. // Private methods
  67802. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  67803. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  67804. return true;
  67805. }
  67806. return false;
  67807. };
  67808. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  67809. var _this = this;
  67810. var engine = scene.getEngine();
  67811. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67812. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67813. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67814. this._volumetricLightScatteringRTT.renderList = null;
  67815. this._volumetricLightScatteringRTT.renderParticles = false;
  67816. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  67817. var camera = this.getCamera();
  67818. if (camera) {
  67819. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67820. }
  67821. else {
  67822. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  67823. }
  67824. // Custom render function for submeshes
  67825. var renderSubMesh = function (subMesh) {
  67826. var mesh = subMesh.getRenderingMesh();
  67827. if (_this._meshExcluded(mesh)) {
  67828. return;
  67829. }
  67830. var material = subMesh.getMaterial();
  67831. if (!material) {
  67832. return;
  67833. }
  67834. var scene = mesh.getScene();
  67835. var engine = scene.getEngine();
  67836. // Culling
  67837. engine.setState(material.backFaceCulling);
  67838. // Managing instances
  67839. var batch = mesh._getInstancesRenderList(subMesh._id);
  67840. if (batch.mustReturn) {
  67841. return;
  67842. }
  67843. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67844. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  67845. var effect = _this._volumetricLightScatteringPass;
  67846. if (mesh === _this.mesh) {
  67847. if (subMesh.effect) {
  67848. effect = subMesh.effect;
  67849. }
  67850. else {
  67851. effect = material.getEffect();
  67852. }
  67853. }
  67854. engine.enableEffect(effect);
  67855. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  67856. if (mesh === _this.mesh) {
  67857. material.bind(mesh.getWorldMatrix(), mesh);
  67858. }
  67859. else {
  67860. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  67861. // Alpha test
  67862. if (material && material.needAlphaTesting()) {
  67863. var alphaTexture = material.getAlphaTestTexture();
  67864. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  67865. if (alphaTexture) {
  67866. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67867. }
  67868. }
  67869. // Bones
  67870. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67871. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67872. }
  67873. }
  67874. // Draw
  67875. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  67876. }
  67877. };
  67878. // Render target texture callbacks
  67879. var savedSceneClearColor;
  67880. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  67881. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  67882. savedSceneClearColor = scene.clearColor;
  67883. scene.clearColor = sceneClearColor;
  67884. });
  67885. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  67886. scene.clearColor = savedSceneClearColor;
  67887. });
  67888. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67889. var engine = scene.getEngine();
  67890. var index;
  67891. if (depthOnlySubMeshes.length) {
  67892. engine.setColorWrite(false);
  67893. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67894. renderSubMesh(depthOnlySubMeshes.data[index]);
  67895. }
  67896. engine.setColorWrite(true);
  67897. }
  67898. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67899. renderSubMesh(opaqueSubMeshes.data[index]);
  67900. }
  67901. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67902. renderSubMesh(alphaTestSubMeshes.data[index]);
  67903. }
  67904. if (transparentSubMeshes.length) {
  67905. // Sort sub meshes
  67906. for (index = 0; index < transparentSubMeshes.length; index++) {
  67907. var submesh = transparentSubMeshes.data[index];
  67908. var boundingInfo = submesh.getBoundingInfo();
  67909. if (boundingInfo && scene.activeCamera) {
  67910. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  67911. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  67912. }
  67913. }
  67914. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  67915. sortedArray.sort(function (a, b) {
  67916. // Alpha index first
  67917. if (a._alphaIndex > b._alphaIndex) {
  67918. return 1;
  67919. }
  67920. if (a._alphaIndex < b._alphaIndex) {
  67921. return -1;
  67922. }
  67923. // Then distance to camera
  67924. if (a._distanceToCamera < b._distanceToCamera) {
  67925. return 1;
  67926. }
  67927. if (a._distanceToCamera > b._distanceToCamera) {
  67928. return -1;
  67929. }
  67930. return 0;
  67931. });
  67932. // Render sub meshes
  67933. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  67934. for (index = 0; index < sortedArray.length; index++) {
  67935. renderSubMesh(sortedArray[index]);
  67936. }
  67937. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67938. }
  67939. };
  67940. };
  67941. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  67942. var transform = scene.getTransformMatrix();
  67943. var meshPosition;
  67944. if (this.useCustomMeshPosition) {
  67945. meshPosition = this.customMeshPosition;
  67946. }
  67947. else if (this.attachedNode) {
  67948. meshPosition = this.attachedNode.position;
  67949. }
  67950. else {
  67951. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  67952. }
  67953. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  67954. this._screenCoordinates.x = pos.x / this._viewPort.width;
  67955. this._screenCoordinates.y = pos.y / this._viewPort.height;
  67956. if (this.invert)
  67957. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  67958. };
  67959. // Static methods
  67960. /**
  67961. * Creates a default mesh for the Volumeric Light Scattering post-process
  67962. * @param {string} The mesh name
  67963. * @param {BABYLON.Scene} The scene where to create the mesh
  67964. * @return {BABYLON.Mesh} the default mesh
  67965. */
  67966. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  67967. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  67968. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  67969. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  67970. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  67971. mesh.material = material;
  67972. return mesh;
  67973. };
  67974. __decorate([
  67975. BABYLON.serializeAsVector3()
  67976. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  67977. __decorate([
  67978. BABYLON.serialize()
  67979. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  67980. __decorate([
  67981. BABYLON.serialize()
  67982. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  67983. __decorate([
  67984. BABYLON.serializeAsMeshReference()
  67985. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  67986. __decorate([
  67987. BABYLON.serialize()
  67988. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  67989. __decorate([
  67990. BABYLON.serialize()
  67991. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  67992. __decorate([
  67993. BABYLON.serialize()
  67994. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  67995. __decorate([
  67996. BABYLON.serialize()
  67997. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  67998. __decorate([
  67999. BABYLON.serialize()
  68000. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  68001. return VolumetricLightScatteringPostProcess;
  68002. }(BABYLON.PostProcess));
  68003. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  68004. })(BABYLON || (BABYLON = {}));
  68005. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  68006. //
  68007. // This post-process allows the modification of rendered colors by using
  68008. // a 'look-up table' (LUT). This effect is also called Color Grading.
  68009. //
  68010. // The object needs to be provided an url to a texture containing the color
  68011. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  68012. // Use an image editing software to tweak the LUT to match your needs.
  68013. //
  68014. // For an example of a color LUT, see here:
  68015. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  68016. // For explanations on color grading, see here:
  68017. // http://udn.epicgames.com/Three/ColorGrading.html
  68018. //
  68019. var BABYLON;
  68020. (function (BABYLON) {
  68021. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  68022. __extends(ColorCorrectionPostProcess, _super);
  68023. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  68024. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  68025. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68026. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  68027. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68028. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68029. _this.onApply = function (effect) {
  68030. effect.setTexture("colorTable", _this._colorTableTexture);
  68031. };
  68032. return _this;
  68033. }
  68034. return ColorCorrectionPostProcess;
  68035. }(BABYLON.PostProcess));
  68036. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  68037. })(BABYLON || (BABYLON = {}));
  68038. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  68039. var BABYLON;
  68040. (function (BABYLON) {
  68041. var TonemappingOperator;
  68042. (function (TonemappingOperator) {
  68043. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  68044. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  68045. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  68046. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  68047. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  68048. ;
  68049. var TonemapPostProcess = /** @class */ (function (_super) {
  68050. __extends(TonemapPostProcess, _super);
  68051. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  68052. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68053. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68054. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  68055. _this._operator = _operator;
  68056. _this.exposureAdjustment = exposureAdjustment;
  68057. var defines = "#define ";
  68058. if (_this._operator === TonemappingOperator.Hable)
  68059. defines += "HABLE_TONEMAPPING";
  68060. else if (_this._operator === TonemappingOperator.Reinhard)
  68061. defines += "REINHARD_TONEMAPPING";
  68062. else if (_this._operator === TonemappingOperator.HejiDawson)
  68063. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  68064. else if (_this._operator === TonemappingOperator.Photographic)
  68065. defines += "PHOTOGRAPHIC_TONEMAPPING";
  68066. //sadly a second call to create the effect.
  68067. _this.updateEffect(defines);
  68068. _this.onApply = function (effect) {
  68069. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  68070. };
  68071. return _this;
  68072. }
  68073. return TonemapPostProcess;
  68074. }(BABYLON.PostProcess));
  68075. BABYLON.TonemapPostProcess = TonemapPostProcess;
  68076. })(BABYLON || (BABYLON = {}));
  68077. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  68078. var BABYLON;
  68079. (function (BABYLON) {
  68080. var DisplayPassPostProcess = /** @class */ (function (_super) {
  68081. __extends(DisplayPassPostProcess, _super);
  68082. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  68083. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  68084. }
  68085. return DisplayPassPostProcess;
  68086. }(BABYLON.PostProcess));
  68087. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  68088. })(BABYLON || (BABYLON = {}));
  68089. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  68090. var BABYLON;
  68091. (function (BABYLON) {
  68092. var HighlightsPostProcess = /** @class */ (function (_super) {
  68093. __extends(HighlightsPostProcess, _super);
  68094. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68095. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68096. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68097. }
  68098. return HighlightsPostProcess;
  68099. }(BABYLON.PostProcess));
  68100. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  68101. })(BABYLON || (BABYLON = {}));
  68102. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  68103. var BABYLON;
  68104. (function (BABYLON) {
  68105. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  68106. __extends(ImageProcessingPostProcess, _super);
  68107. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  68108. if (camera === void 0) { camera = null; }
  68109. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68110. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  68111. _this._fromLinearSpace = true;
  68112. /**
  68113. * Defines cache preventing GC.
  68114. */
  68115. _this._defines = {
  68116. IMAGEPROCESSING: false,
  68117. VIGNETTE: false,
  68118. VIGNETTEBLENDMODEMULTIPLY: false,
  68119. VIGNETTEBLENDMODEOPAQUE: false,
  68120. TONEMAPPING: false,
  68121. CONTRAST: false,
  68122. COLORCURVES: false,
  68123. COLORGRADING: false,
  68124. COLORGRADING3D: false,
  68125. FROMLINEARSPACE: false,
  68126. SAMPLER3DGREENDEPTH: false,
  68127. SAMPLER3DBGRMAP: false,
  68128. IMAGEPROCESSINGPOSTPROCESS: false,
  68129. EXPOSURE: false,
  68130. };
  68131. // Setup the configuration as forced by the constructor. This would then not force the
  68132. // scene materials output in linear space and let untouched the default forward pass.
  68133. if (imageProcessingConfiguration) {
  68134. imageProcessingConfiguration.applyByPostProcess = true;
  68135. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  68136. // This will cause the shader to be compiled
  68137. _this.fromLinearSpace = false;
  68138. }
  68139. else {
  68140. _this._attachImageProcessingConfiguration(null, true);
  68141. _this.imageProcessingConfiguration.applyByPostProcess = true;
  68142. }
  68143. _this.onApply = function (effect) {
  68144. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  68145. };
  68146. return _this;
  68147. }
  68148. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  68149. /**
  68150. * Gets the image processing configuration used either in this material.
  68151. */
  68152. get: function () {
  68153. return this._imageProcessingConfiguration;
  68154. },
  68155. /**
  68156. * Sets the Default image processing configuration used either in the this material.
  68157. *
  68158. * If sets to null, the scene one is in use.
  68159. */
  68160. set: function (value) {
  68161. this._attachImageProcessingConfiguration(value);
  68162. },
  68163. enumerable: true,
  68164. configurable: true
  68165. });
  68166. /**
  68167. * Attaches a new image processing configuration to the PBR Material.
  68168. * @param configuration
  68169. */
  68170. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  68171. var _this = this;
  68172. if (doNotBuild === void 0) { doNotBuild = false; }
  68173. if (configuration === this._imageProcessingConfiguration) {
  68174. return;
  68175. }
  68176. // Detaches observer.
  68177. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68178. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68179. }
  68180. // Pick the scene configuration if needed.
  68181. if (!configuration) {
  68182. var scene = null;
  68183. var engine = this.getEngine();
  68184. var camera = this.getCamera();
  68185. if (camera) {
  68186. scene = camera.getScene();
  68187. }
  68188. else if (engine && engine.scenes) {
  68189. var scenes = engine.scenes;
  68190. scene = scenes[scenes.length - 1];
  68191. }
  68192. else {
  68193. scene = BABYLON.Engine.LastCreatedScene;
  68194. }
  68195. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  68196. }
  68197. else {
  68198. this._imageProcessingConfiguration = configuration;
  68199. }
  68200. // Attaches observer.
  68201. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  68202. _this._updateParameters();
  68203. });
  68204. // Ensure the effect will be rebuilt.
  68205. if (!doNotBuild) {
  68206. this._updateParameters();
  68207. }
  68208. };
  68209. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  68210. /**
  68211. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68212. */
  68213. get: function () {
  68214. return this.imageProcessingConfiguration.colorCurves;
  68215. },
  68216. /**
  68217. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68218. */
  68219. set: function (value) {
  68220. this.imageProcessingConfiguration.colorCurves = value;
  68221. },
  68222. enumerable: true,
  68223. configurable: true
  68224. });
  68225. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  68226. /**
  68227. * Gets wether the color curves effect is enabled.
  68228. */
  68229. get: function () {
  68230. return this.imageProcessingConfiguration.colorCurvesEnabled;
  68231. },
  68232. /**
  68233. * Sets wether the color curves effect is enabled.
  68234. */
  68235. set: function (value) {
  68236. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  68237. },
  68238. enumerable: true,
  68239. configurable: true
  68240. });
  68241. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  68242. /**
  68243. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68244. */
  68245. get: function () {
  68246. return this.imageProcessingConfiguration.colorGradingTexture;
  68247. },
  68248. /**
  68249. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68250. */
  68251. set: function (value) {
  68252. this.imageProcessingConfiguration.colorGradingTexture = value;
  68253. },
  68254. enumerable: true,
  68255. configurable: true
  68256. });
  68257. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  68258. /**
  68259. * Gets wether the color grading effect is enabled.
  68260. */
  68261. get: function () {
  68262. return this.imageProcessingConfiguration.colorGradingEnabled;
  68263. },
  68264. /**
  68265. * Gets wether the color grading effect is enabled.
  68266. */
  68267. set: function (value) {
  68268. this.imageProcessingConfiguration.colorGradingEnabled = value;
  68269. },
  68270. enumerable: true,
  68271. configurable: true
  68272. });
  68273. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  68274. /**
  68275. * Gets exposure used in the effect.
  68276. */
  68277. get: function () {
  68278. return this.imageProcessingConfiguration.exposure;
  68279. },
  68280. /**
  68281. * Sets exposure used in the effect.
  68282. */
  68283. set: function (value) {
  68284. this.imageProcessingConfiguration.exposure = value;
  68285. },
  68286. enumerable: true,
  68287. configurable: true
  68288. });
  68289. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  68290. /**
  68291. * Gets wether tonemapping is enabled or not.
  68292. */
  68293. get: function () {
  68294. return this._imageProcessingConfiguration.toneMappingEnabled;
  68295. },
  68296. /**
  68297. * Sets wether tonemapping is enabled or not
  68298. */
  68299. set: function (value) {
  68300. this._imageProcessingConfiguration.toneMappingEnabled = value;
  68301. },
  68302. enumerable: true,
  68303. configurable: true
  68304. });
  68305. ;
  68306. ;
  68307. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  68308. /**
  68309. * Gets contrast used in the effect.
  68310. */
  68311. get: function () {
  68312. return this.imageProcessingConfiguration.contrast;
  68313. },
  68314. /**
  68315. * Sets contrast used in the effect.
  68316. */
  68317. set: function (value) {
  68318. this.imageProcessingConfiguration.contrast = value;
  68319. },
  68320. enumerable: true,
  68321. configurable: true
  68322. });
  68323. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  68324. /**
  68325. * Gets Vignette stretch size.
  68326. */
  68327. get: function () {
  68328. return this.imageProcessingConfiguration.vignetteStretch;
  68329. },
  68330. /**
  68331. * Sets Vignette stretch size.
  68332. */
  68333. set: function (value) {
  68334. this.imageProcessingConfiguration.vignetteStretch = value;
  68335. },
  68336. enumerable: true,
  68337. configurable: true
  68338. });
  68339. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  68340. /**
  68341. * Gets Vignette centre X Offset.
  68342. */
  68343. get: function () {
  68344. return this.imageProcessingConfiguration.vignetteCentreX;
  68345. },
  68346. /**
  68347. * Sets Vignette centre X Offset.
  68348. */
  68349. set: function (value) {
  68350. this.imageProcessingConfiguration.vignetteCentreX = value;
  68351. },
  68352. enumerable: true,
  68353. configurable: true
  68354. });
  68355. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68356. /**
  68357. * Gets Vignette centre Y Offset.
  68358. */
  68359. get: function () {
  68360. return this.imageProcessingConfiguration.vignetteCentreY;
  68361. },
  68362. /**
  68363. * Sets Vignette centre Y Offset.
  68364. */
  68365. set: function (value) {
  68366. this.imageProcessingConfiguration.vignetteCentreY = value;
  68367. },
  68368. enumerable: true,
  68369. configurable: true
  68370. });
  68371. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68372. /**
  68373. * Gets Vignette weight or intensity of the vignette effect.
  68374. */
  68375. get: function () {
  68376. return this.imageProcessingConfiguration.vignetteWeight;
  68377. },
  68378. /**
  68379. * Sets Vignette weight or intensity of the vignette effect.
  68380. */
  68381. set: function (value) {
  68382. this.imageProcessingConfiguration.vignetteWeight = value;
  68383. },
  68384. enumerable: true,
  68385. configurable: true
  68386. });
  68387. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68388. /**
  68389. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68390. * if vignetteEnabled is set to true.
  68391. */
  68392. get: function () {
  68393. return this.imageProcessingConfiguration.vignetteColor;
  68394. },
  68395. /**
  68396. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68397. * if vignetteEnabled is set to true.
  68398. */
  68399. set: function (value) {
  68400. this.imageProcessingConfiguration.vignetteColor = value;
  68401. },
  68402. enumerable: true,
  68403. configurable: true
  68404. });
  68405. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68406. /**
  68407. * Gets Camera field of view used by the Vignette effect.
  68408. */
  68409. get: function () {
  68410. return this.imageProcessingConfiguration.vignetteCameraFov;
  68411. },
  68412. /**
  68413. * Sets Camera field of view used by the Vignette effect.
  68414. */
  68415. set: function (value) {
  68416. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68417. },
  68418. enumerable: true,
  68419. configurable: true
  68420. });
  68421. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68422. /**
  68423. * Gets the vignette blend mode allowing different kind of effect.
  68424. */
  68425. get: function () {
  68426. return this.imageProcessingConfiguration.vignetteBlendMode;
  68427. },
  68428. /**
  68429. * Sets the vignette blend mode allowing different kind of effect.
  68430. */
  68431. set: function (value) {
  68432. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68433. },
  68434. enumerable: true,
  68435. configurable: true
  68436. });
  68437. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68438. /**
  68439. * Gets wether the vignette effect is enabled.
  68440. */
  68441. get: function () {
  68442. return this.imageProcessingConfiguration.vignetteEnabled;
  68443. },
  68444. /**
  68445. * Sets wether the vignette effect is enabled.
  68446. */
  68447. set: function (value) {
  68448. this.imageProcessingConfiguration.vignetteEnabled = value;
  68449. },
  68450. enumerable: true,
  68451. configurable: true
  68452. });
  68453. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68454. /**
  68455. * Gets wether the input of the processing is in Gamma or Linear Space.
  68456. */
  68457. get: function () {
  68458. return this._fromLinearSpace;
  68459. },
  68460. /**
  68461. * Sets wether the input of the processing is in Gamma or Linear Space.
  68462. */
  68463. set: function (value) {
  68464. if (this._fromLinearSpace === value) {
  68465. return;
  68466. }
  68467. this._fromLinearSpace = value;
  68468. this._updateParameters();
  68469. },
  68470. enumerable: true,
  68471. configurable: true
  68472. });
  68473. ImageProcessingPostProcess.prototype.getClassName = function () {
  68474. return "ImageProcessingPostProcess";
  68475. };
  68476. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68477. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68478. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68479. var defines = "";
  68480. for (var define in this._defines) {
  68481. if (this._defines[define]) {
  68482. defines += "#define " + define + ";\r\n";
  68483. }
  68484. }
  68485. var samplers = ["textureSampler"];
  68486. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68487. var uniforms = ["scale"];
  68488. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68489. this.updateEffect(defines, uniforms, samplers);
  68490. };
  68491. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68492. _super.prototype.dispose.call(this, camera);
  68493. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68494. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68495. }
  68496. this.imageProcessingConfiguration.applyByPostProcess = false;
  68497. };
  68498. __decorate([
  68499. BABYLON.serialize()
  68500. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68501. return ImageProcessingPostProcess;
  68502. }(BABYLON.PostProcess));
  68503. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68504. })(BABYLON || (BABYLON = {}));
  68505. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68506. var BABYLON;
  68507. (function (BABYLON) {
  68508. /**
  68509. * The Blur Post Process which blurs an image based on a kernel and direction.
  68510. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68511. */
  68512. var BlurPostProcess = /** @class */ (function (_super) {
  68513. __extends(BlurPostProcess, _super);
  68514. /**
  68515. * Creates a new instance of @see BlurPostProcess
  68516. * @param name The name of the effect.
  68517. * @param direction The direction in which to blur the image.
  68518. * @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.
  68519. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68520. * @param camera The camera to apply the render pass to.
  68521. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68522. * @param engine The engine which the post process will be applied. (default: current engine)
  68523. * @param reusable If the post process can be reused on the same frame. (default: false)
  68524. * @param textureType Type of textures used when performing the post process. (default: 0)
  68525. */
  68526. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68527. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68528. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68529. if (defines === void 0) { defines = ""; }
  68530. 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;
  68531. _this.direction = direction;
  68532. _this._packedFloat = false;
  68533. _this._staticDefines = "";
  68534. _this._staticDefines = defines;
  68535. _this.onApplyObservable.add(function (effect) {
  68536. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68537. });
  68538. _this.kernel = kernel;
  68539. return _this;
  68540. }
  68541. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68542. /**
  68543. * Gets the length in pixels of the blur sample region
  68544. */
  68545. get: function () {
  68546. return this._idealKernel;
  68547. },
  68548. /**
  68549. * Sets the length in pixels of the blur sample region
  68550. */
  68551. set: function (v) {
  68552. if (this._idealKernel === v) {
  68553. return;
  68554. }
  68555. v = Math.max(v, 1);
  68556. this._idealKernel = v;
  68557. this._kernel = this._nearestBestKernel(v);
  68558. this._updateParameters();
  68559. },
  68560. enumerable: true,
  68561. configurable: true
  68562. });
  68563. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68564. /**
  68565. * Gets wether or not the blur is unpacking/repacking floats
  68566. */
  68567. get: function () {
  68568. return this._packedFloat;
  68569. },
  68570. /**
  68571. * Sets wether or not the blur needs to unpack/repack floats
  68572. */
  68573. set: function (v) {
  68574. if (this._packedFloat === v) {
  68575. return;
  68576. }
  68577. this._packedFloat = v;
  68578. this._updateParameters();
  68579. },
  68580. enumerable: true,
  68581. configurable: true
  68582. });
  68583. BlurPostProcess.prototype._updateParameters = function () {
  68584. // Generate sampling offsets and weights
  68585. var N = this._kernel;
  68586. var centerIndex = (N - 1) / 2;
  68587. // Generate Gaussian sampling weights over kernel
  68588. var offsets = [];
  68589. var weights = [];
  68590. var totalWeight = 0;
  68591. for (var i = 0; i < N; i++) {
  68592. var u = i / (N - 1);
  68593. var w = this._gaussianWeight(u * 2.0 - 1);
  68594. offsets[i] = (i - centerIndex);
  68595. weights[i] = w;
  68596. totalWeight += w;
  68597. }
  68598. // Normalize weights
  68599. for (var i = 0; i < weights.length; i++) {
  68600. weights[i] /= totalWeight;
  68601. }
  68602. // Optimize: combine samples to take advantage of hardware linear sampling
  68603. // Walk from left to center, combining pairs (symmetrically)
  68604. var linearSamplingWeights = [];
  68605. var linearSamplingOffsets = [];
  68606. var linearSamplingMap = [];
  68607. for (var i = 0; i <= centerIndex; i += 2) {
  68608. var j = Math.min(i + 1, Math.floor(centerIndex));
  68609. var singleCenterSample = i === j;
  68610. if (singleCenterSample) {
  68611. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68612. }
  68613. else {
  68614. var sharedCell = j === centerIndex;
  68615. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  68616. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  68617. if (offsetLinear === 0) {
  68618. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  68619. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  68620. }
  68621. else {
  68622. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  68623. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  68624. }
  68625. }
  68626. }
  68627. for (var i = 0; i < linearSamplingMap.length; i++) {
  68628. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  68629. linearSamplingWeights[i] = linearSamplingMap[i].w;
  68630. }
  68631. // Replace with optimized
  68632. offsets = linearSamplingOffsets;
  68633. weights = linearSamplingWeights;
  68634. // Generate shaders
  68635. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  68636. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  68637. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  68638. var defines = "";
  68639. defines += this._staticDefines;
  68640. for (var i = 0; i < varyingCount; i++) {
  68641. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  68642. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  68643. }
  68644. var depCount = 0;
  68645. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  68646. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  68647. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  68648. depCount++;
  68649. }
  68650. if (this.packedFloat) {
  68651. defines += "#define PACKEDFLOAT 1";
  68652. }
  68653. this.updateEffect(defines, null, null, {
  68654. varyingCount: varyingCount,
  68655. depCount: depCount
  68656. });
  68657. };
  68658. /**
  68659. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  68660. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  68661. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  68662. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  68663. * The gaps between physical kernels are compensated for in the weighting of the samples
  68664. * @param idealKernel Ideal blur kernel.
  68665. * @return Nearest best kernel.
  68666. */
  68667. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  68668. var v = Math.round(idealKernel);
  68669. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  68670. var k = _a[_i];
  68671. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  68672. return Math.max(k, 3);
  68673. }
  68674. }
  68675. return Math.max(v, 3);
  68676. };
  68677. /**
  68678. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  68679. * @param x The point on the Gaussian distribution to sample.
  68680. * @return the value of the Gaussian function at x.
  68681. */
  68682. BlurPostProcess.prototype._gaussianWeight = function (x) {
  68683. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  68684. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  68685. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  68686. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  68687. // truncated at around 1.3% of peak strength.
  68688. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  68689. var sigma = (1 / 3);
  68690. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  68691. var exponent = -((x * x) / (2.0 * sigma * sigma));
  68692. var weight = (1.0 / denominator) * Math.exp(exponent);
  68693. return weight;
  68694. };
  68695. /**
  68696. * Generates a string that can be used as a floating point number in GLSL.
  68697. * @param x Value to print.
  68698. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  68699. * @return GLSL float string.
  68700. */
  68701. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  68702. if (decimalFigures === void 0) { decimalFigures = 8; }
  68703. return x.toFixed(decimalFigures).replace(/0+$/, '');
  68704. };
  68705. return BlurPostProcess;
  68706. }(BABYLON.PostProcess));
  68707. BABYLON.BlurPostProcess = BlurPostProcess;
  68708. })(BABYLON || (BABYLON = {}));
  68709. //# sourceMappingURL=babylon.blurPostProcess.js.map
  68710. var BABYLON;
  68711. (function (BABYLON) {
  68712. var Bone = /** @class */ (function (_super) {
  68713. __extends(Bone, _super);
  68714. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  68715. if (parentBone === void 0) { parentBone = null; }
  68716. if (localMatrix === void 0) { localMatrix = null; }
  68717. if (restPose === void 0) { restPose = null; }
  68718. if (baseMatrix === void 0) { baseMatrix = null; }
  68719. if (index === void 0) { index = null; }
  68720. var _this = _super.call(this, name, skeleton.getScene()) || this;
  68721. _this.name = name;
  68722. _this.children = new Array();
  68723. _this.animations = new Array();
  68724. // Set this value to map this bone to a different index in the transform matrices.
  68725. // Set this value to -1 to exclude the bone from the transform matrices.
  68726. _this._index = null;
  68727. _this._worldTransform = new BABYLON.Matrix();
  68728. _this._absoluteTransform = new BABYLON.Matrix();
  68729. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  68730. _this._scaleMatrix = BABYLON.Matrix.Identity();
  68731. _this._scaleVector = BABYLON.Vector3.One();
  68732. _this._negateScaleChildren = BABYLON.Vector3.One();
  68733. _this._scalingDeterminant = 1;
  68734. _this._skeleton = skeleton;
  68735. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  68736. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  68737. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  68738. _this._index = index;
  68739. skeleton.bones.push(_this);
  68740. _this.setParent(parentBone, false);
  68741. _this._updateDifferenceMatrix();
  68742. return _this;
  68743. }
  68744. Object.defineProperty(Bone.prototype, "_matrix", {
  68745. get: function () {
  68746. return this._localMatrix;
  68747. },
  68748. set: function (val) {
  68749. if (this._localMatrix) {
  68750. this._localMatrix.copyFrom(val);
  68751. }
  68752. else {
  68753. this._localMatrix = val;
  68754. }
  68755. },
  68756. enumerable: true,
  68757. configurable: true
  68758. });
  68759. // Members
  68760. Bone.prototype.getSkeleton = function () {
  68761. return this._skeleton;
  68762. };
  68763. Bone.prototype.getParent = function () {
  68764. return this._parent;
  68765. };
  68766. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  68767. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68768. if (this._parent === parent) {
  68769. return;
  68770. }
  68771. if (this._parent) {
  68772. var index = this._parent.children.indexOf(this);
  68773. if (index !== -1) {
  68774. this._parent.children.splice(index, 1);
  68775. }
  68776. }
  68777. this._parent = parent;
  68778. if (this._parent) {
  68779. this._parent.children.push(this);
  68780. }
  68781. if (updateDifferenceMatrix) {
  68782. this._updateDifferenceMatrix();
  68783. }
  68784. };
  68785. Bone.prototype.getLocalMatrix = function () {
  68786. return this._localMatrix;
  68787. };
  68788. Bone.prototype.getBaseMatrix = function () {
  68789. return this._baseMatrix;
  68790. };
  68791. Bone.prototype.getRestPose = function () {
  68792. return this._restPose;
  68793. };
  68794. Bone.prototype.returnToRest = function () {
  68795. this.updateMatrix(this._restPose.clone());
  68796. };
  68797. Bone.prototype.getWorldMatrix = function () {
  68798. return this._worldTransform;
  68799. };
  68800. Bone.prototype.getInvertedAbsoluteTransform = function () {
  68801. return this._invertedAbsoluteTransform;
  68802. };
  68803. Bone.prototype.getAbsoluteTransform = function () {
  68804. return this._absoluteTransform;
  68805. };
  68806. Object.defineProperty(Bone.prototype, "position", {
  68807. // Properties (matches AbstractMesh properties)
  68808. get: function () {
  68809. return this.getPosition();
  68810. },
  68811. set: function (newPosition) {
  68812. this.setPosition(newPosition);
  68813. },
  68814. enumerable: true,
  68815. configurable: true
  68816. });
  68817. Object.defineProperty(Bone.prototype, "rotation", {
  68818. get: function () {
  68819. return this.getRotation();
  68820. },
  68821. set: function (newRotation) {
  68822. this.setRotation(newRotation);
  68823. },
  68824. enumerable: true,
  68825. configurable: true
  68826. });
  68827. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  68828. get: function () {
  68829. return this.getRotationQuaternion();
  68830. },
  68831. set: function (newRotation) {
  68832. this.setRotationQuaternion(newRotation);
  68833. },
  68834. enumerable: true,
  68835. configurable: true
  68836. });
  68837. Object.defineProperty(Bone.prototype, "scaling", {
  68838. get: function () {
  68839. return this.getScale();
  68840. },
  68841. set: function (newScaling) {
  68842. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  68843. },
  68844. enumerable: true,
  68845. configurable: true
  68846. });
  68847. // Methods
  68848. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  68849. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  68850. this._baseMatrix = matrix.clone();
  68851. this._localMatrix = matrix.clone();
  68852. this._skeleton._markAsDirty();
  68853. if (updateDifferenceMatrix) {
  68854. this._updateDifferenceMatrix();
  68855. }
  68856. };
  68857. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  68858. if (!rootMatrix) {
  68859. rootMatrix = this._baseMatrix;
  68860. }
  68861. if (this._parent) {
  68862. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  68863. }
  68864. else {
  68865. this._absoluteTransform.copyFrom(rootMatrix);
  68866. }
  68867. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  68868. for (var index = 0; index < this.children.length; index++) {
  68869. this.children[index]._updateDifferenceMatrix();
  68870. }
  68871. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  68872. };
  68873. Bone.prototype.markAsDirty = function () {
  68874. this._currentRenderId++;
  68875. this._skeleton._markAsDirty();
  68876. };
  68877. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  68878. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  68879. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  68880. // all animation may be coming from a library skeleton, so may need to create animation
  68881. if (this.animations.length === 0) {
  68882. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  68883. this.animations[0].setKeys([]);
  68884. }
  68885. // get animation info / verify there is such a range from the source bone
  68886. var sourceRange = source.animations[0].getRange(rangeName);
  68887. if (!sourceRange) {
  68888. return false;
  68889. }
  68890. var from = sourceRange.from;
  68891. var to = sourceRange.to;
  68892. var sourceKeys = source.animations[0].getKeys();
  68893. // rescaling prep
  68894. var sourceBoneLength = source.length;
  68895. var sourceParent = source.getParent();
  68896. var parent = this.getParent();
  68897. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  68898. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  68899. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  68900. var destKeys = this.animations[0].getKeys();
  68901. // loop vars declaration
  68902. var orig;
  68903. var origTranslation;
  68904. var mat;
  68905. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  68906. orig = sourceKeys[key];
  68907. if (orig.frame >= from && orig.frame <= to) {
  68908. if (rescaleAsRequired) {
  68909. mat = orig.value.clone();
  68910. // scale based on parent ratio, when bone has parent
  68911. if (parentScalingReqd) {
  68912. origTranslation = mat.getTranslation();
  68913. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  68914. // scale based on skeleton dimension ratio when root bone, and value is passed
  68915. }
  68916. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  68917. origTranslation = mat.getTranslation();
  68918. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  68919. // use original when root bone, and no data for skelDimensionsRatio
  68920. }
  68921. else {
  68922. mat = orig.value;
  68923. }
  68924. }
  68925. else {
  68926. mat = orig.value;
  68927. }
  68928. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  68929. }
  68930. }
  68931. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  68932. return true;
  68933. };
  68934. /**
  68935. * Translate the bone in local or world space.
  68936. * @param vec The amount to translate the bone.
  68937. * @param space The space that the translation is in.
  68938. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68939. */
  68940. Bone.prototype.translate = function (vec, space, mesh) {
  68941. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68942. var lm = this.getLocalMatrix();
  68943. if (space == BABYLON.Space.LOCAL) {
  68944. lm.m[12] += vec.x;
  68945. lm.m[13] += vec.y;
  68946. lm.m[14] += vec.z;
  68947. }
  68948. else {
  68949. var wm = null;
  68950. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68951. if (mesh) {
  68952. wm = mesh.getWorldMatrix();
  68953. }
  68954. this._skeleton.computeAbsoluteTransforms();
  68955. var tmat = Bone._tmpMats[0];
  68956. var tvec = Bone._tmpVecs[0];
  68957. if (this._parent) {
  68958. if (mesh && wm) {
  68959. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68960. tmat.multiplyToRef(wm, tmat);
  68961. }
  68962. else {
  68963. tmat.copyFrom(this._parent.getAbsoluteTransform());
  68964. }
  68965. }
  68966. tmat.m[12] = 0;
  68967. tmat.m[13] = 0;
  68968. tmat.m[14] = 0;
  68969. tmat.invert();
  68970. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  68971. lm.m[12] += tvec.x;
  68972. lm.m[13] += tvec.y;
  68973. lm.m[14] += tvec.z;
  68974. }
  68975. this.markAsDirty();
  68976. };
  68977. /**
  68978. * Set the postion of the bone in local or world space.
  68979. * @param position The position to set the bone.
  68980. * @param space The space that the position is in.
  68981. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  68982. */
  68983. Bone.prototype.setPosition = function (position, space, mesh) {
  68984. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  68985. var lm = this.getLocalMatrix();
  68986. if (space == BABYLON.Space.LOCAL) {
  68987. lm.m[12] = position.x;
  68988. lm.m[13] = position.y;
  68989. lm.m[14] = position.z;
  68990. }
  68991. else {
  68992. var wm = null;
  68993. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  68994. if (mesh) {
  68995. wm = mesh.getWorldMatrix();
  68996. }
  68997. this._skeleton.computeAbsoluteTransforms();
  68998. var tmat = Bone._tmpMats[0];
  68999. var vec = Bone._tmpVecs[0];
  69000. if (this._parent) {
  69001. if (mesh && wm) {
  69002. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69003. tmat.multiplyToRef(wm, tmat);
  69004. }
  69005. else {
  69006. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69007. }
  69008. }
  69009. tmat.invert();
  69010. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  69011. lm.m[12] = vec.x;
  69012. lm.m[13] = vec.y;
  69013. lm.m[14] = vec.z;
  69014. }
  69015. this.markAsDirty();
  69016. };
  69017. /**
  69018. * Set the absolute postion of the bone (world space).
  69019. * @param position The position to set the bone.
  69020. * @param mesh The mesh that this bone is attached to.
  69021. */
  69022. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  69023. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  69024. };
  69025. /**
  69026. * Set the scale of the bone on the x, y and z axes.
  69027. * @param x The scale of the bone on the x axis.
  69028. * @param x The scale of the bone on the y axis.
  69029. * @param z The scale of the bone on the z axis.
  69030. * @param scaleChildren Set this to true if children of the bone should be scaled.
  69031. */
  69032. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  69033. if (scaleChildren === void 0) { scaleChildren = false; }
  69034. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  69035. if (!scaleChildren) {
  69036. this._negateScaleChildren.x = 1 / x;
  69037. this._negateScaleChildren.y = 1 / y;
  69038. this._negateScaleChildren.z = 1 / z;
  69039. }
  69040. this._syncScaleVector();
  69041. }
  69042. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  69043. };
  69044. /**
  69045. * Scale the bone on the x, y and z axes.
  69046. * @param x The amount to scale the bone on the x axis.
  69047. * @param x The amount to scale the bone on the y axis.
  69048. * @param z The amount to scale the bone on the z axis.
  69049. * @param scaleChildren Set this to true if children of the bone should be scaled.
  69050. */
  69051. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  69052. if (scaleChildren === void 0) { scaleChildren = false; }
  69053. var locMat = this.getLocalMatrix();
  69054. var origLocMat = Bone._tmpMats[0];
  69055. origLocMat.copyFrom(locMat);
  69056. var origLocMatInv = Bone._tmpMats[1];
  69057. origLocMatInv.copyFrom(origLocMat);
  69058. origLocMatInv.invert();
  69059. var scaleMat = Bone._tmpMats[2];
  69060. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  69061. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  69062. this._scaleVector.x *= x;
  69063. this._scaleVector.y *= y;
  69064. this._scaleVector.z *= z;
  69065. locMat.multiplyToRef(origLocMatInv, locMat);
  69066. locMat.multiplyToRef(scaleMat, locMat);
  69067. locMat.multiplyToRef(origLocMat, locMat);
  69068. var parent = this.getParent();
  69069. if (parent) {
  69070. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  69071. }
  69072. else {
  69073. this.getAbsoluteTransform().copyFrom(locMat);
  69074. }
  69075. var len = this.children.length;
  69076. scaleMat.invert();
  69077. for (var i = 0; i < len; i++) {
  69078. var child = this.children[i];
  69079. var cm = child.getLocalMatrix();
  69080. cm.multiplyToRef(scaleMat, cm);
  69081. var lm = child.getLocalMatrix();
  69082. lm.m[12] *= x;
  69083. lm.m[13] *= y;
  69084. lm.m[14] *= z;
  69085. }
  69086. this.computeAbsoluteTransforms();
  69087. if (scaleChildren) {
  69088. for (var i = 0; i < len; i++) {
  69089. this.children[i].scale(x, y, z, scaleChildren);
  69090. }
  69091. }
  69092. this.markAsDirty();
  69093. };
  69094. /**
  69095. * Set the yaw, pitch, and roll of the bone in local or world space.
  69096. * @param yaw The rotation of the bone on the y axis.
  69097. * @param pitch The rotation of the bone on the x axis.
  69098. * @param roll The rotation of the bone on the z axis.
  69099. * @param space The space that the axes of rotation are in.
  69100. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69101. */
  69102. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  69103. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69104. var rotMat = Bone._tmpMats[0];
  69105. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  69106. var rotMatInv = Bone._tmpMats[1];
  69107. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69108. rotMatInv.multiplyToRef(rotMat, rotMat);
  69109. this._rotateWithMatrix(rotMat, space, mesh);
  69110. };
  69111. /**
  69112. * Rotate the bone on an axis in local or world space.
  69113. * @param axis The axis to rotate the bone on.
  69114. * @param amount The amount to rotate the bone.
  69115. * @param space The space that the axis is in.
  69116. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69117. */
  69118. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  69119. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69120. var rmat = Bone._tmpMats[0];
  69121. rmat.m[12] = 0;
  69122. rmat.m[13] = 0;
  69123. rmat.m[14] = 0;
  69124. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  69125. this._rotateWithMatrix(rmat, space, mesh);
  69126. };
  69127. /**
  69128. * Set the rotation of the bone to a particular axis angle in local or world space.
  69129. * @param axis The axis to rotate the bone on.
  69130. * @param angle The angle that the bone should be rotated to.
  69131. * @param space The space that the axis is in.
  69132. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69133. */
  69134. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  69135. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69136. var rotMat = Bone._tmpMats[0];
  69137. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  69138. var rotMatInv = Bone._tmpMats[1];
  69139. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69140. rotMatInv.multiplyToRef(rotMat, rotMat);
  69141. this._rotateWithMatrix(rotMat, space, mesh);
  69142. };
  69143. /**
  69144. * Set the euler rotation of the bone in local of world space.
  69145. * @param rotation The euler rotation that the bone should be set to.
  69146. * @param space The space that the rotation is in.
  69147. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69148. */
  69149. Bone.prototype.setRotation = function (rotation, space, mesh) {
  69150. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69151. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  69152. };
  69153. /**
  69154. * Set the quaternion rotation of the bone in local of world space.
  69155. * @param quat The quaternion rotation that the bone should be set to.
  69156. * @param space The space that the rotation is in.
  69157. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69158. */
  69159. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  69160. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69161. var rotMatInv = Bone._tmpMats[0];
  69162. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69163. var rotMat = Bone._tmpMats[1];
  69164. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  69165. rotMatInv.multiplyToRef(rotMat, rotMat);
  69166. this._rotateWithMatrix(rotMat, space, mesh);
  69167. };
  69168. /**
  69169. * Set the rotation matrix of the bone in local of world space.
  69170. * @param rotMat The rotation matrix that the bone should be set to.
  69171. * @param space The space that the rotation is in.
  69172. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69173. */
  69174. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  69175. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69176. var rotMatInv = Bone._tmpMats[0];
  69177. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69178. var rotMat2 = Bone._tmpMats[1];
  69179. rotMat2.copyFrom(rotMat);
  69180. rotMatInv.multiplyToRef(rotMat, rotMat2);
  69181. this._rotateWithMatrix(rotMat2, space, mesh);
  69182. };
  69183. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  69184. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69185. var lmat = this.getLocalMatrix();
  69186. var lx = lmat.m[12];
  69187. var ly = lmat.m[13];
  69188. var lz = lmat.m[14];
  69189. var parent = this.getParent();
  69190. var parentScale = Bone._tmpMats[3];
  69191. var parentScaleInv = Bone._tmpMats[4];
  69192. if (parent) {
  69193. if (space == BABYLON.Space.WORLD) {
  69194. if (mesh) {
  69195. parentScale.copyFrom(mesh.getWorldMatrix());
  69196. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  69197. }
  69198. else {
  69199. parentScale.copyFrom(parent.getAbsoluteTransform());
  69200. }
  69201. }
  69202. else {
  69203. parentScale = parent._scaleMatrix;
  69204. }
  69205. parentScaleInv.copyFrom(parentScale);
  69206. parentScaleInv.invert();
  69207. lmat.multiplyToRef(parentScale, lmat);
  69208. lmat.multiplyToRef(rmat, lmat);
  69209. lmat.multiplyToRef(parentScaleInv, lmat);
  69210. }
  69211. else {
  69212. if (space == BABYLON.Space.WORLD && mesh) {
  69213. parentScale.copyFrom(mesh.getWorldMatrix());
  69214. parentScaleInv.copyFrom(parentScale);
  69215. parentScaleInv.invert();
  69216. lmat.multiplyToRef(parentScale, lmat);
  69217. lmat.multiplyToRef(rmat, lmat);
  69218. lmat.multiplyToRef(parentScaleInv, lmat);
  69219. }
  69220. else {
  69221. lmat.multiplyToRef(rmat, lmat);
  69222. }
  69223. }
  69224. lmat.m[12] = lx;
  69225. lmat.m[13] = ly;
  69226. lmat.m[14] = lz;
  69227. this.computeAbsoluteTransforms();
  69228. this.markAsDirty();
  69229. };
  69230. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  69231. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69232. if (space == BABYLON.Space.WORLD) {
  69233. var scaleMatrix = Bone._tmpMats[2];
  69234. scaleMatrix.copyFrom(this._scaleMatrix);
  69235. rotMatInv.copyFrom(this.getAbsoluteTransform());
  69236. if (mesh) {
  69237. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  69238. var meshScale = Bone._tmpMats[3];
  69239. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  69240. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  69241. }
  69242. rotMatInv.invert();
  69243. scaleMatrix.m[0] *= this._scalingDeterminant;
  69244. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69245. }
  69246. else {
  69247. rotMatInv.copyFrom(this.getLocalMatrix());
  69248. rotMatInv.invert();
  69249. var scaleMatrix = Bone._tmpMats[2];
  69250. scaleMatrix.copyFrom(this._scaleMatrix);
  69251. if (this._parent) {
  69252. var pscaleMatrix = Bone._tmpMats[3];
  69253. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  69254. pscaleMatrix.invert();
  69255. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  69256. }
  69257. else {
  69258. scaleMatrix.m[0] *= this._scalingDeterminant;
  69259. }
  69260. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69261. }
  69262. };
  69263. /**
  69264. * Get the scale of the bone
  69265. * @returns the scale of the bone
  69266. */
  69267. Bone.prototype.getScale = function () {
  69268. return this._scaleVector.clone();
  69269. };
  69270. /**
  69271. * Copy the scale of the bone to a vector3.
  69272. * @param result The vector3 to copy the scale to
  69273. */
  69274. Bone.prototype.getScaleToRef = function (result) {
  69275. result.copyFrom(this._scaleVector);
  69276. };
  69277. /**
  69278. * Get the position of the bone in local or world space.
  69279. * @param space The space that the returned position is in.
  69280. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69281. * @returns The position of the bone
  69282. */
  69283. Bone.prototype.getPosition = function (space, mesh) {
  69284. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69285. if (mesh === void 0) { mesh = null; }
  69286. var pos = BABYLON.Vector3.Zero();
  69287. this.getPositionToRef(space, mesh, pos);
  69288. return pos;
  69289. };
  69290. /**
  69291. * Copy the position of the bone to a vector3 in local or world space.
  69292. * @param space The space that the returned position is in.
  69293. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69294. * @param result The vector3 to copy the position to.
  69295. */
  69296. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  69297. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69298. if (space == BABYLON.Space.LOCAL) {
  69299. var lm = this.getLocalMatrix();
  69300. result.x = lm.m[12];
  69301. result.y = lm.m[13];
  69302. result.z = lm.m[14];
  69303. }
  69304. else {
  69305. var wm = null;
  69306. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69307. if (mesh) {
  69308. wm = mesh.getWorldMatrix();
  69309. }
  69310. this._skeleton.computeAbsoluteTransforms();
  69311. var tmat = Bone._tmpMats[0];
  69312. if (mesh && wm) {
  69313. tmat.copyFrom(this.getAbsoluteTransform());
  69314. tmat.multiplyToRef(wm, tmat);
  69315. }
  69316. else {
  69317. tmat = this.getAbsoluteTransform();
  69318. }
  69319. result.x = tmat.m[12];
  69320. result.y = tmat.m[13];
  69321. result.z = tmat.m[14];
  69322. }
  69323. };
  69324. /**
  69325. * Get the absolute position of the bone (world space).
  69326. * @param mesh The mesh that this bone is attached to.
  69327. * @returns The absolute position of the bone
  69328. */
  69329. Bone.prototype.getAbsolutePosition = function (mesh) {
  69330. if (mesh === void 0) { mesh = null; }
  69331. var pos = BABYLON.Vector3.Zero();
  69332. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  69333. return pos;
  69334. };
  69335. /**
  69336. * Copy the absolute position of the bone (world space) to the result param.
  69337. * @param mesh The mesh that this bone is attached to.
  69338. * @param result The vector3 to copy the absolute position to.
  69339. */
  69340. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69341. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69342. };
  69343. /**
  69344. * Compute the absolute transforms of this bone and its children.
  69345. */
  69346. Bone.prototype.computeAbsoluteTransforms = function () {
  69347. if (this._parent) {
  69348. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69349. }
  69350. else {
  69351. this._absoluteTransform.copyFrom(this._localMatrix);
  69352. var poseMatrix = this._skeleton.getPoseMatrix();
  69353. if (poseMatrix) {
  69354. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69355. }
  69356. }
  69357. var children = this.children;
  69358. var len = children.length;
  69359. for (var i = 0; i < len; i++) {
  69360. children[i].computeAbsoluteTransforms();
  69361. }
  69362. };
  69363. Bone.prototype._syncScaleVector = function () {
  69364. var lm = this.getLocalMatrix();
  69365. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69366. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69367. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69368. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69369. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69370. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69371. this._scaleVector.x = xs * Math.sqrt(xsq);
  69372. this._scaleVector.y = ys * Math.sqrt(ysq);
  69373. this._scaleVector.z = zs * Math.sqrt(zsq);
  69374. if (this._parent) {
  69375. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69376. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69377. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69378. }
  69379. 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);
  69380. };
  69381. /**
  69382. * Get the world direction from an axis that is in the local space of the bone.
  69383. * @param localAxis The local direction that is used to compute the world direction.
  69384. * @param mesh The mesh that this bone is attached to.
  69385. * @returns The world direction
  69386. */
  69387. Bone.prototype.getDirection = function (localAxis, mesh) {
  69388. if (mesh === void 0) { mesh = null; }
  69389. var result = BABYLON.Vector3.Zero();
  69390. this.getDirectionToRef(localAxis, mesh, result);
  69391. return result;
  69392. };
  69393. /**
  69394. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69395. * @param localAxis The local direction that is used to compute the world direction.
  69396. * @param mesh The mesh that this bone is attached to.
  69397. * @param result The vector3 that the world direction will be copied to.
  69398. */
  69399. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69400. if (mesh === void 0) { mesh = null; }
  69401. var wm = null;
  69402. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69403. if (mesh) {
  69404. wm = mesh.getWorldMatrix();
  69405. }
  69406. this._skeleton.computeAbsoluteTransforms();
  69407. var mat = Bone._tmpMats[0];
  69408. mat.copyFrom(this.getAbsoluteTransform());
  69409. if (mesh && wm) {
  69410. mat.multiplyToRef(wm, mat);
  69411. }
  69412. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69413. result.normalize();
  69414. };
  69415. /**
  69416. * Get the euler rotation of the bone in local or world space.
  69417. * @param space The space that the rotation should be in.
  69418. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69419. * @returns The euler rotation
  69420. */
  69421. Bone.prototype.getRotation = function (space, mesh) {
  69422. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69423. if (mesh === void 0) { mesh = null; }
  69424. var result = BABYLON.Vector3.Zero();
  69425. this.getRotationToRef(space, mesh, result);
  69426. return result;
  69427. };
  69428. /**
  69429. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69430. * @param space The space that the rotation should be in.
  69431. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69432. * @param result The vector3 that the rotation should be copied to.
  69433. */
  69434. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69435. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69436. if (mesh === void 0) { mesh = null; }
  69437. var quat = Bone._tmpQuat;
  69438. this.getRotationQuaternionToRef(space, mesh, quat);
  69439. quat.toEulerAnglesToRef(result);
  69440. };
  69441. /**
  69442. * Get the quaternion rotation of the bone in either local or world space.
  69443. * @param space The space that the rotation should be in.
  69444. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69445. * @returns The quaternion rotation
  69446. */
  69447. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69448. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69449. if (mesh === void 0) { mesh = null; }
  69450. var result = BABYLON.Quaternion.Identity();
  69451. this.getRotationQuaternionToRef(space, mesh, result);
  69452. return result;
  69453. };
  69454. /**
  69455. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69456. * @param space The space that the rotation should be in.
  69457. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69458. * @param result The quaternion that the rotation should be copied to.
  69459. */
  69460. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69461. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69462. if (mesh === void 0) { mesh = null; }
  69463. if (space == BABYLON.Space.LOCAL) {
  69464. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69465. }
  69466. else {
  69467. var mat = Bone._tmpMats[0];
  69468. var amat = this.getAbsoluteTransform();
  69469. if (mesh) {
  69470. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69471. }
  69472. else {
  69473. mat.copyFrom(amat);
  69474. }
  69475. mat.m[0] *= this._scalingDeterminant;
  69476. mat.m[1] *= this._scalingDeterminant;
  69477. mat.m[2] *= this._scalingDeterminant;
  69478. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69479. }
  69480. };
  69481. /**
  69482. * Get the rotation matrix of the bone in local or world space.
  69483. * @param space The space that the rotation should be in.
  69484. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69485. * @returns The rotation matrix
  69486. */
  69487. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69488. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69489. var result = BABYLON.Matrix.Identity();
  69490. this.getRotationMatrixToRef(space, mesh, result);
  69491. return result;
  69492. };
  69493. /**
  69494. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69495. * @param space The space that the rotation should be in.
  69496. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69497. * @param result The quaternion that the rotation should be copied to.
  69498. */
  69499. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69500. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69501. if (space == BABYLON.Space.LOCAL) {
  69502. this.getLocalMatrix().getRotationMatrixToRef(result);
  69503. }
  69504. else {
  69505. var mat = Bone._tmpMats[0];
  69506. var amat = this.getAbsoluteTransform();
  69507. if (mesh) {
  69508. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69509. }
  69510. else {
  69511. mat.copyFrom(amat);
  69512. }
  69513. mat.m[0] *= this._scalingDeterminant;
  69514. mat.m[1] *= this._scalingDeterminant;
  69515. mat.m[2] *= this._scalingDeterminant;
  69516. mat.getRotationMatrixToRef(result);
  69517. }
  69518. };
  69519. /**
  69520. * Get the world position of a point that is in the local space of the bone.
  69521. * @param position The local position
  69522. * @param mesh The mesh that this bone is attached to.
  69523. * @returns The world position
  69524. */
  69525. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69526. if (mesh === void 0) { mesh = null; }
  69527. var result = BABYLON.Vector3.Zero();
  69528. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69529. return result;
  69530. };
  69531. /**
  69532. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  69533. * @param position The local position
  69534. * @param mesh The mesh that this bone is attached to.
  69535. * @param result The vector3 that the world position should be copied to.
  69536. */
  69537. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  69538. if (mesh === void 0) { mesh = null; }
  69539. var wm = null;
  69540. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69541. if (mesh) {
  69542. wm = mesh.getWorldMatrix();
  69543. }
  69544. this._skeleton.computeAbsoluteTransforms();
  69545. var tmat = Bone._tmpMats[0];
  69546. if (mesh && wm) {
  69547. tmat.copyFrom(this.getAbsoluteTransform());
  69548. tmat.multiplyToRef(wm, tmat);
  69549. }
  69550. else {
  69551. tmat = this.getAbsoluteTransform();
  69552. }
  69553. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69554. };
  69555. /**
  69556. * Get the local position of a point that is in world space.
  69557. * @param position The world position
  69558. * @param mesh The mesh that this bone is attached to.
  69559. * @returns The local position
  69560. */
  69561. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  69562. if (mesh === void 0) { mesh = null; }
  69563. var result = BABYLON.Vector3.Zero();
  69564. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  69565. return result;
  69566. };
  69567. /**
  69568. * Get the local position of a point that is in world space and copy it to the result param.
  69569. * @param position The world position
  69570. * @param mesh The mesh that this bone is attached to.
  69571. * @param result The vector3 that the local position should be copied to.
  69572. */
  69573. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  69574. if (mesh === void 0) { mesh = null; }
  69575. var wm = null;
  69576. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69577. if (mesh) {
  69578. wm = mesh.getWorldMatrix();
  69579. }
  69580. this._skeleton.computeAbsoluteTransforms();
  69581. var tmat = Bone._tmpMats[0];
  69582. tmat.copyFrom(this.getAbsoluteTransform());
  69583. if (mesh && wm) {
  69584. tmat.multiplyToRef(wm, tmat);
  69585. }
  69586. tmat.invert();
  69587. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  69588. };
  69589. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69590. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  69591. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69592. return Bone;
  69593. }(BABYLON.Node));
  69594. BABYLON.Bone = Bone;
  69595. })(BABYLON || (BABYLON = {}));
  69596. //# sourceMappingURL=babylon.bone.js.map
  69597. var BABYLON;
  69598. (function (BABYLON) {
  69599. var BoneIKController = /** @class */ (function () {
  69600. function BoneIKController(mesh, bone, options) {
  69601. this.targetPosition = BABYLON.Vector3.Zero();
  69602. this.poleTargetPosition = BABYLON.Vector3.Zero();
  69603. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  69604. this.poleAngle = 0;
  69605. this.slerpAmount = 1;
  69606. this._bone1Quat = BABYLON.Quaternion.Identity();
  69607. this._bone1Mat = BABYLON.Matrix.Identity();
  69608. this._bone2Ang = Math.PI;
  69609. this._maxAngle = Math.PI;
  69610. this._rightHandedSystem = false;
  69611. this._bendAxis = BABYLON.Vector3.Right();
  69612. this._slerping = false;
  69613. this._adjustRoll = 0;
  69614. this._bone2 = bone;
  69615. this._bone1 = bone.getParent();
  69616. if (!this._bone1) {
  69617. return;
  69618. }
  69619. this.mesh = mesh;
  69620. var bonePos = bone.getPosition();
  69621. if (bone.getAbsoluteTransform().determinant() > 0) {
  69622. this._rightHandedSystem = true;
  69623. this._bendAxis.x = 0;
  69624. this._bendAxis.y = 0;
  69625. this._bendAxis.z = -1;
  69626. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  69627. this._adjustRoll = Math.PI * .5;
  69628. this._bendAxis.z = 1;
  69629. }
  69630. }
  69631. if (this._bone1.length) {
  69632. var boneScale1 = this._bone1.getScale();
  69633. var boneScale2 = this._bone2.getScale();
  69634. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  69635. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  69636. }
  69637. else if (this._bone1.children[0]) {
  69638. mesh.computeWorldMatrix(true);
  69639. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  69640. var pos2 = this._bone2.getAbsolutePosition(mesh);
  69641. var pos3 = this._bone1.getAbsolutePosition(mesh);
  69642. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  69643. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  69644. }
  69645. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  69646. this.maxAngle = Math.PI;
  69647. if (options) {
  69648. if (options.targetMesh) {
  69649. this.targetMesh = options.targetMesh;
  69650. this.targetMesh.computeWorldMatrix(true);
  69651. }
  69652. if (options.poleTargetMesh) {
  69653. this.poleTargetMesh = options.poleTargetMesh;
  69654. this.poleTargetMesh.computeWorldMatrix(true);
  69655. }
  69656. else if (options.poleTargetBone) {
  69657. this.poleTargetBone = options.poleTargetBone;
  69658. }
  69659. else if (this._bone1.getParent()) {
  69660. this.poleTargetBone = this._bone1.getParent();
  69661. }
  69662. if (options.poleTargetLocalOffset) {
  69663. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  69664. }
  69665. if (options.poleAngle) {
  69666. this.poleAngle = options.poleAngle;
  69667. }
  69668. if (options.bendAxis) {
  69669. this._bendAxis.copyFrom(options.bendAxis);
  69670. }
  69671. if (options.maxAngle) {
  69672. this.maxAngle = options.maxAngle;
  69673. }
  69674. if (options.slerpAmount) {
  69675. this.slerpAmount = options.slerpAmount;
  69676. }
  69677. }
  69678. }
  69679. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  69680. get: function () {
  69681. return this._maxAngle;
  69682. },
  69683. set: function (value) {
  69684. this._setMaxAngle(value);
  69685. },
  69686. enumerable: true,
  69687. configurable: true
  69688. });
  69689. BoneIKController.prototype._setMaxAngle = function (ang) {
  69690. if (ang < 0) {
  69691. ang = 0;
  69692. }
  69693. if (ang > Math.PI || ang == undefined) {
  69694. ang = Math.PI;
  69695. }
  69696. this._maxAngle = ang;
  69697. var a = this._bone1Length;
  69698. var b = this._bone2Length;
  69699. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  69700. };
  69701. BoneIKController.prototype.update = function () {
  69702. var bone1 = this._bone1;
  69703. if (!bone1) {
  69704. return;
  69705. }
  69706. var target = this.targetPosition;
  69707. var poleTarget = this.poleTargetPosition;
  69708. var mat1 = BoneIKController._tmpMats[0];
  69709. var mat2 = BoneIKController._tmpMats[1];
  69710. if (this.targetMesh) {
  69711. target.copyFrom(this.targetMesh.getAbsolutePosition());
  69712. }
  69713. if (this.poleTargetBone) {
  69714. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  69715. }
  69716. else if (this.poleTargetMesh) {
  69717. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  69718. }
  69719. var bonePos = BoneIKController._tmpVecs[0];
  69720. var zaxis = BoneIKController._tmpVecs[1];
  69721. var xaxis = BoneIKController._tmpVecs[2];
  69722. var yaxis = BoneIKController._tmpVecs[3];
  69723. var upAxis = BoneIKController._tmpVecs[4];
  69724. var _tmpQuat = BoneIKController._tmpQuat;
  69725. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  69726. poleTarget.subtractToRef(bonePos, upAxis);
  69727. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  69728. upAxis.y = 1;
  69729. }
  69730. else {
  69731. upAxis.normalize();
  69732. }
  69733. target.subtractToRef(bonePos, yaxis);
  69734. yaxis.normalize();
  69735. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  69736. zaxis.normalize();
  69737. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  69738. xaxis.normalize();
  69739. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  69740. var a = this._bone1Length;
  69741. var b = this._bone2Length;
  69742. var c = BABYLON.Vector3.Distance(bonePos, target);
  69743. if (this._maxReach > 0) {
  69744. c = Math.min(this._maxReach, c);
  69745. }
  69746. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  69747. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  69748. if (acosa > 1) {
  69749. acosa = 1;
  69750. }
  69751. if (acosb > 1) {
  69752. acosb = 1;
  69753. }
  69754. if (acosa < -1) {
  69755. acosa = -1;
  69756. }
  69757. if (acosb < -1) {
  69758. acosb = -1;
  69759. }
  69760. var angA = Math.acos(acosa);
  69761. var angB = Math.acos(acosb);
  69762. var angC = -angA - angB;
  69763. if (this._rightHandedSystem) {
  69764. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  69765. mat2.multiplyToRef(mat1, mat1);
  69766. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  69767. mat2.multiplyToRef(mat1, mat1);
  69768. }
  69769. else {
  69770. var _tmpVec = BoneIKController._tmpVecs[5];
  69771. _tmpVec.copyFrom(this._bendAxis);
  69772. _tmpVec.x *= -1;
  69773. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  69774. mat2.multiplyToRef(mat1, mat1);
  69775. }
  69776. if (this.poleAngle) {
  69777. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  69778. mat1.multiplyToRef(mat2, mat1);
  69779. }
  69780. if (this._bone1) {
  69781. if (this.slerpAmount < 1) {
  69782. if (!this._slerping) {
  69783. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  69784. }
  69785. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  69786. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  69787. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  69788. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  69789. this._slerping = true;
  69790. }
  69791. else {
  69792. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  69793. this._bone1Mat.copyFrom(mat1);
  69794. this._slerping = false;
  69795. }
  69796. }
  69797. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  69798. this._bone2Ang = angC;
  69799. };
  69800. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  69801. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  69802. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  69803. return BoneIKController;
  69804. }());
  69805. BABYLON.BoneIKController = BoneIKController;
  69806. })(BABYLON || (BABYLON = {}));
  69807. //# sourceMappingURL=babylon.boneIKController.js.map
  69808. var BABYLON;
  69809. (function (BABYLON) {
  69810. var BoneLookController = /** @class */ (function () {
  69811. /**
  69812. * Create a BoneLookController
  69813. * @param mesh the mesh that the bone belongs to
  69814. * @param bone the bone that will be looking to the target
  69815. * @param target the target Vector3 to look at
  69816. * @param settings optional settings:
  69817. * - maxYaw: the maximum angle the bone will yaw to
  69818. * - minYaw: the minimum angle the bone will yaw to
  69819. * - maxPitch: the maximum angle the bone will pitch to
  69820. * - minPitch: the minimum angle the bone will yaw to
  69821. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  69822. * - upAxis: the up axis of the coordinate system
  69823. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69824. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  69825. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  69826. * - adjustYaw: used to make an adjustment to the yaw of the bone
  69827. * - adjustPitch: used to make an adjustment to the pitch of the bone
  69828. * - adjustRoll: used to make an adjustment to the roll of the bone
  69829. **/
  69830. function BoneLookController(mesh, bone, target, options) {
  69831. /**
  69832. * The up axis of the coordinate system that is used when the bone is rotated.
  69833. */
  69834. this.upAxis = BABYLON.Vector3.Up();
  69835. /**
  69836. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  69837. */
  69838. this.upAxisSpace = BABYLON.Space.LOCAL;
  69839. /**
  69840. * Used to make an adjustment to the yaw of the bone.
  69841. */
  69842. this.adjustYaw = 0;
  69843. /**
  69844. * Used to make an adjustment to the pitch of the bone.
  69845. */
  69846. this.adjustPitch = 0;
  69847. /**
  69848. * Used to make an adjustment to the roll of the bone.
  69849. */
  69850. this.adjustRoll = 0;
  69851. /**
  69852. * 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).
  69853. */
  69854. this.slerpAmount = 1;
  69855. this._boneQuat = BABYLON.Quaternion.Identity();
  69856. this._slerping = false;
  69857. this._firstFrameSkipped = false;
  69858. this._fowardAxis = BABYLON.Vector3.Forward();
  69859. this.mesh = mesh;
  69860. this.bone = bone;
  69861. this.target = target;
  69862. if (options) {
  69863. if (options.adjustYaw) {
  69864. this.adjustYaw = options.adjustYaw;
  69865. }
  69866. if (options.adjustPitch) {
  69867. this.adjustPitch = options.adjustPitch;
  69868. }
  69869. if (options.adjustRoll) {
  69870. this.adjustRoll = options.adjustRoll;
  69871. }
  69872. if (options.maxYaw != null) {
  69873. this.maxYaw = options.maxYaw;
  69874. }
  69875. else {
  69876. this.maxYaw = Math.PI;
  69877. }
  69878. if (options.minYaw != null) {
  69879. this.minYaw = options.minYaw;
  69880. }
  69881. else {
  69882. this.minYaw = -Math.PI;
  69883. }
  69884. if (options.maxPitch != null) {
  69885. this.maxPitch = options.maxPitch;
  69886. }
  69887. else {
  69888. this.maxPitch = Math.PI;
  69889. }
  69890. if (options.minPitch != null) {
  69891. this.minPitch = options.minPitch;
  69892. }
  69893. else {
  69894. this.minPitch = -Math.PI;
  69895. }
  69896. if (options.slerpAmount != null) {
  69897. this.slerpAmount = options.slerpAmount;
  69898. }
  69899. if (options.upAxis != null) {
  69900. this.upAxis = options.upAxis;
  69901. }
  69902. if (options.upAxisSpace != null) {
  69903. this.upAxisSpace = options.upAxisSpace;
  69904. }
  69905. if (options.yawAxis != null || options.pitchAxis != null) {
  69906. var newYawAxis = BABYLON.Axis.Y;
  69907. var newPitchAxis = BABYLON.Axis.X;
  69908. if (options.yawAxis != null) {
  69909. newYawAxis = options.yawAxis.clone();
  69910. newYawAxis.normalize();
  69911. }
  69912. if (options.pitchAxis != null) {
  69913. newPitchAxis = options.pitchAxis.clone();
  69914. newPitchAxis.normalize();
  69915. }
  69916. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  69917. this._transformYawPitch = BABYLON.Matrix.Identity();
  69918. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  69919. this._transformYawPitchInv = this._transformYawPitch.clone();
  69920. this._transformYawPitch.invert();
  69921. }
  69922. }
  69923. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  69924. this.upAxisSpace = BABYLON.Space.LOCAL;
  69925. }
  69926. }
  69927. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  69928. /**
  69929. * Get/set the minimum yaw angle that the bone can look to.
  69930. */
  69931. get: function () {
  69932. return this._minYaw;
  69933. },
  69934. set: function (value) {
  69935. this._minYaw = value;
  69936. this._minYawSin = Math.sin(value);
  69937. this._minYawCos = Math.cos(value);
  69938. if (this._maxYaw != null) {
  69939. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69940. this._yawRange = this._maxYaw - this._minYaw;
  69941. }
  69942. },
  69943. enumerable: true,
  69944. configurable: true
  69945. });
  69946. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  69947. /**
  69948. * Get/set the maximum yaw angle that the bone can look to.
  69949. */
  69950. get: function () {
  69951. return this._maxYaw;
  69952. },
  69953. set: function (value) {
  69954. this._maxYaw = value;
  69955. this._maxYawSin = Math.sin(value);
  69956. this._maxYawCos = Math.cos(value);
  69957. if (this._minYaw != null) {
  69958. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  69959. this._yawRange = this._maxYaw - this._minYaw;
  69960. }
  69961. },
  69962. enumerable: true,
  69963. configurable: true
  69964. });
  69965. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  69966. /**
  69967. * Get/set the minimum pitch angle that the bone can look to.
  69968. */
  69969. get: function () {
  69970. return this._minPitch;
  69971. },
  69972. set: function (value) {
  69973. this._minPitch = value;
  69974. this._minPitchTan = Math.tan(value);
  69975. },
  69976. enumerable: true,
  69977. configurable: true
  69978. });
  69979. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  69980. /**
  69981. * Get/set the maximum pitch angle that the bone can look to.
  69982. */
  69983. get: function () {
  69984. return this._maxPitch;
  69985. },
  69986. set: function (value) {
  69987. this._maxPitch = value;
  69988. this._maxPitchTan = Math.tan(value);
  69989. },
  69990. enumerable: true,
  69991. configurable: true
  69992. });
  69993. /**
  69994. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  69995. */
  69996. BoneLookController.prototype.update = function () {
  69997. //skip the first frame when slerping so that the mesh rotation is correct
  69998. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  69999. this._firstFrameSkipped = true;
  70000. return;
  70001. }
  70002. var bone = this.bone;
  70003. var bonePos = BoneLookController._tmpVecs[0];
  70004. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  70005. var target = this.target;
  70006. var _tmpMat1 = BoneLookController._tmpMats[0];
  70007. var _tmpMat2 = BoneLookController._tmpMats[1];
  70008. var mesh = this.mesh;
  70009. var parentBone = bone.getParent();
  70010. var upAxis = BoneLookController._tmpVecs[1];
  70011. upAxis.copyFrom(this.upAxis);
  70012. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  70013. if (this._transformYawPitch) {
  70014. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  70015. }
  70016. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  70017. }
  70018. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  70019. mesh.getDirectionToRef(upAxis, upAxis);
  70020. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  70021. upAxis.normalize();
  70022. }
  70023. }
  70024. var checkYaw = false;
  70025. var checkPitch = false;
  70026. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  70027. checkYaw = true;
  70028. }
  70029. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  70030. checkPitch = true;
  70031. }
  70032. if (checkYaw || checkPitch) {
  70033. var spaceMat = BoneLookController._tmpMats[2];
  70034. var spaceMatInv = BoneLookController._tmpMats[3];
  70035. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  70036. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  70037. }
  70038. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  70039. spaceMat.copyFrom(mesh.getWorldMatrix());
  70040. }
  70041. else {
  70042. var forwardAxis = BoneLookController._tmpVecs[2];
  70043. forwardAxis.copyFrom(this._fowardAxis);
  70044. if (this._transformYawPitch) {
  70045. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  70046. }
  70047. if (parentBone) {
  70048. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  70049. }
  70050. else {
  70051. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  70052. }
  70053. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  70054. rightAxis.normalize();
  70055. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  70056. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  70057. }
  70058. spaceMat.invertToRef(spaceMatInv);
  70059. var xzlen = null;
  70060. if (checkPitch) {
  70061. var localTarget = BoneLookController._tmpVecs[3];
  70062. target.subtractToRef(bonePos, localTarget);
  70063. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70064. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70065. var pitch = Math.atan2(localTarget.y, xzlen);
  70066. var newPitch = pitch;
  70067. if (pitch > this._maxPitch) {
  70068. localTarget.y = this._maxPitchTan * xzlen;
  70069. newPitch = this._maxPitch;
  70070. }
  70071. else if (pitch < this._minPitch) {
  70072. localTarget.y = this._minPitchTan * xzlen;
  70073. newPitch = this._minPitch;
  70074. }
  70075. if (pitch != newPitch) {
  70076. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70077. localTarget.addInPlace(bonePos);
  70078. target = localTarget;
  70079. }
  70080. }
  70081. if (checkYaw) {
  70082. var localTarget = BoneLookController._tmpVecs[4];
  70083. target.subtractToRef(bonePos, localTarget);
  70084. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70085. var yaw = Math.atan2(localTarget.x, localTarget.z);
  70086. var newYaw = yaw;
  70087. if (yaw > this._maxYaw || yaw < this._minYaw) {
  70088. if (xzlen == null) {
  70089. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70090. }
  70091. if (this._yawRange > Math.PI) {
  70092. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  70093. localTarget.z = this._maxYawCos * xzlen;
  70094. localTarget.x = this._maxYawSin * xzlen;
  70095. newYaw = this._maxYaw;
  70096. }
  70097. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  70098. localTarget.z = this._minYawCos * xzlen;
  70099. localTarget.x = this._minYawSin * xzlen;
  70100. newYaw = this._minYaw;
  70101. }
  70102. }
  70103. else {
  70104. if (yaw > this._maxYaw) {
  70105. localTarget.z = this._maxYawCos * xzlen;
  70106. localTarget.x = this._maxYawSin * xzlen;
  70107. newYaw = this._maxYaw;
  70108. }
  70109. else if (yaw < this._minYaw) {
  70110. localTarget.z = this._minYawCos * xzlen;
  70111. localTarget.x = this._minYawSin * xzlen;
  70112. newYaw = this._minYaw;
  70113. }
  70114. }
  70115. }
  70116. if (this._slerping && this._yawRange > Math.PI) {
  70117. //are we going to be crossing into the min/max region?
  70118. var boneFwd = BoneLookController._tmpVecs[8];
  70119. boneFwd.copyFrom(BABYLON.Axis.Z);
  70120. if (this._transformYawPitch) {
  70121. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  70122. }
  70123. var boneRotMat = BoneLookController._tmpMats[4];
  70124. this._boneQuat.toRotationMatrix(boneRotMat);
  70125. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  70126. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  70127. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  70128. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  70129. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  70130. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  70131. if (angBtwTar > angBtwMidYaw) {
  70132. if (xzlen == null) {
  70133. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70134. }
  70135. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  70136. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  70137. if (angBtwMin < angBtwMax) {
  70138. newYaw = boneYaw + Math.PI * .75;
  70139. localTarget.z = Math.cos(newYaw) * xzlen;
  70140. localTarget.x = Math.sin(newYaw) * xzlen;
  70141. }
  70142. else {
  70143. newYaw = boneYaw - Math.PI * .75;
  70144. localTarget.z = Math.cos(newYaw) * xzlen;
  70145. localTarget.x = Math.sin(newYaw) * xzlen;
  70146. }
  70147. }
  70148. }
  70149. if (yaw != newYaw) {
  70150. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70151. localTarget.addInPlace(bonePos);
  70152. target = localTarget;
  70153. }
  70154. }
  70155. }
  70156. var zaxis = BoneLookController._tmpVecs[5];
  70157. var xaxis = BoneLookController._tmpVecs[6];
  70158. var yaxis = BoneLookController._tmpVecs[7];
  70159. var _tmpQuat = BoneLookController._tmpQuat;
  70160. target.subtractToRef(bonePos, zaxis);
  70161. zaxis.normalize();
  70162. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  70163. xaxis.normalize();
  70164. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  70165. yaxis.normalize();
  70166. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  70167. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  70168. return;
  70169. }
  70170. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  70171. return;
  70172. }
  70173. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  70174. return;
  70175. }
  70176. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  70177. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  70178. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  70179. }
  70180. if (this.slerpAmount < 1) {
  70181. if (!this._slerping) {
  70182. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  70183. }
  70184. if (this._transformYawPitch) {
  70185. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70186. }
  70187. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  70188. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  70189. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  70190. this._slerping = true;
  70191. }
  70192. else {
  70193. if (this._transformYawPitch) {
  70194. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70195. }
  70196. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  70197. this._slerping = false;
  70198. }
  70199. };
  70200. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  70201. var angDiff = ang2 - ang1;
  70202. angDiff %= Math.PI * 2;
  70203. if (angDiff > Math.PI) {
  70204. angDiff -= Math.PI * 2;
  70205. }
  70206. else if (angDiff < -Math.PI) {
  70207. angDiff += Math.PI * 2;
  70208. }
  70209. return angDiff;
  70210. };
  70211. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  70212. ang1 %= (2 * Math.PI);
  70213. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70214. ang2 %= (2 * Math.PI);
  70215. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70216. var ab = 0;
  70217. if (ang1 < ang2) {
  70218. ab = ang2 - ang1;
  70219. }
  70220. else {
  70221. ab = ang1 - ang2;
  70222. }
  70223. if (ab > Math.PI) {
  70224. ab = Math.PI * 2 - ab;
  70225. }
  70226. return ab;
  70227. };
  70228. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  70229. ang %= (2 * Math.PI);
  70230. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  70231. ang1 %= (2 * Math.PI);
  70232. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70233. ang2 %= (2 * Math.PI);
  70234. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70235. if (ang1 < ang2) {
  70236. if (ang > ang1 && ang < ang2) {
  70237. return true;
  70238. }
  70239. }
  70240. else {
  70241. if (ang > ang2 && ang < ang1) {
  70242. return true;
  70243. }
  70244. }
  70245. return false;
  70246. };
  70247. 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()];
  70248. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  70249. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70250. return BoneLookController;
  70251. }());
  70252. BABYLON.BoneLookController = BoneLookController;
  70253. })(BABYLON || (BABYLON = {}));
  70254. //# sourceMappingURL=babylon.boneLookController.js.map
  70255. var BABYLON;
  70256. (function (BABYLON) {
  70257. var Skeleton = /** @class */ (function () {
  70258. function Skeleton(name, id, scene) {
  70259. this.name = name;
  70260. this.id = id;
  70261. this.bones = new Array();
  70262. this.needInitialSkinMatrix = false;
  70263. this._isDirty = true;
  70264. this._meshesWithPoseMatrix = new Array();
  70265. this._identity = BABYLON.Matrix.Identity();
  70266. this._ranges = {};
  70267. this._lastAbsoluteTransformsUpdateId = -1;
  70268. /**
  70269. * Specifies if the skeleton should be serialized.
  70270. */
  70271. this.doNotSerialize = false;
  70272. // Events
  70273. /**
  70274. * An event triggered before computing the skeleton's matrices
  70275. * @type {BABYLON.Observable}
  70276. */
  70277. this.onBeforeComputeObservable = new BABYLON.Observable();
  70278. this.bones = [];
  70279. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70280. scene.skeletons.push(this);
  70281. //make sure it will recalculate the matrix next time prepare is called.
  70282. this._isDirty = true;
  70283. }
  70284. // Members
  70285. Skeleton.prototype.getTransformMatrices = function (mesh) {
  70286. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  70287. return mesh._bonesTransformMatrices;
  70288. }
  70289. if (!this._transformMatrices) {
  70290. this.prepare();
  70291. }
  70292. return this._transformMatrices;
  70293. };
  70294. Skeleton.prototype.getScene = function () {
  70295. return this._scene;
  70296. };
  70297. // Methods
  70298. /**
  70299. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  70300. */
  70301. Skeleton.prototype.toString = function (fullDetails) {
  70302. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  70303. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  70304. if (fullDetails) {
  70305. ret += ", Ranges: {";
  70306. var first = true;
  70307. for (var name_1 in this._ranges) {
  70308. if (first) {
  70309. ret += ", ";
  70310. first = false;
  70311. }
  70312. ret += name_1;
  70313. }
  70314. ret += "}";
  70315. }
  70316. return ret;
  70317. };
  70318. /**
  70319. * Get bone's index searching by name
  70320. * @param {string} name is bone's name to search for
  70321. * @return {number} Indice of the bone. Returns -1 if not found
  70322. */
  70323. Skeleton.prototype.getBoneIndexByName = function (name) {
  70324. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  70325. if (this.bones[boneIndex].name === name) {
  70326. return boneIndex;
  70327. }
  70328. }
  70329. return -1;
  70330. };
  70331. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  70332. // check name not already in use
  70333. if (!this._ranges[name]) {
  70334. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  70335. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70336. if (this.bones[i].animations[0]) {
  70337. this.bones[i].animations[0].createRange(name, from, to);
  70338. }
  70339. }
  70340. }
  70341. };
  70342. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  70343. if (deleteFrames === void 0) { deleteFrames = true; }
  70344. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70345. if (this.bones[i].animations[0]) {
  70346. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70347. }
  70348. }
  70349. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70350. };
  70351. Skeleton.prototype.getAnimationRange = function (name) {
  70352. return this._ranges[name];
  70353. };
  70354. /**
  70355. * Returns as an Array, all AnimationRanges defined on this skeleton
  70356. */
  70357. Skeleton.prototype.getAnimationRanges = function () {
  70358. var animationRanges = [];
  70359. var name;
  70360. var i = 0;
  70361. for (name in this._ranges) {
  70362. animationRanges[i] = this._ranges[name];
  70363. i++;
  70364. }
  70365. return animationRanges;
  70366. };
  70367. /**
  70368. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70369. */
  70370. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70371. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70372. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70373. return false;
  70374. }
  70375. var ret = true;
  70376. var frameOffset = this._getHighestAnimationFrame() + 1;
  70377. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70378. var boneDict = {};
  70379. var sourceBones = source.bones;
  70380. var nBones;
  70381. var i;
  70382. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70383. boneDict[sourceBones[i].name] = sourceBones[i];
  70384. }
  70385. if (this.bones.length !== sourceBones.length) {
  70386. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70387. ret = false;
  70388. }
  70389. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70390. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70391. var boneName = this.bones[i].name;
  70392. var sourceBone = boneDict[boneName];
  70393. if (sourceBone) {
  70394. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70395. }
  70396. else {
  70397. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70398. ret = false;
  70399. }
  70400. }
  70401. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70402. var range = source.getAnimationRange(name);
  70403. if (range) {
  70404. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70405. }
  70406. return ret;
  70407. };
  70408. Skeleton.prototype.returnToRest = function () {
  70409. for (var index = 0; index < this.bones.length; index++) {
  70410. this.bones[index].returnToRest();
  70411. }
  70412. };
  70413. Skeleton.prototype._getHighestAnimationFrame = function () {
  70414. var ret = 0;
  70415. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70416. if (this.bones[i].animations[0]) {
  70417. var highest = this.bones[i].animations[0].getHighestFrame();
  70418. if (ret < highest) {
  70419. ret = highest;
  70420. }
  70421. }
  70422. }
  70423. return ret;
  70424. };
  70425. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70426. var range = this.getAnimationRange(name);
  70427. if (!range) {
  70428. return null;
  70429. }
  70430. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70431. };
  70432. Skeleton.prototype._markAsDirty = function () {
  70433. this._isDirty = true;
  70434. };
  70435. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70436. this._meshesWithPoseMatrix.push(mesh);
  70437. };
  70438. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70439. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70440. if (index > -1) {
  70441. this._meshesWithPoseMatrix.splice(index, 1);
  70442. }
  70443. };
  70444. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70445. this.onBeforeComputeObservable.notifyObservers(this);
  70446. for (var index = 0; index < this.bones.length; index++) {
  70447. var bone = this.bones[index];
  70448. var parentBone = bone.getParent();
  70449. if (parentBone) {
  70450. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70451. }
  70452. else {
  70453. if (initialSkinMatrix) {
  70454. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70455. }
  70456. else {
  70457. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70458. }
  70459. }
  70460. if (bone._index !== -1) {
  70461. var mappedIndex = bone._index === null ? index : bone._index;
  70462. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70463. }
  70464. }
  70465. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70466. };
  70467. Skeleton.prototype.prepare = function () {
  70468. if (!this._isDirty) {
  70469. return;
  70470. }
  70471. if (this.needInitialSkinMatrix) {
  70472. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70473. var mesh = this._meshesWithPoseMatrix[index];
  70474. var poseMatrix = mesh.getPoseMatrix();
  70475. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70476. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70477. }
  70478. if (this._synchronizedWithMesh !== mesh) {
  70479. this._synchronizedWithMesh = mesh;
  70480. // Prepare bones
  70481. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70482. var bone = this.bones[boneIndex];
  70483. if (!bone.getParent()) {
  70484. var matrix = bone.getBaseMatrix();
  70485. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70486. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70487. }
  70488. }
  70489. }
  70490. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70491. }
  70492. }
  70493. else {
  70494. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70495. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70496. }
  70497. this._computeTransformMatrices(this._transformMatrices, null);
  70498. }
  70499. this._isDirty = false;
  70500. this._scene._activeBones.addCount(this.bones.length, false);
  70501. };
  70502. Skeleton.prototype.getAnimatables = function () {
  70503. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70504. this._animatables = [];
  70505. for (var index = 0; index < this.bones.length; index++) {
  70506. this._animatables.push(this.bones[index]);
  70507. }
  70508. }
  70509. return this._animatables;
  70510. };
  70511. Skeleton.prototype.clone = function (name, id) {
  70512. var result = new Skeleton(name, id || name, this._scene);
  70513. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70514. for (var index = 0; index < this.bones.length; index++) {
  70515. var source = this.bones[index];
  70516. var parentBone = null;
  70517. var parent_1 = source.getParent();
  70518. if (parent_1) {
  70519. var parentIndex = this.bones.indexOf(parent_1);
  70520. parentBone = result.bones[parentIndex];
  70521. }
  70522. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70523. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70524. }
  70525. if (this._ranges) {
  70526. result._ranges = {};
  70527. for (var rangeName in this._ranges) {
  70528. var range = this._ranges[rangeName];
  70529. if (range) {
  70530. result._ranges[rangeName] = range.clone();
  70531. }
  70532. }
  70533. }
  70534. this._isDirty = true;
  70535. return result;
  70536. };
  70537. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  70538. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  70539. this.bones.forEach(function (bone) {
  70540. bone.animations.forEach(function (animation) {
  70541. animation.enableBlending = true;
  70542. animation.blendingSpeed = blendingSpeed;
  70543. });
  70544. });
  70545. };
  70546. Skeleton.prototype.dispose = function () {
  70547. this._meshesWithPoseMatrix = [];
  70548. // Animations
  70549. this.getScene().stopAnimation(this);
  70550. // Remove from scene
  70551. this.getScene().removeSkeleton(this);
  70552. };
  70553. Skeleton.prototype.serialize = function () {
  70554. var serializationObject = {};
  70555. serializationObject.name = this.name;
  70556. serializationObject.id = this.id;
  70557. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  70558. serializationObject.bones = [];
  70559. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70560. for (var index = 0; index < this.bones.length; index++) {
  70561. var bone = this.bones[index];
  70562. var parent_2 = bone.getParent();
  70563. var serializedBone = {
  70564. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  70565. name: bone.name,
  70566. matrix: bone.getBaseMatrix().toArray(),
  70567. rest: bone.getRestPose().toArray()
  70568. };
  70569. serializationObject.bones.push(serializedBone);
  70570. if (bone.length) {
  70571. serializedBone.length = bone.length;
  70572. }
  70573. if (bone.animations && bone.animations.length > 0) {
  70574. serializedBone.animation = bone.animations[0].serialize();
  70575. }
  70576. serializationObject.ranges = [];
  70577. for (var name in this._ranges) {
  70578. var source = this._ranges[name];
  70579. if (!source) {
  70580. continue;
  70581. }
  70582. var range = {};
  70583. range.name = name;
  70584. range.from = source.from;
  70585. range.to = source.to;
  70586. serializationObject.ranges.push(range);
  70587. }
  70588. }
  70589. return serializationObject;
  70590. };
  70591. Skeleton.Parse = function (parsedSkeleton, scene) {
  70592. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  70593. if (parsedSkeleton.dimensionsAtRest) {
  70594. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  70595. }
  70596. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  70597. var index;
  70598. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  70599. var parsedBone = parsedSkeleton.bones[index];
  70600. var parentBone = null;
  70601. if (parsedBone.parentBoneIndex > -1) {
  70602. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  70603. }
  70604. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  70605. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  70606. if (parsedBone.length) {
  70607. bone.length = parsedBone.length;
  70608. }
  70609. if (parsedBone.animation) {
  70610. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  70611. }
  70612. }
  70613. // placed after bones, so createAnimationRange can cascade down
  70614. if (parsedSkeleton.ranges) {
  70615. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  70616. var data = parsedSkeleton.ranges[index];
  70617. skeleton.createAnimationRange(data.name, data.from, data.to);
  70618. }
  70619. }
  70620. return skeleton;
  70621. };
  70622. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  70623. if (forceUpdate === void 0) { forceUpdate = false; }
  70624. var renderId = this._scene.getRenderId();
  70625. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  70626. this.bones[0].computeAbsoluteTransforms();
  70627. this._lastAbsoluteTransformsUpdateId = renderId;
  70628. }
  70629. };
  70630. Skeleton.prototype.getPoseMatrix = function () {
  70631. var poseMatrix = null;
  70632. if (this._meshesWithPoseMatrix.length > 0) {
  70633. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  70634. }
  70635. return poseMatrix;
  70636. };
  70637. Skeleton.prototype.sortBones = function () {
  70638. var bones = new Array();
  70639. var visited = new Array(this.bones.length);
  70640. for (var index = 0; index < this.bones.length; index++) {
  70641. this._sortBones(index, bones, visited);
  70642. }
  70643. this.bones = bones;
  70644. };
  70645. Skeleton.prototype._sortBones = function (index, bones, visited) {
  70646. if (visited[index]) {
  70647. return;
  70648. }
  70649. visited[index] = true;
  70650. var bone = this.bones[index];
  70651. if (bone._index === undefined) {
  70652. bone._index = index;
  70653. }
  70654. var parentBone = bone.getParent();
  70655. if (parentBone) {
  70656. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  70657. }
  70658. bones.push(bone);
  70659. };
  70660. return Skeleton;
  70661. }());
  70662. BABYLON.Skeleton = Skeleton;
  70663. })(BABYLON || (BABYLON = {}));
  70664. //# sourceMappingURL=babylon.skeleton.js.map
  70665. var BABYLON;
  70666. (function (BABYLON) {
  70667. var SphericalPolynomial = /** @class */ (function () {
  70668. function SphericalPolynomial() {
  70669. this.x = BABYLON.Vector3.Zero();
  70670. this.y = BABYLON.Vector3.Zero();
  70671. this.z = BABYLON.Vector3.Zero();
  70672. this.xx = BABYLON.Vector3.Zero();
  70673. this.yy = BABYLON.Vector3.Zero();
  70674. this.zz = BABYLON.Vector3.Zero();
  70675. this.xy = BABYLON.Vector3.Zero();
  70676. this.yz = BABYLON.Vector3.Zero();
  70677. this.zx = BABYLON.Vector3.Zero();
  70678. }
  70679. SphericalPolynomial.prototype.addAmbient = function (color) {
  70680. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70681. this.xx = this.xx.add(colorVector);
  70682. this.yy = this.yy.add(colorVector);
  70683. this.zz = this.zz.add(colorVector);
  70684. };
  70685. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  70686. var result = new SphericalPolynomial();
  70687. result.x = harmonics.L11.scale(1.02333);
  70688. result.y = harmonics.L1_1.scale(1.02333);
  70689. result.z = harmonics.L10.scale(1.02333);
  70690. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  70691. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  70692. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  70693. result.yz = harmonics.L2_1.scale(0.858086);
  70694. result.zx = harmonics.L21.scale(0.858086);
  70695. result.xy = harmonics.L2_2.scale(0.858086);
  70696. result.scale(1.0 / Math.PI);
  70697. return result;
  70698. };
  70699. SphericalPolynomial.prototype.scale = function (scale) {
  70700. this.x = this.x.scale(scale);
  70701. this.y = this.y.scale(scale);
  70702. this.z = this.z.scale(scale);
  70703. this.xx = this.xx.scale(scale);
  70704. this.yy = this.yy.scale(scale);
  70705. this.zz = this.zz.scale(scale);
  70706. this.yz = this.yz.scale(scale);
  70707. this.zx = this.zx.scale(scale);
  70708. this.xy = this.xy.scale(scale);
  70709. };
  70710. return SphericalPolynomial;
  70711. }());
  70712. BABYLON.SphericalPolynomial = SphericalPolynomial;
  70713. var SphericalHarmonics = /** @class */ (function () {
  70714. function SphericalHarmonics() {
  70715. this.L00 = BABYLON.Vector3.Zero();
  70716. this.L1_1 = BABYLON.Vector3.Zero();
  70717. this.L10 = BABYLON.Vector3.Zero();
  70718. this.L11 = BABYLON.Vector3.Zero();
  70719. this.L2_2 = BABYLON.Vector3.Zero();
  70720. this.L2_1 = BABYLON.Vector3.Zero();
  70721. this.L20 = BABYLON.Vector3.Zero();
  70722. this.L21 = BABYLON.Vector3.Zero();
  70723. this.L22 = BABYLON.Vector3.Zero();
  70724. }
  70725. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  70726. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  70727. var c = colorVector.scale(deltaSolidAngle);
  70728. this.L00 = this.L00.add(c.scale(0.282095));
  70729. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  70730. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  70731. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  70732. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  70733. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  70734. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  70735. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  70736. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  70737. };
  70738. SphericalHarmonics.prototype.scale = function (scale) {
  70739. this.L00 = this.L00.scale(scale);
  70740. this.L1_1 = this.L1_1.scale(scale);
  70741. this.L10 = this.L10.scale(scale);
  70742. this.L11 = this.L11.scale(scale);
  70743. this.L2_2 = this.L2_2.scale(scale);
  70744. this.L2_1 = this.L2_1.scale(scale);
  70745. this.L20 = this.L20.scale(scale);
  70746. this.L21 = this.L21.scale(scale);
  70747. this.L22 = this.L22.scale(scale);
  70748. };
  70749. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  70750. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  70751. //
  70752. // E_lm = A_l * L_lm
  70753. //
  70754. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  70755. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  70756. // the scaling factors are given in equation 9.
  70757. // Constant (Band 0)
  70758. this.L00 = this.L00.scale(3.141593);
  70759. // Linear (Band 1)
  70760. this.L1_1 = this.L1_1.scale(2.094395);
  70761. this.L10 = this.L10.scale(2.094395);
  70762. this.L11 = this.L11.scale(2.094395);
  70763. // Quadratic (Band 2)
  70764. this.L2_2 = this.L2_2.scale(0.785398);
  70765. this.L2_1 = this.L2_1.scale(0.785398);
  70766. this.L20 = this.L20.scale(0.785398);
  70767. this.L21 = this.L21.scale(0.785398);
  70768. this.L22 = this.L22.scale(0.785398);
  70769. };
  70770. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  70771. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  70772. // L = (1/pi) * E * rho
  70773. //
  70774. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  70775. this.scale(1.0 / Math.PI);
  70776. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  70777. // (The pixel shader must apply albedo after texture fetches, etc).
  70778. };
  70779. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  70780. var result = new SphericalHarmonics();
  70781. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  70782. result.L1_1 = polynomial.y.scale(0.977204);
  70783. result.L10 = polynomial.z.scale(0.977204);
  70784. result.L11 = polynomial.x.scale(0.977204);
  70785. result.L2_2 = polynomial.xy.scale(1.16538);
  70786. result.L2_1 = polynomial.yz.scale(1.16538);
  70787. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  70788. result.L21 = polynomial.zx.scale(1.16538);
  70789. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  70790. result.scale(Math.PI);
  70791. return result;
  70792. };
  70793. return SphericalHarmonics;
  70794. }());
  70795. BABYLON.SphericalHarmonics = SphericalHarmonics;
  70796. })(BABYLON || (BABYLON = {}));
  70797. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  70798. var BABYLON;
  70799. (function (BABYLON) {
  70800. var FileFaceOrientation = /** @class */ (function () {
  70801. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  70802. this.name = name;
  70803. this.worldAxisForNormal = worldAxisForNormal;
  70804. this.worldAxisForFileX = worldAxisForFileX;
  70805. this.worldAxisForFileY = worldAxisForFileY;
  70806. }
  70807. return FileFaceOrientation;
  70808. }());
  70809. ;
  70810. /**
  70811. * Helper class dealing with the extraction of spherical polynomial dataArray
  70812. * from a cube map.
  70813. */
  70814. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  70815. function CubeMapToSphericalPolynomialTools() {
  70816. }
  70817. /**
  70818. * Converts a texture to the according Spherical Polynomial data.
  70819. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70820. *
  70821. * @param texture The texture to extract the information from.
  70822. * @return The Spherical Polynomial data.
  70823. */
  70824. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  70825. if (!texture.isCube) {
  70826. // Only supports cube Textures currently.
  70827. return null;
  70828. }
  70829. var size = texture.getSize().width;
  70830. var right = texture.readPixels(0);
  70831. var left = texture.readPixels(1);
  70832. var up;
  70833. var down;
  70834. if (texture.isRenderTarget) {
  70835. up = texture.readPixels(3);
  70836. down = texture.readPixels(2);
  70837. }
  70838. else {
  70839. up = texture.readPixels(2);
  70840. down = texture.readPixels(3);
  70841. }
  70842. var front = texture.readPixels(4);
  70843. var back = texture.readPixels(5);
  70844. var gammaSpace = texture.gammaSpace;
  70845. // Always read as RGBA.
  70846. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  70847. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70848. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70849. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70850. }
  70851. var cubeInfo = {
  70852. size: size,
  70853. right: right,
  70854. left: left,
  70855. up: up,
  70856. down: down,
  70857. front: front,
  70858. back: back,
  70859. format: format,
  70860. type: type,
  70861. gammaSpace: gammaSpace,
  70862. };
  70863. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  70864. };
  70865. /**
  70866. * Converts a cubemap to the according Spherical Polynomial data.
  70867. * This extracts the first 3 orders only as they are the only one used in the lighting.
  70868. *
  70869. * @param cubeInfo The Cube map to extract the information from.
  70870. * @return The Spherical Polynomial data.
  70871. */
  70872. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  70873. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  70874. var totalSolidAngle = 0.0;
  70875. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  70876. var du = 2.0 / cubeInfo.size;
  70877. var dv = du;
  70878. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  70879. var minUV = du * 0.5 - 1.0;
  70880. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  70881. var fileFace = this.FileFaces[faceIndex];
  70882. var dataArray = cubeInfo[fileFace.name];
  70883. var v = minUV;
  70884. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  70885. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  70886. // Because SP is still linear, so summation is fine in that basis.
  70887. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  70888. for (var y = 0; y < cubeInfo.size; y++) {
  70889. var u = minUV;
  70890. for (var x = 0; x < cubeInfo.size; x++) {
  70891. // World direction (not normalised)
  70892. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  70893. worldDirection.normalize();
  70894. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  70895. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  70896. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  70897. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  70898. // Handle Integer types.
  70899. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  70900. r /= 255;
  70901. g /= 255;
  70902. b /= 255;
  70903. }
  70904. // Handle Gamma space textures.
  70905. if (cubeInfo.gammaSpace) {
  70906. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  70907. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  70908. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  70909. }
  70910. var color = new BABYLON.Color3(r, g, b);
  70911. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  70912. totalSolidAngle += deltaSolidAngle;
  70913. u += du;
  70914. }
  70915. v += dv;
  70916. }
  70917. }
  70918. // Solid angle for entire sphere is 4*pi
  70919. var sphereSolidAngle = 4.0 * Math.PI;
  70920. // Adjust the solid angle to allow for how many faces we processed.
  70921. var facesProcessed = 6.0;
  70922. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  70923. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  70924. // This is needed because the numerical integration over the cube uses a
  70925. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  70926. // and also to compensate for accumulative error due to float precision in the summation.
  70927. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  70928. sphericalHarmonics.scale(correctionFactor);
  70929. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  70930. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  70931. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  70932. };
  70933. CubeMapToSphericalPolynomialTools.FileFaces = [
  70934. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  70935. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  70936. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  70937. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  70938. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  70939. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  70940. ];
  70941. return CubeMapToSphericalPolynomialTools;
  70942. }());
  70943. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  70944. })(BABYLON || (BABYLON = {}));
  70945. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  70946. var BABYLON;
  70947. (function (BABYLON) {
  70948. /**
  70949. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  70950. */
  70951. var PanoramaToCubeMapTools = /** @class */ (function () {
  70952. function PanoramaToCubeMapTools() {
  70953. }
  70954. /**
  70955. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  70956. *
  70957. * @param float32Array The source data.
  70958. * @param inputWidth The width of the input panorama.
  70959. * @param inputhHeight The height of the input panorama.
  70960. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  70961. * @return The cubemap data
  70962. */
  70963. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  70964. if (!float32Array) {
  70965. throw "ConvertPanoramaToCubemap: input cannot be null";
  70966. }
  70967. if (float32Array.length != inputWidth * inputHeight * 3) {
  70968. throw "ConvertPanoramaToCubemap: input size is wrong";
  70969. }
  70970. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  70971. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  70972. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  70973. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  70974. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  70975. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  70976. return {
  70977. front: textureFront,
  70978. back: textureBack,
  70979. left: textureLeft,
  70980. right: textureRight,
  70981. up: textureUp,
  70982. down: textureDown,
  70983. size: size,
  70984. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  70985. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  70986. gammaSpace: false,
  70987. };
  70988. };
  70989. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  70990. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  70991. var textureArray = new Float32Array(buffer);
  70992. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  70993. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  70994. var dy = 1 / texSize;
  70995. var fy = 0;
  70996. for (var y = 0; y < texSize; y++) {
  70997. var xv1 = faceData[0];
  70998. var xv2 = faceData[2];
  70999. for (var x = 0; x < texSize; x++) {
  71000. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  71001. v.normalize();
  71002. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  71003. // 3 channels per pixels
  71004. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  71005. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  71006. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  71007. xv1 = xv1.add(rotDX1);
  71008. xv2 = xv2.add(rotDX2);
  71009. }
  71010. fy += dy;
  71011. }
  71012. return textureArray;
  71013. };
  71014. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  71015. var theta = Math.atan2(vDir.z, vDir.x);
  71016. var phi = Math.acos(vDir.y);
  71017. while (theta < -Math.PI)
  71018. theta += 2 * Math.PI;
  71019. while (theta > Math.PI)
  71020. theta -= 2 * Math.PI;
  71021. var dx = theta / Math.PI;
  71022. var dy = phi / Math.PI;
  71023. // recenter.
  71024. dx = dx * 0.5 + 0.5;
  71025. var px = Math.round(dx * inputWidth);
  71026. if (px < 0)
  71027. px = 0;
  71028. else if (px >= inputWidth)
  71029. px = inputWidth - 1;
  71030. var py = Math.round(dy * inputHeight);
  71031. if (py < 0)
  71032. py = 0;
  71033. else if (py >= inputHeight)
  71034. py = inputHeight - 1;
  71035. var inputY = (inputHeight - py - 1);
  71036. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  71037. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  71038. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  71039. return {
  71040. r: r,
  71041. g: g,
  71042. b: b
  71043. };
  71044. };
  71045. PanoramaToCubeMapTools.FACE_FRONT = [
  71046. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71047. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71048. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71049. new BABYLON.Vector3(1.0, 1.0, -1.0)
  71050. ];
  71051. PanoramaToCubeMapTools.FACE_BACK = [
  71052. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71053. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71054. new BABYLON.Vector3(1.0, 1.0, 1.0),
  71055. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  71056. ];
  71057. PanoramaToCubeMapTools.FACE_RIGHT = [
  71058. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71059. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71060. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71061. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71062. ];
  71063. PanoramaToCubeMapTools.FACE_LEFT = [
  71064. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71065. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71066. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71067. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  71068. ];
  71069. PanoramaToCubeMapTools.FACE_DOWN = [
  71070. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71071. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71072. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71073. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71074. ];
  71075. PanoramaToCubeMapTools.FACE_UP = [
  71076. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71077. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71078. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71079. new BABYLON.Vector3(1.0, -1.0, -1.0)
  71080. ];
  71081. return PanoramaToCubeMapTools;
  71082. }());
  71083. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  71084. })(BABYLON || (BABYLON = {}));
  71085. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  71086. var BABYLON;
  71087. (function (BABYLON) {
  71088. ;
  71089. /**
  71090. * This groups tools to convert HDR texture to native colors array.
  71091. */
  71092. var HDRTools = /** @class */ (function () {
  71093. function HDRTools() {
  71094. }
  71095. HDRTools.Ldexp = function (mantissa, exponent) {
  71096. if (exponent > 1023) {
  71097. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  71098. }
  71099. if (exponent < -1074) {
  71100. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  71101. }
  71102. return mantissa * Math.pow(2, exponent);
  71103. };
  71104. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  71105. if (exponent > 0) {
  71106. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  71107. float32array[index + 0] = red * exponent;
  71108. float32array[index + 1] = green * exponent;
  71109. float32array[index + 2] = blue * exponent;
  71110. }
  71111. else {
  71112. float32array[index + 0] = 0;
  71113. float32array[index + 1] = 0;
  71114. float32array[index + 2] = 0;
  71115. }
  71116. };
  71117. HDRTools.readStringLine = function (uint8array, startIndex) {
  71118. var line = "";
  71119. var character = "";
  71120. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  71121. character = String.fromCharCode(uint8array[i]);
  71122. if (character == "\n") {
  71123. break;
  71124. }
  71125. line += character;
  71126. }
  71127. return line;
  71128. };
  71129. /**
  71130. * Reads header information from an RGBE texture stored in a native array.
  71131. * More information on this format are available here:
  71132. * https://en.wikipedia.org/wiki/RGBE_image_format
  71133. *
  71134. * @param uint8array The binary file stored in native array.
  71135. * @return The header information.
  71136. */
  71137. HDRTools.RGBE_ReadHeader = function (uint8array) {
  71138. var height = 0;
  71139. var width = 0;
  71140. var line = this.readStringLine(uint8array, 0);
  71141. if (line[0] != '#' || line[1] != '?') {
  71142. throw "Bad HDR Format.";
  71143. }
  71144. var endOfHeader = false;
  71145. var findFormat = false;
  71146. var lineIndex = 0;
  71147. do {
  71148. lineIndex += (line.length + 1);
  71149. line = this.readStringLine(uint8array, lineIndex);
  71150. if (line == "FORMAT=32-bit_rle_rgbe") {
  71151. findFormat = true;
  71152. }
  71153. else if (line.length == 0) {
  71154. endOfHeader = true;
  71155. }
  71156. } while (!endOfHeader);
  71157. if (!findFormat) {
  71158. throw "HDR Bad header format, unsupported FORMAT";
  71159. }
  71160. lineIndex += (line.length + 1);
  71161. line = this.readStringLine(uint8array, lineIndex);
  71162. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  71163. var match = sizeRegexp.exec(line);
  71164. // TODO. Support +Y and -X if needed.
  71165. if (!match || match.length < 3) {
  71166. throw "HDR Bad header format, no size";
  71167. }
  71168. width = parseInt(match[2]);
  71169. height = parseInt(match[1]);
  71170. if (width < 8 || width > 0x7fff) {
  71171. throw "HDR Bad header format, unsupported size";
  71172. }
  71173. lineIndex += (line.length + 1);
  71174. return {
  71175. height: height,
  71176. width: width,
  71177. dataPosition: lineIndex
  71178. };
  71179. };
  71180. /**
  71181. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  71182. * This RGBE texture needs to store the information as a panorama.
  71183. *
  71184. * More information on this format are available here:
  71185. * https://en.wikipedia.org/wiki/RGBE_image_format
  71186. *
  71187. * @param buffer The binary file stored in an array buffer.
  71188. * @param size The expected size of the extracted cubemap.
  71189. * @return The Cube Map information.
  71190. */
  71191. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  71192. var uint8array = new Uint8Array(buffer);
  71193. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  71194. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71195. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  71196. return cubeMapData;
  71197. };
  71198. /**
  71199. * Returns the pixels data extracted from an RGBE texture.
  71200. * This pixels will be stored left to right up to down in the R G B order in one array.
  71201. *
  71202. * More information on this format are available here:
  71203. * https://en.wikipedia.org/wiki/RGBE_image_format
  71204. *
  71205. * @param uint8array The binary file stored in an array buffer.
  71206. * @param hdrInfo The header information of the file.
  71207. * @return The pixels data in RGB right to left up to down order.
  71208. */
  71209. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  71210. // Keep for multi format supports.
  71211. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71212. };
  71213. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  71214. var num_scanlines = hdrInfo.height;
  71215. var scanline_width = hdrInfo.width;
  71216. var a, b, c, d, count;
  71217. var dataIndex = hdrInfo.dataPosition;
  71218. var index = 0, endIndex = 0, i = 0;
  71219. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  71220. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  71221. // 3 channels of 4 bytes per pixel in float.
  71222. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  71223. var resultArray = new Float32Array(resultBuffer);
  71224. // read in each successive scanline
  71225. while (num_scanlines > 0) {
  71226. a = uint8array[dataIndex++];
  71227. b = uint8array[dataIndex++];
  71228. c = uint8array[dataIndex++];
  71229. d = uint8array[dataIndex++];
  71230. if (a != 2 || b != 2 || (c & 0x80)) {
  71231. // this file is not run length encoded
  71232. throw "HDR Bad header format, not RLE";
  71233. }
  71234. if (((c << 8) | d) != scanline_width) {
  71235. throw "HDR Bad header format, wrong scan line width";
  71236. }
  71237. index = 0;
  71238. // read each of the four channels for the scanline into the buffer
  71239. for (i = 0; i < 4; i++) {
  71240. endIndex = (i + 1) * scanline_width;
  71241. while (index < endIndex) {
  71242. a = uint8array[dataIndex++];
  71243. b = uint8array[dataIndex++];
  71244. if (a > 128) {
  71245. // a run of the same value
  71246. count = a - 128;
  71247. if ((count == 0) || (count > endIndex - index)) {
  71248. throw "HDR Bad Format, bad scanline data (run)";
  71249. }
  71250. while (count-- > 0) {
  71251. scanLineArray[index++] = b;
  71252. }
  71253. }
  71254. else {
  71255. // a non-run
  71256. count = a;
  71257. if ((count == 0) || (count > endIndex - index)) {
  71258. throw "HDR Bad Format, bad scanline data (non-run)";
  71259. }
  71260. scanLineArray[index++] = b;
  71261. if (--count > 0) {
  71262. for (var j = 0; j < count; j++) {
  71263. scanLineArray[index++] = uint8array[dataIndex++];
  71264. }
  71265. }
  71266. }
  71267. }
  71268. }
  71269. // now convert data from buffer into floats
  71270. for (i = 0; i < scanline_width; i++) {
  71271. a = scanLineArray[i];
  71272. b = scanLineArray[i + scanline_width];
  71273. c = scanLineArray[i + 2 * scanline_width];
  71274. d = scanLineArray[i + 3 * scanline_width];
  71275. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  71276. }
  71277. num_scanlines--;
  71278. }
  71279. return resultArray;
  71280. };
  71281. return HDRTools;
  71282. }());
  71283. BABYLON.HDRTools = HDRTools;
  71284. })(BABYLON || (BABYLON = {}));
  71285. //# sourceMappingURL=babylon.hdr.js.map
  71286. var BABYLON;
  71287. (function (BABYLON) {
  71288. /**
  71289. * This represents a texture coming from an HDR input.
  71290. *
  71291. * The only supported format is currently panorama picture stored in RGBE format.
  71292. * Example of such files can be found on HDRLib: http://hdrlib.com/
  71293. */
  71294. var HDRCubeTexture = /** @class */ (function (_super) {
  71295. __extends(HDRCubeTexture, _super);
  71296. /**
  71297. * Instantiates an HDRTexture from the following parameters.
  71298. *
  71299. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  71300. * @param scene The scene the texture will be used in
  71301. * @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.
  71302. * @param noMipmap Forces to not generate the mipmap if true
  71303. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  71304. * @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)
  71305. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  71306. */
  71307. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  71308. if (noMipmap === void 0) { noMipmap = false; }
  71309. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71310. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71311. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71312. if (onLoad === void 0) { onLoad = null; }
  71313. if (onError === void 0) { onError = null; }
  71314. var _this = _super.call(this, scene) || this;
  71315. _this._useInGammaSpace = false;
  71316. _this._generateHarmonics = true;
  71317. _this._isBABYLONPreprocessed = false;
  71318. _this._onLoad = null;
  71319. _this._onError = null;
  71320. /**
  71321. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  71322. */
  71323. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71324. /**
  71325. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  71326. * This is usefull at run time to apply the good shader.
  71327. */
  71328. _this.isPMREM = false;
  71329. _this._isBlocking = true;
  71330. if (!url) {
  71331. return _this;
  71332. }
  71333. _this.name = url;
  71334. _this.url = url;
  71335. _this.hasAlpha = false;
  71336. _this.isCube = true;
  71337. _this._textureMatrix = BABYLON.Matrix.Identity();
  71338. _this._onLoad = onLoad;
  71339. _this._onError = onError;
  71340. _this.gammaSpace = false;
  71341. var caps = scene.getEngine().getCaps();
  71342. if (size) {
  71343. _this._isBABYLONPreprocessed = false;
  71344. _this._noMipmap = noMipmap;
  71345. _this._size = size;
  71346. _this._useInGammaSpace = useInGammaSpace;
  71347. _this._usePMREMGenerator = usePMREMGenerator &&
  71348. caps.textureLOD &&
  71349. caps.textureFloat &&
  71350. !_this._useInGammaSpace;
  71351. }
  71352. else {
  71353. _this._isBABYLONPreprocessed = true;
  71354. _this._noMipmap = false;
  71355. _this._useInGammaSpace = false;
  71356. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71357. !_this._useInGammaSpace;
  71358. }
  71359. _this.isPMREM = _this._usePMREMGenerator;
  71360. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71361. if (!_this._texture) {
  71362. if (!scene.useDelayedTextureLoading) {
  71363. _this.loadTexture();
  71364. }
  71365. else {
  71366. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71367. }
  71368. }
  71369. return _this;
  71370. }
  71371. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71372. /**
  71373. * Gets wether or not the texture is blocking during loading.
  71374. */
  71375. get: function () {
  71376. return this._isBlocking;
  71377. },
  71378. /**
  71379. * Sets wether or not the texture is blocking during loading.
  71380. */
  71381. set: function (value) {
  71382. this._isBlocking = value;
  71383. },
  71384. enumerable: true,
  71385. configurable: true
  71386. });
  71387. /**
  71388. * Occurs when the file is a preprocessed .babylon.hdr file.
  71389. */
  71390. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71391. var _this = this;
  71392. var mipLevels = 0;
  71393. var floatArrayView = null;
  71394. var scene = this.getScene();
  71395. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71396. var mips = new Array();
  71397. if (!floatArrayView) {
  71398. return mips;
  71399. }
  71400. var startIndex = 30;
  71401. for (var level = 0; level < mipLevels; level++) {
  71402. mips.push([]);
  71403. // Fill each pixel of the mip level.
  71404. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71405. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71406. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71407. mips[level].push(faceData);
  71408. startIndex += faceSize;
  71409. }
  71410. }
  71411. return mips;
  71412. } : null;
  71413. var callback = function (buffer) {
  71414. var scene = _this.getScene();
  71415. if (!scene) {
  71416. return null;
  71417. }
  71418. // Create Native Array Views
  71419. var intArrayView = new Int32Array(buffer);
  71420. floatArrayView = new Float32Array(buffer);
  71421. // Fill header.
  71422. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71423. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71424. // Update Texture Information.
  71425. if (!_this._texture) {
  71426. return null;
  71427. }
  71428. _this._texture.updateSize(_this._size, _this._size);
  71429. // Fill polynomial information.
  71430. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71431. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71432. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71433. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71434. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71435. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71436. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71437. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71438. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71439. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71440. _this.sphericalPolynomial = sphericalPolynomial;
  71441. // Fill pixel data.
  71442. mipLevels = intArrayView[29]; // Number of mip levels.
  71443. var startIndex = 30;
  71444. var data = [];
  71445. var faceSize = Math.pow(_this._size, 2) * 3;
  71446. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71447. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71448. startIndex += faceSize;
  71449. }
  71450. var results = [];
  71451. var byteArray = null;
  71452. // Push each faces.
  71453. for (var k = 0; k < 6; k++) {
  71454. var dataFace = null;
  71455. // To be deprecated.
  71456. if (version === 1) {
  71457. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71458. dataFace = data[j];
  71459. }
  71460. // If special cases.
  71461. if (!mipmapGenerator && dataFace) {
  71462. if (!scene.getEngine().getCaps().textureFloat) {
  71463. // 3 channels of 1 bytes per pixel in bytes.
  71464. var byteBuffer = new ArrayBuffer(faceSize);
  71465. byteArray = new Uint8Array(byteBuffer);
  71466. }
  71467. for (var i = 0; i < _this._size * _this._size; i++) {
  71468. // Put in gamma space if requested.
  71469. if (_this._useInGammaSpace) {
  71470. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71471. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71472. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71473. }
  71474. // Convert to int texture for fallback.
  71475. if (byteArray) {
  71476. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71477. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71478. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71479. // May use luminance instead if the result is not accurate.
  71480. var max = Math.max(Math.max(r, g), b);
  71481. if (max > 255) {
  71482. var scale = 255 / max;
  71483. r *= scale;
  71484. g *= scale;
  71485. b *= scale;
  71486. }
  71487. byteArray[(i * 3) + 0] = r;
  71488. byteArray[(i * 3) + 1] = g;
  71489. byteArray[(i * 3) + 2] = b;
  71490. }
  71491. }
  71492. }
  71493. // Fill the array accordingly.
  71494. if (byteArray) {
  71495. results.push(byteArray);
  71496. }
  71497. else {
  71498. results.push(dataFace);
  71499. }
  71500. }
  71501. return results;
  71502. };
  71503. if (scene) {
  71504. 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);
  71505. }
  71506. };
  71507. /**
  71508. * Occurs when the file is raw .hdr file.
  71509. */
  71510. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71511. var _this = this;
  71512. var callback = function (buffer) {
  71513. var scene = _this.getScene();
  71514. if (!scene) {
  71515. return null;
  71516. }
  71517. // Extract the raw linear data.
  71518. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71519. // Generate harmonics if needed.
  71520. if (_this._generateHarmonics) {
  71521. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71522. _this.sphericalPolynomial = sphericalPolynomial;
  71523. }
  71524. var results = [];
  71525. var byteArray = null;
  71526. // Push each faces.
  71527. for (var j = 0; j < 6; j++) {
  71528. // Create uintarray fallback.
  71529. if (!scene.getEngine().getCaps().textureFloat) {
  71530. // 3 channels of 1 bytes per pixel in bytes.
  71531. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  71532. byteArray = new Uint8Array(byteBuffer);
  71533. }
  71534. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  71535. // If special cases.
  71536. if (_this._useInGammaSpace || byteArray) {
  71537. for (var i = 0; i < _this._size * _this._size; i++) {
  71538. // Put in gamma space if requested.
  71539. if (_this._useInGammaSpace) {
  71540. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71541. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71542. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71543. }
  71544. // Convert to int texture for fallback.
  71545. if (byteArray) {
  71546. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71547. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71548. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71549. // May use luminance instead if the result is not accurate.
  71550. var max = Math.max(Math.max(r, g), b);
  71551. if (max > 255) {
  71552. var scale = 255 / max;
  71553. r *= scale;
  71554. g *= scale;
  71555. b *= scale;
  71556. }
  71557. byteArray[(i * 3) + 0] = r;
  71558. byteArray[(i * 3) + 1] = g;
  71559. byteArray[(i * 3) + 2] = b;
  71560. }
  71561. }
  71562. }
  71563. if (byteArray) {
  71564. results.push(byteArray);
  71565. }
  71566. else {
  71567. results.push(dataFace);
  71568. }
  71569. }
  71570. return results;
  71571. };
  71572. var mipmapGenerator = null;
  71573. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  71574. // if (!this._noMipmap &&
  71575. // this._usePMREMGenerator) {
  71576. // mipmapGenerator = (data: ArrayBufferView[]) => {
  71577. // // Custom setup of the generator matching with the PBR shader values.
  71578. // var generator = new BABYLON.PMREMGenerator(data,
  71579. // this._size,
  71580. // this._size,
  71581. // 0,
  71582. // 3,
  71583. // this.getScene().getEngine().getCaps().textureFloat,
  71584. // 2048,
  71585. // 0.25,
  71586. // false,
  71587. // true);
  71588. // return generator.filterCubeMap();
  71589. // };
  71590. // }
  71591. var scene = this.getScene();
  71592. if (scene) {
  71593. 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);
  71594. }
  71595. };
  71596. /**
  71597. * Starts the loading process of the texture.
  71598. */
  71599. HDRCubeTexture.prototype.loadTexture = function () {
  71600. if (this._isBABYLONPreprocessed) {
  71601. this.loadBabylonTexture();
  71602. }
  71603. else {
  71604. this.loadHDRTexture();
  71605. }
  71606. };
  71607. HDRCubeTexture.prototype.clone = function () {
  71608. var scene = this.getScene();
  71609. if (!scene) {
  71610. return this;
  71611. }
  71612. var size = (this._isBABYLONPreprocessed ? null : this._size);
  71613. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  71614. // Base texture
  71615. newTexture.level = this.level;
  71616. newTexture.wrapU = this.wrapU;
  71617. newTexture.wrapV = this.wrapV;
  71618. newTexture.coordinatesIndex = this.coordinatesIndex;
  71619. newTexture.coordinatesMode = this.coordinatesMode;
  71620. return newTexture;
  71621. };
  71622. // Methods
  71623. HDRCubeTexture.prototype.delayLoad = function () {
  71624. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71625. return;
  71626. }
  71627. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71628. this._texture = this._getFromCache(this.url, this._noMipmap);
  71629. if (!this._texture) {
  71630. this.loadTexture();
  71631. }
  71632. };
  71633. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  71634. return this._textureMatrix;
  71635. };
  71636. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71637. this._textureMatrix = value;
  71638. };
  71639. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71640. var texture = null;
  71641. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  71642. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  71643. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  71644. texture.name = parsedTexture.name;
  71645. texture.hasAlpha = parsedTexture.hasAlpha;
  71646. texture.level = parsedTexture.level;
  71647. texture.coordinatesMode = parsedTexture.coordinatesMode;
  71648. texture.isBlocking = parsedTexture.isBlocking;
  71649. }
  71650. return texture;
  71651. };
  71652. HDRCubeTexture.prototype.serialize = function () {
  71653. if (!this.name) {
  71654. return null;
  71655. }
  71656. var serializationObject = {};
  71657. serializationObject.name = this.name;
  71658. serializationObject.hasAlpha = this.hasAlpha;
  71659. serializationObject.isCube = true;
  71660. serializationObject.level = this.level;
  71661. serializationObject.size = this._size;
  71662. serializationObject.coordinatesMode = this.coordinatesMode;
  71663. serializationObject.useInGammaSpace = this._useInGammaSpace;
  71664. serializationObject.generateHarmonics = this._generateHarmonics;
  71665. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  71666. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  71667. serializationObject.customType = "BABYLON.HDRCubeTexture";
  71668. serializationObject.noMipmap = this._noMipmap;
  71669. serializationObject.isBlocking = this._isBlocking;
  71670. return serializationObject;
  71671. };
  71672. /**
  71673. * Saves as a file the data contained in the texture in a binary format.
  71674. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71675. * as the spherical used in the lighting.
  71676. * @param url The HDR file url.
  71677. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71678. * @param onError Method called if any error happens during download.
  71679. * @return The packed binary data.
  71680. */
  71681. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  71682. if (onError === void 0) { onError = null; }
  71683. var callback = function (buffer) {
  71684. var data = new Blob([buffer], { type: 'application/octet-stream' });
  71685. // Returns a URL you can use as a href.
  71686. var objUrl = window.URL.createObjectURL(data);
  71687. // Simulates a link to it and click to dowload.
  71688. var a = document.createElement("a");
  71689. document.body.appendChild(a);
  71690. a.style.display = "none";
  71691. a.href = objUrl;
  71692. a.download = "envmap.babylon.hdr";
  71693. a.click();
  71694. };
  71695. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  71696. };
  71697. /**
  71698. * Serializes the data contained in the texture in a binary format.
  71699. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  71700. * as the spherical used in the lighting.
  71701. * @param url The HDR file url.
  71702. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  71703. * @param onError Method called if any error happens during download.
  71704. * @return The packed binary data.
  71705. */
  71706. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  71707. if (onError === void 0) { onError = null; }
  71708. // Needs the url tho create the texture.
  71709. if (!url) {
  71710. return;
  71711. }
  71712. // Check Power of two size.
  71713. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  71714. return;
  71715. }
  71716. // Coming Back in 3.x.
  71717. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  71718. };
  71719. HDRCubeTexture._facesMapping = [
  71720. "right",
  71721. "left",
  71722. "up",
  71723. "down",
  71724. "front",
  71725. "back"
  71726. ];
  71727. return HDRCubeTexture;
  71728. }(BABYLON.BaseTexture));
  71729. BABYLON.HDRCubeTexture = HDRCubeTexture;
  71730. })(BABYLON || (BABYLON = {}));
  71731. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  71732. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  71733. // Huge respect for a such great lib.
  71734. // Earcut license:
  71735. // Copyright (c) 2016, Mapbox
  71736. //
  71737. // Permission to use, copy, modify, and/or distribute this software for any purpose
  71738. // with or without fee is hereby granted, provided that the above copyright notice
  71739. // and this permission notice appear in all copies.
  71740. //
  71741. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  71742. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  71743. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  71744. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  71745. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  71746. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  71747. // THIS SOFTWARE.
  71748. var Earcut;
  71749. (function (Earcut) {
  71750. /**
  71751. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  71752. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  71753. * @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).
  71754. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  71755. */
  71756. function earcut(data, holeIndices, dim) {
  71757. dim = dim || 2;
  71758. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  71759. if (!outerNode)
  71760. return triangles;
  71761. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  71762. if (hasHoles)
  71763. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  71764. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  71765. if (data.length > 80 * dim) {
  71766. minX = maxX = data[0];
  71767. minY = maxY = data[1];
  71768. for (var i = dim; i < outerLen; i += dim) {
  71769. x = data[i];
  71770. y = data[i + 1];
  71771. if (x < minX)
  71772. minX = x;
  71773. if (y < minY)
  71774. minY = y;
  71775. if (x > maxX)
  71776. maxX = x;
  71777. if (y > maxY)
  71778. maxY = y;
  71779. }
  71780. // minX, minY and size are later used to transform coords into integers for z-order calculation
  71781. size = Math.max(maxX - minX, maxY - minY);
  71782. }
  71783. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  71784. return triangles;
  71785. }
  71786. Earcut.earcut = earcut;
  71787. var Node = /** @class */ (function () {
  71788. function Node(i, x, y) {
  71789. this.i = i;
  71790. this.x = x;
  71791. this.y = y;
  71792. this.prev = null;
  71793. this.next = null;
  71794. this.z = null;
  71795. this.prevZ = null;
  71796. this.nextZ = null;
  71797. this.steiner = false;
  71798. }
  71799. return Node;
  71800. }());
  71801. // create a circular doubly linked list from polygon points in the specified winding order
  71802. function linkedList(data, start, end, dim, clockwise) {
  71803. var i, last = null;
  71804. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  71805. for (i = start; i < end; i += dim)
  71806. last = insertNode(i, data[i], data[i + 1], last);
  71807. }
  71808. else {
  71809. for (i = end - dim; i >= start; i -= dim)
  71810. last = insertNode(i, data[i], data[i + 1], last);
  71811. }
  71812. if (last && equals(last, last.next)) {
  71813. removeNode(last);
  71814. last = last.next;
  71815. }
  71816. return last;
  71817. }
  71818. // eliminate colinear or duplicate points
  71819. function filterPoints(start, end) {
  71820. if (!start)
  71821. return start;
  71822. if (!end)
  71823. end = start;
  71824. var p = start, again;
  71825. do {
  71826. again = false;
  71827. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  71828. removeNode(p);
  71829. p = end = p.prev;
  71830. if (p === p.next)
  71831. return undefined;
  71832. again = true;
  71833. }
  71834. else {
  71835. p = p.next;
  71836. }
  71837. } while (again || p !== end);
  71838. return end;
  71839. }
  71840. // main ear slicing loop which triangulates a polygon (given as a linked list)
  71841. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  71842. if (!ear)
  71843. return;
  71844. // interlink polygon nodes in z-order
  71845. if (!pass && size)
  71846. indexCurve(ear, minX, minY, size);
  71847. var stop = ear, prev, next;
  71848. // iterate through ears, slicing them one by one
  71849. while (ear.prev !== ear.next) {
  71850. prev = ear.prev;
  71851. next = ear.next;
  71852. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  71853. // cut off the triangle
  71854. triangles.push(prev.i / dim);
  71855. triangles.push(ear.i / dim);
  71856. triangles.push(next.i / dim);
  71857. removeNode(ear);
  71858. // skipping the next vertice leads to less sliver triangles
  71859. ear = next.next;
  71860. stop = next.next;
  71861. continue;
  71862. }
  71863. ear = next;
  71864. // if we looped through the whole remaining polygon and can't find any more ears
  71865. if (ear === stop) {
  71866. // try filtering points and slicing again
  71867. if (!pass) {
  71868. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  71869. // if this didn't work, try curing all small self-intersections locally
  71870. }
  71871. else if (pass === 1) {
  71872. ear = cureLocalIntersections(ear, triangles, dim);
  71873. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  71874. // as a last resort, try splitting the remaining polygon into two
  71875. }
  71876. else if (pass === 2) {
  71877. splitEarcut(ear, triangles, dim, minX, minY, size);
  71878. }
  71879. break;
  71880. }
  71881. }
  71882. }
  71883. // check whether a polygon node forms a valid ear with adjacent nodes
  71884. function isEar(ear) {
  71885. var a = ear.prev, b = ear, c = ear.next;
  71886. if (area(a, b, c) >= 0)
  71887. return false; // reflex, can't be an ear
  71888. // now make sure we don't have other points inside the potential ear
  71889. var p = ear.next.next;
  71890. while (p !== ear.prev) {
  71891. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71892. area(p.prev, p, p.next) >= 0)
  71893. return false;
  71894. p = p.next;
  71895. }
  71896. return true;
  71897. }
  71898. function isEarHashed(ear, minX, minY, size) {
  71899. var a = ear.prev, b = ear, c = ear.next;
  71900. if (area(a, b, c) >= 0)
  71901. return false; // reflex, can't be an ear
  71902. // triangle bbox; min & max are calculated like this for speed
  71903. 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);
  71904. // z-order range for the current triangle bbox;
  71905. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  71906. // first look for points inside the triangle in increasing z-order
  71907. var p = ear.nextZ;
  71908. while (p && p.z <= maxZ) {
  71909. if (p !== ear.prev &&
  71910. p !== ear.next &&
  71911. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71912. area(p.prev, p, p.next) >= 0)
  71913. return false;
  71914. p = p.nextZ;
  71915. }
  71916. // then look for points in decreasing z-order
  71917. p = ear.prevZ;
  71918. while (p && p.z >= minZ) {
  71919. if (p !== ear.prev &&
  71920. p !== ear.next &&
  71921. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  71922. area(p.prev, p, p.next) >= 0)
  71923. return false;
  71924. p = p.prevZ;
  71925. }
  71926. return true;
  71927. }
  71928. // go through all polygon nodes and cure small local self-intersections
  71929. function cureLocalIntersections(start, triangles, dim) {
  71930. var p = start;
  71931. do {
  71932. var a = p.prev, b = p.next.next;
  71933. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  71934. triangles.push(a.i / dim);
  71935. triangles.push(p.i / dim);
  71936. triangles.push(b.i / dim);
  71937. // remove two nodes involved
  71938. removeNode(p);
  71939. removeNode(p.next);
  71940. p = start = b;
  71941. }
  71942. p = p.next;
  71943. } while (p !== start);
  71944. return p;
  71945. }
  71946. // try splitting polygon into two and triangulate them independently
  71947. function splitEarcut(start, triangles, dim, minX, minY, size) {
  71948. // look for a valid diagonal that divides the polygon into two
  71949. var a = start;
  71950. do {
  71951. var b = a.next.next;
  71952. while (b !== a.prev) {
  71953. if (a.i !== b.i && isValidDiagonal(a, b)) {
  71954. // split the polygon in two by the diagonal
  71955. var c = splitPolygon(a, b);
  71956. // filter colinear points around the cuts
  71957. a = filterPoints(a, a.next);
  71958. c = filterPoints(c, c.next);
  71959. // run earcut on each half
  71960. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  71961. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  71962. return;
  71963. }
  71964. b = b.next;
  71965. }
  71966. a = a.next;
  71967. } while (a !== start);
  71968. }
  71969. // link every hole into the outer loop, producing a single-ring polygon without holes
  71970. function eliminateHoles(data, holeIndices, outerNode, dim) {
  71971. var queue = [], i, len, start, end, list;
  71972. for (i = 0, len = holeIndices.length; i < len; i++) {
  71973. start = holeIndices[i] * dim;
  71974. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  71975. list = linkedList(data, start, end, dim, false);
  71976. if (list === list.next)
  71977. list.steiner = true;
  71978. queue.push(getLeftmost(list));
  71979. }
  71980. queue.sort(compareX);
  71981. // process holes from left to right
  71982. for (i = 0; i < queue.length; i++) {
  71983. eliminateHole(queue[i], outerNode);
  71984. outerNode = filterPoints(outerNode, outerNode.next);
  71985. }
  71986. return outerNode;
  71987. }
  71988. function compareX(a, b) {
  71989. return a.x - b.x;
  71990. }
  71991. // find a bridge between vertices that connects hole with an outer ring and and link it
  71992. function eliminateHole(hole, outerNode) {
  71993. outerNode = findHoleBridge(hole, outerNode);
  71994. if (outerNode) {
  71995. var b = splitPolygon(outerNode, hole);
  71996. filterPoints(b, b.next);
  71997. }
  71998. }
  71999. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  72000. function findHoleBridge(hole, outerNode) {
  72001. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  72002. // find a segment intersected by a ray from the hole's leftmost point to the left;
  72003. // segment's endpoint with lesser x will be potential connection point
  72004. do {
  72005. if (hy <= p.y && hy >= p.next.y) {
  72006. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  72007. if (x <= hx && x > qx) {
  72008. qx = x;
  72009. if (x === hx) {
  72010. if (hy === p.y)
  72011. return p;
  72012. if (hy === p.next.y)
  72013. return p.next;
  72014. }
  72015. m = p.x < p.next.x ? p : p.next;
  72016. }
  72017. }
  72018. p = p.next;
  72019. } while (p !== outerNode);
  72020. if (!m)
  72021. return null;
  72022. if (hx === qx)
  72023. return m.prev; // hole touches outer segment; pick lower endpoint
  72024. // look for points inside the triangle of hole point, segment intersection and endpoint;
  72025. // if there are no points found, we have a valid connection;
  72026. // otherwise choose the point of the minimum angle with the ray as connection point
  72027. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  72028. p = m.next;
  72029. while (p !== stop) {
  72030. if (hx >= p.x &&
  72031. p.x >= mx &&
  72032. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  72033. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  72034. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  72035. m = p;
  72036. tanMin = tan;
  72037. }
  72038. }
  72039. p = p.next;
  72040. }
  72041. return m;
  72042. }
  72043. // interlink polygon nodes in z-order
  72044. function indexCurve(start, minX, minY, size) {
  72045. var p = start;
  72046. do {
  72047. if (p.z === null)
  72048. p.z = zOrder(p.x, p.y, minX, minY, size);
  72049. p.prevZ = p.prev;
  72050. p.nextZ = p.next;
  72051. p = p.next;
  72052. } while (p !== start);
  72053. p.prevZ.nextZ = null;
  72054. p.prevZ = null;
  72055. sortLinked(p);
  72056. }
  72057. // Simon Tatham's linked list merge sort algorithm
  72058. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  72059. function sortLinked(list) {
  72060. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  72061. do {
  72062. p = list;
  72063. list = null;
  72064. tail = null;
  72065. numMerges = 0;
  72066. while (p) {
  72067. numMerges++;
  72068. q = p;
  72069. pSize = 0;
  72070. for (i = 0; i < inSize; i++) {
  72071. pSize++;
  72072. q = q.nextZ;
  72073. if (!q)
  72074. break;
  72075. }
  72076. qSize = inSize;
  72077. while (pSize > 0 || (qSize > 0 && q)) {
  72078. if (pSize === 0) {
  72079. e = q;
  72080. q = q.nextZ;
  72081. qSize--;
  72082. }
  72083. else if (qSize === 0 || !q) {
  72084. e = p;
  72085. p = p.nextZ;
  72086. pSize--;
  72087. }
  72088. else if (p.z <= q.z) {
  72089. e = p;
  72090. p = p.nextZ;
  72091. pSize--;
  72092. }
  72093. else {
  72094. e = q;
  72095. q = q.nextZ;
  72096. qSize--;
  72097. }
  72098. if (tail)
  72099. tail.nextZ = e;
  72100. else
  72101. list = e;
  72102. e.prevZ = tail;
  72103. tail = e;
  72104. }
  72105. p = q;
  72106. }
  72107. tail.nextZ = null;
  72108. inSize *= 2;
  72109. } while (numMerges > 1);
  72110. return list;
  72111. }
  72112. // z-order of a point given coords and size of the data bounding box
  72113. function zOrder(x, y, minX, minY, size) {
  72114. // coords are transformed into non-negative 15-bit integer range
  72115. x = 32767 * (x - minX) / size;
  72116. y = 32767 * (y - minY) / size;
  72117. x = (x | (x << 8)) & 0x00FF00FF;
  72118. x = (x | (x << 4)) & 0x0F0F0F0F;
  72119. x = (x | (x << 2)) & 0x33333333;
  72120. x = (x | (x << 1)) & 0x55555555;
  72121. y = (y | (y << 8)) & 0x00FF00FF;
  72122. y = (y | (y << 4)) & 0x0F0F0F0F;
  72123. y = (y | (y << 2)) & 0x33333333;
  72124. y = (y | (y << 1)) & 0x55555555;
  72125. return x | (y << 1);
  72126. }
  72127. // find the leftmost node of a polygon ring
  72128. function getLeftmost(start) {
  72129. var p = start, leftmost = start;
  72130. do {
  72131. if (p.x < leftmost.x)
  72132. leftmost = p;
  72133. p = p.next;
  72134. } while (p !== start);
  72135. return leftmost;
  72136. }
  72137. // check if a point lies within a convex triangle
  72138. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  72139. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  72140. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  72141. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  72142. }
  72143. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  72144. function isValidDiagonal(a, b) {
  72145. return a.next.i !== b.i &&
  72146. a.prev.i !== b.i &&
  72147. !intersectsPolygon(a, b) &&
  72148. locallyInside(a, b) &&
  72149. locallyInside(b, a) &&
  72150. middleInside(a, b);
  72151. }
  72152. // signed area of a triangle
  72153. function area(p, q, r) {
  72154. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  72155. }
  72156. // check if two points are equal
  72157. function equals(p1, p2) {
  72158. return p1.x === p2.x && p1.y === p2.y;
  72159. }
  72160. // check if two segments intersect
  72161. function intersects(p1, q1, p2, q2) {
  72162. if ((equals(p1, q1) && equals(p2, q2)) ||
  72163. (equals(p1, q2) && equals(p2, q1)))
  72164. return true;
  72165. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  72166. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  72167. }
  72168. // check if a polygon diagonal intersects any polygon segments
  72169. function intersectsPolygon(a, b) {
  72170. var p = a;
  72171. do {
  72172. if (p.i !== a.i &&
  72173. p.next.i !== a.i &&
  72174. p.i !== b.i &&
  72175. p.next.i !== b.i &&
  72176. intersects(p, p.next, a, b))
  72177. return true;
  72178. p = p.next;
  72179. } while (p !== a);
  72180. return false;
  72181. }
  72182. // check if a polygon diagonal is locally inside the polygon
  72183. function locallyInside(a, b) {
  72184. return area(a.prev, a, a.next) < 0
  72185. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  72186. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  72187. }
  72188. // check if the middle point of a polygon diagonal is inside the polygon
  72189. function middleInside(a, b) {
  72190. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  72191. do {
  72192. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  72193. inside = !inside;
  72194. p = p.next;
  72195. } while (p !== a);
  72196. return inside;
  72197. }
  72198. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  72199. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  72200. function splitPolygon(a, b) {
  72201. 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;
  72202. a.next = b;
  72203. b.prev = a;
  72204. a2.next = an;
  72205. an.prev = a2;
  72206. b2.next = a2;
  72207. a2.prev = b2;
  72208. bp.next = b2;
  72209. b2.prev = bp;
  72210. return b2;
  72211. }
  72212. // create a node and optionally link it with previous one (in a circular doubly linked list)
  72213. function insertNode(i, x, y, last) {
  72214. var p = new Node(i, x, y);
  72215. if (!last) {
  72216. p.prev = p;
  72217. p.next = p;
  72218. }
  72219. else {
  72220. p.next = last.next;
  72221. p.prev = last;
  72222. last.next.prev = p;
  72223. last.next = p;
  72224. }
  72225. return p;
  72226. }
  72227. function removeNode(p) {
  72228. p.next.prev = p.prev;
  72229. p.prev.next = p.next;
  72230. if (p.prevZ)
  72231. p.prevZ.nextZ = p.nextZ;
  72232. if (p.nextZ)
  72233. p.nextZ.prevZ = p.prevZ;
  72234. }
  72235. /**
  72236. * return a percentage difference between the polygon area and its triangulation area;
  72237. * used to verify correctness of triangulation
  72238. */
  72239. function deviation(data, holeIndices, dim, triangles) {
  72240. var hasHoles = holeIndices && holeIndices.length;
  72241. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  72242. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  72243. if (hasHoles) {
  72244. for (var i = 0, len = holeIndices.length; i < len; i++) {
  72245. var start = holeIndices[i] * dim;
  72246. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72247. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  72248. }
  72249. }
  72250. var trianglesArea = 0;
  72251. for (i = 0; i < triangles.length; i += 3) {
  72252. var a = triangles[i] * dim;
  72253. var b = triangles[i + 1] * dim;
  72254. var c = triangles[i + 2] * dim;
  72255. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  72256. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  72257. }
  72258. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  72259. }
  72260. Earcut.deviation = deviation;
  72261. ;
  72262. function signedArea(data, start, end, dim) {
  72263. var sum = 0;
  72264. for (var i = start, j = end - dim; i < end; i += dim) {
  72265. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  72266. j = i;
  72267. }
  72268. return sum;
  72269. }
  72270. /**
  72271. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  72272. */
  72273. function flatten(data) {
  72274. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  72275. for (var i = 0; i < data.length; i++) {
  72276. for (var j = 0; j < data[i].length; j++) {
  72277. for (var d = 0; d < dim; d++)
  72278. result.vertices.push(data[i][j][d]);
  72279. }
  72280. if (i > 0) {
  72281. holeIndex += data[i - 1].length;
  72282. result.holes.push(holeIndex);
  72283. }
  72284. }
  72285. return result;
  72286. }
  72287. Earcut.flatten = flatten;
  72288. ;
  72289. })(Earcut || (Earcut = {}));
  72290. //# sourceMappingURL=babylon.earcut.js.map
  72291. var BABYLON;
  72292. (function (BABYLON) {
  72293. var IndexedVector2 = /** @class */ (function (_super) {
  72294. __extends(IndexedVector2, _super);
  72295. function IndexedVector2(original, index) {
  72296. var _this = _super.call(this, original.x, original.y) || this;
  72297. _this.index = index;
  72298. return _this;
  72299. }
  72300. return IndexedVector2;
  72301. }(BABYLON.Vector2));
  72302. var PolygonPoints = /** @class */ (function () {
  72303. function PolygonPoints() {
  72304. this.elements = new Array();
  72305. }
  72306. PolygonPoints.prototype.add = function (originalPoints) {
  72307. var _this = this;
  72308. var result = new Array();
  72309. originalPoints.forEach(function (point) {
  72310. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  72311. var newPoint = new IndexedVector2(point, _this.elements.length);
  72312. result.push(newPoint);
  72313. _this.elements.push(newPoint);
  72314. }
  72315. });
  72316. return result;
  72317. };
  72318. PolygonPoints.prototype.computeBounds = function () {
  72319. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72320. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72321. this.elements.forEach(function (point) {
  72322. // x
  72323. if (point.x < lmin.x) {
  72324. lmin.x = point.x;
  72325. }
  72326. else if (point.x > lmax.x) {
  72327. lmax.x = point.x;
  72328. }
  72329. // y
  72330. if (point.y < lmin.y) {
  72331. lmin.y = point.y;
  72332. }
  72333. else if (point.y > lmax.y) {
  72334. lmax.y = point.y;
  72335. }
  72336. });
  72337. return {
  72338. min: lmin,
  72339. max: lmax,
  72340. width: lmax.x - lmin.x,
  72341. height: lmax.y - lmin.y
  72342. };
  72343. };
  72344. return PolygonPoints;
  72345. }());
  72346. var Polygon = /** @class */ (function () {
  72347. function Polygon() {
  72348. }
  72349. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72350. return [
  72351. new BABYLON.Vector2(xmin, ymin),
  72352. new BABYLON.Vector2(xmax, ymin),
  72353. new BABYLON.Vector2(xmax, ymax),
  72354. new BABYLON.Vector2(xmin, ymax)
  72355. ];
  72356. };
  72357. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72358. if (cx === void 0) { cx = 0; }
  72359. if (cy === void 0) { cy = 0; }
  72360. if (numberOfSides === void 0) { numberOfSides = 32; }
  72361. var result = new Array();
  72362. var angle = 0;
  72363. var increment = (Math.PI * 2) / numberOfSides;
  72364. for (var i = 0; i < numberOfSides; i++) {
  72365. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72366. angle -= increment;
  72367. }
  72368. return result;
  72369. };
  72370. Polygon.Parse = function (input) {
  72371. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72372. var i, result = [];
  72373. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72374. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72375. }
  72376. return result;
  72377. };
  72378. Polygon.StartingAt = function (x, y) {
  72379. return BABYLON.Path2.StartingAt(x, y);
  72380. };
  72381. return Polygon;
  72382. }());
  72383. BABYLON.Polygon = Polygon;
  72384. var PolygonMeshBuilder = /** @class */ (function () {
  72385. function PolygonMeshBuilder(name, contours, scene) {
  72386. this._points = new PolygonPoints();
  72387. this._outlinepoints = new PolygonPoints();
  72388. this._holes = new Array();
  72389. this._epoints = new Array();
  72390. this._eholes = new Array();
  72391. this._name = name;
  72392. this._scene = scene;
  72393. var points;
  72394. if (contours instanceof BABYLON.Path2) {
  72395. points = contours.getPoints();
  72396. }
  72397. else {
  72398. points = contours;
  72399. }
  72400. this._addToepoint(points);
  72401. this._points.add(points);
  72402. this._outlinepoints.add(points);
  72403. }
  72404. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72405. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72406. var p = points_1[_i];
  72407. this._epoints.push(p.x, p.y);
  72408. }
  72409. };
  72410. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72411. this._points.add(hole);
  72412. var holepoints = new PolygonPoints();
  72413. holepoints.add(hole);
  72414. this._holes.push(holepoints);
  72415. this._eholes.push(this._epoints.length / 2);
  72416. this._addToepoint(hole);
  72417. return this;
  72418. };
  72419. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72420. var _this = this;
  72421. if (updatable === void 0) { updatable = false; }
  72422. if (depth === void 0) { depth = 0; }
  72423. var result = new BABYLON.Mesh(this._name, this._scene);
  72424. var normals = new Array();
  72425. var positions = new Array();
  72426. var uvs = new Array();
  72427. var bounds = this._points.computeBounds();
  72428. this._points.elements.forEach(function (p) {
  72429. normals.push(0, 1.0, 0);
  72430. positions.push(p.x, 0, p.y);
  72431. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72432. });
  72433. var indices = new Array();
  72434. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72435. for (var i = 0; i < res.length; i++) {
  72436. indices.push(res[i]);
  72437. }
  72438. if (depth > 0) {
  72439. var positionscount = (positions.length / 3); //get the current pointcount
  72440. this._points.elements.forEach(function (p) {
  72441. normals.push(0, -1.0, 0);
  72442. positions.push(p.x, -depth, p.y);
  72443. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72444. });
  72445. var totalCount = indices.length;
  72446. for (var i = 0; i < totalCount; i += 3) {
  72447. var i0 = indices[i + 0];
  72448. var i1 = indices[i + 1];
  72449. var i2 = indices[i + 2];
  72450. indices.push(i2 + positionscount);
  72451. indices.push(i1 + positionscount);
  72452. indices.push(i0 + positionscount);
  72453. }
  72454. //Add the sides
  72455. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72456. this._holes.forEach(function (hole) {
  72457. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72458. });
  72459. }
  72460. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72461. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72462. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72463. result.setIndices(indices);
  72464. return result;
  72465. };
  72466. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72467. var StartIndex = positions.length / 3;
  72468. var ulength = 0;
  72469. for (var i = 0; i < points.elements.length; i++) {
  72470. var p = points.elements[i];
  72471. var p1;
  72472. if ((i + 1) > points.elements.length - 1) {
  72473. p1 = points.elements[0];
  72474. }
  72475. else {
  72476. p1 = points.elements[i + 1];
  72477. }
  72478. positions.push(p.x, 0, p.y);
  72479. positions.push(p.x, -depth, p.y);
  72480. positions.push(p1.x, 0, p1.y);
  72481. positions.push(p1.x, -depth, p1.y);
  72482. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72483. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72484. var v3 = v2.subtract(v1);
  72485. var v4 = new BABYLON.Vector3(0, 1, 0);
  72486. var vn = BABYLON.Vector3.Cross(v3, v4);
  72487. vn = vn.normalize();
  72488. uvs.push(ulength / bounds.width, 0);
  72489. uvs.push(ulength / bounds.width, 1);
  72490. ulength += v3.length();
  72491. uvs.push((ulength / bounds.width), 0);
  72492. uvs.push((ulength / bounds.width), 1);
  72493. if (!flip) {
  72494. normals.push(-vn.x, -vn.y, -vn.z);
  72495. normals.push(-vn.x, -vn.y, -vn.z);
  72496. normals.push(-vn.x, -vn.y, -vn.z);
  72497. normals.push(-vn.x, -vn.y, -vn.z);
  72498. indices.push(StartIndex);
  72499. indices.push(StartIndex + 1);
  72500. indices.push(StartIndex + 2);
  72501. indices.push(StartIndex + 1);
  72502. indices.push(StartIndex + 3);
  72503. indices.push(StartIndex + 2);
  72504. }
  72505. else {
  72506. normals.push(vn.x, vn.y, vn.z);
  72507. normals.push(vn.x, vn.y, vn.z);
  72508. normals.push(vn.x, vn.y, vn.z);
  72509. normals.push(vn.x, vn.y, vn.z);
  72510. indices.push(StartIndex);
  72511. indices.push(StartIndex + 2);
  72512. indices.push(StartIndex + 1);
  72513. indices.push(StartIndex + 1);
  72514. indices.push(StartIndex + 2);
  72515. indices.push(StartIndex + 3);
  72516. }
  72517. StartIndex += 4;
  72518. }
  72519. ;
  72520. };
  72521. return PolygonMeshBuilder;
  72522. }());
  72523. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72524. })(BABYLON || (BABYLON = {}));
  72525. //# sourceMappingURL=babylon.polygonMesh.js.map
  72526. var BABYLON;
  72527. (function (BABYLON) {
  72528. // Unique ID when we import meshes from Babylon to CSG
  72529. var currentCSGMeshId = 0;
  72530. // # class Vertex
  72531. // Represents a vertex of a polygon. Use your own vertex class instead of this
  72532. // one to provide additional features like texture coordinates and vertex
  72533. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  72534. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  72535. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  72536. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  72537. // is not used anywhere else.
  72538. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  72539. var Vertex = /** @class */ (function () {
  72540. function Vertex(pos, normal, uv) {
  72541. this.pos = pos;
  72542. this.normal = normal;
  72543. this.uv = uv;
  72544. }
  72545. Vertex.prototype.clone = function () {
  72546. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  72547. };
  72548. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  72549. // orientation of a polygon is flipped.
  72550. Vertex.prototype.flip = function () {
  72551. this.normal = this.normal.scale(-1);
  72552. };
  72553. // Create a new vertex between this vertex and `other` by linearly
  72554. // interpolating all properties using a parameter of `t`. Subclasses should
  72555. // override this to interpolate additional properties.
  72556. Vertex.prototype.interpolate = function (other, t) {
  72557. 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));
  72558. };
  72559. return Vertex;
  72560. }());
  72561. // # class Plane
  72562. // Represents a plane in 3D space.
  72563. var Plane = /** @class */ (function () {
  72564. function Plane(normal, w) {
  72565. this.normal = normal;
  72566. this.w = w;
  72567. }
  72568. Plane.FromPoints = function (a, b, c) {
  72569. var v0 = c.subtract(a);
  72570. var v1 = b.subtract(a);
  72571. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  72572. return null;
  72573. }
  72574. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  72575. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  72576. };
  72577. Plane.prototype.clone = function () {
  72578. return new Plane(this.normal.clone(), this.w);
  72579. };
  72580. Plane.prototype.flip = function () {
  72581. this.normal.scaleInPlace(-1);
  72582. this.w = -this.w;
  72583. };
  72584. // Split `polygon` by this plane if needed, then put the polygon or polygon
  72585. // fragments in the appropriate lists. Coplanar polygons go into either
  72586. // `coplanarFront` or `coplanarBack` depending on their orientation with
  72587. // respect to this plane. Polygons in front or in back of this plane go into
  72588. // either `front` or `back`.
  72589. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  72590. var COPLANAR = 0;
  72591. var FRONT = 1;
  72592. var BACK = 2;
  72593. var SPANNING = 3;
  72594. // Classify each point as well as the entire polygon into one of the above
  72595. // four classes.
  72596. var polygonType = 0;
  72597. var types = [];
  72598. var i;
  72599. var t;
  72600. for (i = 0; i < polygon.vertices.length; i++) {
  72601. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  72602. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  72603. polygonType |= type;
  72604. types.push(type);
  72605. }
  72606. // Put the polygon in the correct list, splitting it when necessary.
  72607. switch (polygonType) {
  72608. case COPLANAR:
  72609. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  72610. break;
  72611. case FRONT:
  72612. front.push(polygon);
  72613. break;
  72614. case BACK:
  72615. back.push(polygon);
  72616. break;
  72617. case SPANNING:
  72618. var f = [], b = [];
  72619. for (i = 0; i < polygon.vertices.length; i++) {
  72620. var j = (i + 1) % polygon.vertices.length;
  72621. var ti = types[i], tj = types[j];
  72622. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  72623. if (ti !== BACK)
  72624. f.push(vi);
  72625. if (ti !== FRONT)
  72626. b.push(ti !== BACK ? vi.clone() : vi);
  72627. if ((ti | tj) === SPANNING) {
  72628. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  72629. var v = vi.interpolate(vj, t);
  72630. f.push(v);
  72631. b.push(v.clone());
  72632. }
  72633. }
  72634. var poly;
  72635. if (f.length >= 3) {
  72636. poly = new Polygon(f, polygon.shared);
  72637. if (poly.plane)
  72638. front.push(poly);
  72639. }
  72640. if (b.length >= 3) {
  72641. poly = new Polygon(b, polygon.shared);
  72642. if (poly.plane)
  72643. back.push(poly);
  72644. }
  72645. break;
  72646. }
  72647. };
  72648. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  72649. // point is on the plane.
  72650. Plane.EPSILON = 1e-5;
  72651. return Plane;
  72652. }());
  72653. // # class Polygon
  72654. // Represents a convex polygon. The vertices used to initialize a polygon must
  72655. // be coplanar and form a convex loop.
  72656. //
  72657. // Each convex polygon has a `shared` property, which is shared between all
  72658. // polygons that are clones of each other or were split from the same polygon.
  72659. // This can be used to define per-polygon properties (such as surface color).
  72660. var Polygon = /** @class */ (function () {
  72661. function Polygon(vertices, shared) {
  72662. this.vertices = vertices;
  72663. this.shared = shared;
  72664. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  72665. }
  72666. Polygon.prototype.clone = function () {
  72667. var vertices = this.vertices.map(function (v) { return v.clone(); });
  72668. return new Polygon(vertices, this.shared);
  72669. };
  72670. Polygon.prototype.flip = function () {
  72671. this.vertices.reverse().map(function (v) { v.flip(); });
  72672. this.plane.flip();
  72673. };
  72674. return Polygon;
  72675. }());
  72676. // # class Node
  72677. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  72678. // by picking a polygon to split along. That polygon (and all other coplanar
  72679. // polygons) are added directly to that node and the other polygons are added to
  72680. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  72681. // no distinction between internal and leaf nodes.
  72682. var Node = /** @class */ (function () {
  72683. function Node(polygons) {
  72684. this.plane = null;
  72685. this.front = null;
  72686. this.back = null;
  72687. this.polygons = new Array();
  72688. if (polygons) {
  72689. this.build(polygons);
  72690. }
  72691. }
  72692. Node.prototype.clone = function () {
  72693. var node = new Node();
  72694. node.plane = this.plane && this.plane.clone();
  72695. node.front = this.front && this.front.clone();
  72696. node.back = this.back && this.back.clone();
  72697. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  72698. return node;
  72699. };
  72700. // Convert solid space to empty space and empty space to solid space.
  72701. Node.prototype.invert = function () {
  72702. for (var i = 0; i < this.polygons.length; i++) {
  72703. this.polygons[i].flip();
  72704. }
  72705. if (this.plane) {
  72706. this.plane.flip();
  72707. }
  72708. if (this.front) {
  72709. this.front.invert();
  72710. }
  72711. if (this.back) {
  72712. this.back.invert();
  72713. }
  72714. var temp = this.front;
  72715. this.front = this.back;
  72716. this.back = temp;
  72717. };
  72718. // Recursively remove all polygons in `polygons` that are inside this BSP
  72719. // tree.
  72720. Node.prototype.clipPolygons = function (polygons) {
  72721. if (!this.plane)
  72722. return polygons.slice();
  72723. var front = new Array(), back = new Array();
  72724. for (var i = 0; i < polygons.length; i++) {
  72725. this.plane.splitPolygon(polygons[i], front, back, front, back);
  72726. }
  72727. if (this.front) {
  72728. front = this.front.clipPolygons(front);
  72729. }
  72730. if (this.back) {
  72731. back = this.back.clipPolygons(back);
  72732. }
  72733. else {
  72734. back = [];
  72735. }
  72736. return front.concat(back);
  72737. };
  72738. // Remove all polygons in this BSP tree that are inside the other BSP tree
  72739. // `bsp`.
  72740. Node.prototype.clipTo = function (bsp) {
  72741. this.polygons = bsp.clipPolygons(this.polygons);
  72742. if (this.front)
  72743. this.front.clipTo(bsp);
  72744. if (this.back)
  72745. this.back.clipTo(bsp);
  72746. };
  72747. // Return a list of all polygons in this BSP tree.
  72748. Node.prototype.allPolygons = function () {
  72749. var polygons = this.polygons.slice();
  72750. if (this.front)
  72751. polygons = polygons.concat(this.front.allPolygons());
  72752. if (this.back)
  72753. polygons = polygons.concat(this.back.allPolygons());
  72754. return polygons;
  72755. };
  72756. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  72757. // new polygons are filtered down to the bottom of the tree and become new
  72758. // nodes there. Each set of polygons is partitioned using the first polygon
  72759. // (no heuristic is used to pick a good split).
  72760. Node.prototype.build = function (polygons) {
  72761. if (!polygons.length)
  72762. return;
  72763. if (!this.plane)
  72764. this.plane = polygons[0].plane.clone();
  72765. var front = new Array(), back = new Array();
  72766. for (var i = 0; i < polygons.length; i++) {
  72767. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  72768. }
  72769. if (front.length) {
  72770. if (!this.front)
  72771. this.front = new Node();
  72772. this.front.build(front);
  72773. }
  72774. if (back.length) {
  72775. if (!this.back)
  72776. this.back = new Node();
  72777. this.back.build(back);
  72778. }
  72779. };
  72780. return Node;
  72781. }());
  72782. var CSG = /** @class */ (function () {
  72783. function CSG() {
  72784. this.polygons = new Array();
  72785. }
  72786. // Convert BABYLON.Mesh to BABYLON.CSG
  72787. CSG.FromMesh = function (mesh) {
  72788. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  72789. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  72790. if (mesh instanceof BABYLON.Mesh) {
  72791. mesh.computeWorldMatrix(true);
  72792. matrix = mesh.getWorldMatrix();
  72793. meshPosition = mesh.position.clone();
  72794. meshRotation = mesh.rotation.clone();
  72795. if (mesh.rotationQuaternion) {
  72796. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  72797. }
  72798. meshScaling = mesh.scaling.clone();
  72799. }
  72800. else {
  72801. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  72802. }
  72803. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  72804. var subMeshes = mesh.subMeshes;
  72805. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  72806. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  72807. vertices = [];
  72808. for (var j = 0; j < 3; j++) {
  72809. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  72810. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  72811. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  72812. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  72813. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  72814. vertex = new Vertex(position, normal, uv);
  72815. vertices.push(vertex);
  72816. }
  72817. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  72818. // To handle the case of degenerated triangle
  72819. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  72820. if (polygon.plane)
  72821. polygons.push(polygon);
  72822. }
  72823. }
  72824. var csg = CSG.FromPolygons(polygons);
  72825. csg.matrix = matrix;
  72826. csg.position = meshPosition;
  72827. csg.rotation = meshRotation;
  72828. csg.scaling = meshScaling;
  72829. csg.rotationQuaternion = meshRotationQuaternion;
  72830. currentCSGMeshId++;
  72831. return csg;
  72832. };
  72833. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  72834. CSG.FromPolygons = function (polygons) {
  72835. var csg = new CSG();
  72836. csg.polygons = polygons;
  72837. return csg;
  72838. };
  72839. CSG.prototype.clone = function () {
  72840. var csg = new CSG();
  72841. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  72842. csg.copyTransformAttributes(this);
  72843. return csg;
  72844. };
  72845. CSG.prototype.union = function (csg) {
  72846. var a = new Node(this.clone().polygons);
  72847. var b = new Node(csg.clone().polygons);
  72848. a.clipTo(b);
  72849. b.clipTo(a);
  72850. b.invert();
  72851. b.clipTo(a);
  72852. b.invert();
  72853. a.build(b.allPolygons());
  72854. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72855. };
  72856. CSG.prototype.unionInPlace = function (csg) {
  72857. var a = new Node(this.polygons);
  72858. var b = new Node(csg.polygons);
  72859. a.clipTo(b);
  72860. b.clipTo(a);
  72861. b.invert();
  72862. b.clipTo(a);
  72863. b.invert();
  72864. a.build(b.allPolygons());
  72865. this.polygons = a.allPolygons();
  72866. };
  72867. CSG.prototype.subtract = function (csg) {
  72868. var a = new Node(this.clone().polygons);
  72869. var b = new Node(csg.clone().polygons);
  72870. a.invert();
  72871. a.clipTo(b);
  72872. b.clipTo(a);
  72873. b.invert();
  72874. b.clipTo(a);
  72875. b.invert();
  72876. a.build(b.allPolygons());
  72877. a.invert();
  72878. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72879. };
  72880. CSG.prototype.subtractInPlace = function (csg) {
  72881. var a = new Node(this.polygons);
  72882. var b = new Node(csg.polygons);
  72883. a.invert();
  72884. a.clipTo(b);
  72885. b.clipTo(a);
  72886. b.invert();
  72887. b.clipTo(a);
  72888. b.invert();
  72889. a.build(b.allPolygons());
  72890. a.invert();
  72891. this.polygons = a.allPolygons();
  72892. };
  72893. CSG.prototype.intersect = function (csg) {
  72894. var a = new Node(this.clone().polygons);
  72895. var b = new Node(csg.clone().polygons);
  72896. a.invert();
  72897. b.clipTo(a);
  72898. b.invert();
  72899. a.clipTo(b);
  72900. b.clipTo(a);
  72901. a.build(b.allPolygons());
  72902. a.invert();
  72903. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  72904. };
  72905. CSG.prototype.intersectInPlace = function (csg) {
  72906. var a = new Node(this.polygons);
  72907. var b = new Node(csg.polygons);
  72908. a.invert();
  72909. b.clipTo(a);
  72910. b.invert();
  72911. a.clipTo(b);
  72912. b.clipTo(a);
  72913. a.build(b.allPolygons());
  72914. a.invert();
  72915. this.polygons = a.allPolygons();
  72916. };
  72917. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  72918. // not modified.
  72919. CSG.prototype.inverse = function () {
  72920. var csg = this.clone();
  72921. csg.inverseInPlace();
  72922. return csg;
  72923. };
  72924. CSG.prototype.inverseInPlace = function () {
  72925. this.polygons.map(function (p) { p.flip(); });
  72926. };
  72927. // This is used to keep meshes transformations so they can be restored
  72928. // when we build back a Babylon Mesh
  72929. // NB : All CSG operations are performed in world coordinates
  72930. CSG.prototype.copyTransformAttributes = function (csg) {
  72931. this.matrix = csg.matrix;
  72932. this.position = csg.position;
  72933. this.rotation = csg.rotation;
  72934. this.scaling = csg.scaling;
  72935. this.rotationQuaternion = csg.rotationQuaternion;
  72936. return this;
  72937. };
  72938. // Build Raw mesh from CSG
  72939. // Coordinates here are in world space
  72940. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  72941. var matrix = this.matrix.clone();
  72942. matrix.invert();
  72943. 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;
  72944. if (keepSubMeshes) {
  72945. // Sort Polygons, since subMeshes are indices range
  72946. polygons.sort(function (a, b) {
  72947. if (a.shared.meshId === b.shared.meshId) {
  72948. return a.shared.subMeshId - b.shared.subMeshId;
  72949. }
  72950. else {
  72951. return a.shared.meshId - b.shared.meshId;
  72952. }
  72953. });
  72954. }
  72955. for (var i = 0, il = polygons.length; i < il; i++) {
  72956. polygon = polygons[i];
  72957. // Building SubMeshes
  72958. if (!subMesh_dict[polygon.shared.meshId]) {
  72959. subMesh_dict[polygon.shared.meshId] = {};
  72960. }
  72961. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  72962. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  72963. indexStart: +Infinity,
  72964. indexEnd: -Infinity,
  72965. materialIndex: polygon.shared.materialIndex
  72966. };
  72967. }
  72968. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  72969. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  72970. polygonIndices[0] = 0;
  72971. polygonIndices[1] = j - 1;
  72972. polygonIndices[2] = j;
  72973. for (var k = 0; k < 3; k++) {
  72974. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  72975. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  72976. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  72977. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  72978. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  72979. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  72980. // Check if 2 points can be merged
  72981. if (!(typeof vertex_idx !== 'undefined' &&
  72982. normals[vertex_idx * 3] === localNormal.x &&
  72983. normals[vertex_idx * 3 + 1] === localNormal.y &&
  72984. normals[vertex_idx * 3 + 2] === localNormal.z &&
  72985. uvs[vertex_idx * 2] === uv.x &&
  72986. uvs[vertex_idx * 2 + 1] === uv.y)) {
  72987. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  72988. uvs.push(uv.x, uv.y);
  72989. normals.push(normal.x, normal.y, normal.z);
  72990. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  72991. }
  72992. indices.push(vertex_idx);
  72993. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  72994. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  72995. currentIndex++;
  72996. }
  72997. }
  72998. }
  72999. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  73000. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  73001. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  73002. mesh.setIndices(indices, null);
  73003. if (keepSubMeshes) {
  73004. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  73005. var materialIndexOffset = 0, materialMaxIndex;
  73006. mesh.subMeshes = new Array();
  73007. for (var m in subMesh_dict) {
  73008. materialMaxIndex = -1;
  73009. for (var sm in subMesh_dict[m]) {
  73010. subMesh_obj = subMesh_dict[m][sm];
  73011. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  73012. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  73013. }
  73014. materialIndexOffset += ++materialMaxIndex;
  73015. }
  73016. }
  73017. return mesh;
  73018. };
  73019. // Build Mesh from CSG taking material and transforms into account
  73020. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  73021. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  73022. mesh.material = material;
  73023. mesh.position.copyFrom(this.position);
  73024. mesh.rotation.copyFrom(this.rotation);
  73025. if (this.rotationQuaternion) {
  73026. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  73027. }
  73028. mesh.scaling.copyFrom(this.scaling);
  73029. mesh.computeWorldMatrix(true);
  73030. return mesh;
  73031. };
  73032. return CSG;
  73033. }());
  73034. BABYLON.CSG = CSG;
  73035. })(BABYLON || (BABYLON = {}));
  73036. //# sourceMappingURL=babylon.csg.js.map
  73037. var BABYLON;
  73038. (function (BABYLON) {
  73039. var LensFlare = /** @class */ (function () {
  73040. function LensFlare(size, position, color, imgUrl, system) {
  73041. this.size = size;
  73042. this.position = position;
  73043. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  73044. this.color = color || new BABYLON.Color3(1, 1, 1);
  73045. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  73046. this._system = system;
  73047. system.lensFlares.push(this);
  73048. }
  73049. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  73050. return new LensFlare(size, position, color, imgUrl, system);
  73051. };
  73052. LensFlare.prototype.dispose = function () {
  73053. if (this.texture) {
  73054. this.texture.dispose();
  73055. }
  73056. // Remove from scene
  73057. var index = this._system.lensFlares.indexOf(this);
  73058. this._system.lensFlares.splice(index, 1);
  73059. };
  73060. ;
  73061. return LensFlare;
  73062. }());
  73063. BABYLON.LensFlare = LensFlare;
  73064. })(BABYLON || (BABYLON = {}));
  73065. //# sourceMappingURL=babylon.lensFlare.js.map
  73066. var BABYLON;
  73067. (function (BABYLON) {
  73068. var LensFlareSystem = /** @class */ (function () {
  73069. function LensFlareSystem(name, emitter, scene) {
  73070. this.name = name;
  73071. this.lensFlares = new Array();
  73072. this.borderLimit = 300;
  73073. this.viewportBorder = 0;
  73074. this.layerMask = 0x0FFFFFFF;
  73075. this._vertexBuffers = {};
  73076. this._isEnabled = true;
  73077. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73078. this._emitter = emitter;
  73079. this.id = name;
  73080. scene.lensFlareSystems.push(this);
  73081. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  73082. var engine = scene.getEngine();
  73083. // VBO
  73084. var vertices = [];
  73085. vertices.push(1, 1);
  73086. vertices.push(-1, 1);
  73087. vertices.push(-1, -1);
  73088. vertices.push(1, -1);
  73089. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73090. // Indices
  73091. var indices = [];
  73092. indices.push(0);
  73093. indices.push(1);
  73094. indices.push(2);
  73095. indices.push(0);
  73096. indices.push(2);
  73097. indices.push(3);
  73098. this._indexBuffer = engine.createIndexBuffer(indices);
  73099. // Effects
  73100. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  73101. }
  73102. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  73103. get: function () {
  73104. return this._isEnabled;
  73105. },
  73106. set: function (value) {
  73107. this._isEnabled = value;
  73108. },
  73109. enumerable: true,
  73110. configurable: true
  73111. });
  73112. LensFlareSystem.prototype.getScene = function () {
  73113. return this._scene;
  73114. };
  73115. LensFlareSystem.prototype.getEmitter = function () {
  73116. return this._emitter;
  73117. };
  73118. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  73119. this._emitter = newEmitter;
  73120. };
  73121. LensFlareSystem.prototype.getEmitterPosition = function () {
  73122. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  73123. };
  73124. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  73125. var position = this.getEmitterPosition();
  73126. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  73127. this._positionX = position.x;
  73128. this._positionY = position.y;
  73129. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  73130. if (this.viewportBorder > 0) {
  73131. globalViewport.x -= this.viewportBorder;
  73132. globalViewport.y -= this.viewportBorder;
  73133. globalViewport.width += this.viewportBorder * 2;
  73134. globalViewport.height += this.viewportBorder * 2;
  73135. position.x += this.viewportBorder;
  73136. position.y += this.viewportBorder;
  73137. this._positionX += this.viewportBorder;
  73138. this._positionY += this.viewportBorder;
  73139. }
  73140. if (position.z > 0) {
  73141. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  73142. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  73143. return true;
  73144. }
  73145. return true;
  73146. }
  73147. return false;
  73148. };
  73149. LensFlareSystem.prototype._isVisible = function () {
  73150. if (!this._isEnabled || !this._scene.activeCamera) {
  73151. return false;
  73152. }
  73153. var emitterPosition = this.getEmitterPosition();
  73154. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  73155. var distance = direction.length();
  73156. direction.normalize();
  73157. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  73158. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  73159. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  73160. };
  73161. LensFlareSystem.prototype.render = function () {
  73162. if (!this._effect.isReady() || !this._scene.activeCamera)
  73163. return false;
  73164. var engine = this._scene.getEngine();
  73165. var viewport = this._scene.activeCamera.viewport;
  73166. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  73167. // Position
  73168. if (!this.computeEffectivePosition(globalViewport)) {
  73169. return false;
  73170. }
  73171. // Visibility
  73172. if (!this._isVisible()) {
  73173. return false;
  73174. }
  73175. // Intensity
  73176. var awayX;
  73177. var awayY;
  73178. if (this._positionX < this.borderLimit + globalViewport.x) {
  73179. awayX = this.borderLimit + globalViewport.x - this._positionX;
  73180. }
  73181. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  73182. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  73183. }
  73184. else {
  73185. awayX = 0;
  73186. }
  73187. if (this._positionY < this.borderLimit + globalViewport.y) {
  73188. awayY = this.borderLimit + globalViewport.y - this._positionY;
  73189. }
  73190. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  73191. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  73192. }
  73193. else {
  73194. awayY = 0;
  73195. }
  73196. var away = (awayX > awayY) ? awayX : awayY;
  73197. away -= this.viewportBorder;
  73198. if (away > this.borderLimit) {
  73199. away = this.borderLimit;
  73200. }
  73201. var intensity = 1.0 - (away / this.borderLimit);
  73202. if (intensity < 0) {
  73203. return false;
  73204. }
  73205. if (intensity > 1.0) {
  73206. intensity = 1.0;
  73207. }
  73208. if (this.viewportBorder > 0) {
  73209. globalViewport.x += this.viewportBorder;
  73210. globalViewport.y += this.viewportBorder;
  73211. globalViewport.width -= this.viewportBorder * 2;
  73212. globalViewport.height -= this.viewportBorder * 2;
  73213. this._positionX -= this.viewportBorder;
  73214. this._positionY -= this.viewportBorder;
  73215. }
  73216. // Position
  73217. var centerX = globalViewport.x + globalViewport.width / 2;
  73218. var centerY = globalViewport.y + globalViewport.height / 2;
  73219. var distX = centerX - this._positionX;
  73220. var distY = centerY - this._positionY;
  73221. // Effects
  73222. engine.enableEffect(this._effect);
  73223. engine.setState(false);
  73224. engine.setDepthBuffer(false);
  73225. // VBOs
  73226. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73227. // Flares
  73228. for (var index = 0; index < this.lensFlares.length; index++) {
  73229. var flare = this.lensFlares[index];
  73230. engine.setAlphaMode(flare.alphaMode);
  73231. var x = centerX - (distX * flare.position);
  73232. var y = centerY - (distY * flare.position);
  73233. var cw = flare.size;
  73234. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  73235. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  73236. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  73237. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  73238. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  73239. // Texture
  73240. this._effect.setTexture("textureSampler", flare.texture);
  73241. // Color
  73242. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  73243. // Draw order
  73244. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73245. }
  73246. engine.setDepthBuffer(true);
  73247. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73248. return true;
  73249. };
  73250. LensFlareSystem.prototype.dispose = function () {
  73251. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73252. if (vertexBuffer) {
  73253. vertexBuffer.dispose();
  73254. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73255. }
  73256. if (this._indexBuffer) {
  73257. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73258. this._indexBuffer = null;
  73259. }
  73260. while (this.lensFlares.length) {
  73261. this.lensFlares[0].dispose();
  73262. }
  73263. // Remove from scene
  73264. var index = this._scene.lensFlareSystems.indexOf(this);
  73265. this._scene.lensFlareSystems.splice(index, 1);
  73266. };
  73267. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  73268. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  73269. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  73270. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  73271. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  73272. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  73273. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  73274. var parsedFlare = parsedLensFlareSystem.flares[index];
  73275. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  73276. }
  73277. return lensFlareSystem;
  73278. };
  73279. LensFlareSystem.prototype.serialize = function () {
  73280. var serializationObject = {};
  73281. serializationObject.id = this.id;
  73282. serializationObject.name = this.name;
  73283. serializationObject.emitterId = this.getEmitter().id;
  73284. serializationObject.borderLimit = this.borderLimit;
  73285. serializationObject.flares = [];
  73286. for (var index = 0; index < this.lensFlares.length; index++) {
  73287. var flare = this.lensFlares[index];
  73288. serializationObject.flares.push({
  73289. size: flare.size,
  73290. position: flare.position,
  73291. color: flare.color.asArray(),
  73292. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  73293. });
  73294. }
  73295. return serializationObject;
  73296. };
  73297. return LensFlareSystem;
  73298. }());
  73299. BABYLON.LensFlareSystem = LensFlareSystem;
  73300. })(BABYLON || (BABYLON = {}));
  73301. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  73302. var BABYLON;
  73303. (function (BABYLON) {
  73304. /**
  73305. * This is a holder class for the physics joint created by the physics plugin.
  73306. * It holds a set of functions to control the underlying joint.
  73307. */
  73308. var PhysicsJoint = /** @class */ (function () {
  73309. function PhysicsJoint(type, jointData) {
  73310. this.type = type;
  73311. this.jointData = jointData;
  73312. jointData.nativeParams = jointData.nativeParams || {};
  73313. }
  73314. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  73315. get: function () {
  73316. return this._physicsJoint;
  73317. },
  73318. set: function (newJoint) {
  73319. if (this._physicsJoint) {
  73320. //remove from the wolrd
  73321. }
  73322. this._physicsJoint = newJoint;
  73323. },
  73324. enumerable: true,
  73325. configurable: true
  73326. });
  73327. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  73328. set: function (physicsPlugin) {
  73329. this._physicsPlugin = physicsPlugin;
  73330. },
  73331. enumerable: true,
  73332. configurable: true
  73333. });
  73334. /**
  73335. * Execute a function that is physics-plugin specific.
  73336. * @param {Function} func the function that will be executed.
  73337. * It accepts two parameters: the physics world and the physics joint.
  73338. */
  73339. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  73340. func(this._physicsPlugin.world, this._physicsJoint);
  73341. };
  73342. //TODO check if the native joints are the same
  73343. //Joint Types
  73344. PhysicsJoint.DistanceJoint = 0;
  73345. PhysicsJoint.HingeJoint = 1;
  73346. PhysicsJoint.BallAndSocketJoint = 2;
  73347. PhysicsJoint.WheelJoint = 3;
  73348. PhysicsJoint.SliderJoint = 4;
  73349. //OIMO
  73350. PhysicsJoint.PrismaticJoint = 5;
  73351. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73352. PhysicsJoint.UniversalJoint = 6;
  73353. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73354. //Cannon
  73355. //Similar to a Ball-Joint. Different in params
  73356. PhysicsJoint.PointToPointJoint = 8;
  73357. //Cannon only at the moment
  73358. PhysicsJoint.SpringJoint = 9;
  73359. PhysicsJoint.LockJoint = 10;
  73360. return PhysicsJoint;
  73361. }());
  73362. BABYLON.PhysicsJoint = PhysicsJoint;
  73363. /**
  73364. * A class representing a physics distance joint.
  73365. */
  73366. var DistanceJoint = /** @class */ (function (_super) {
  73367. __extends(DistanceJoint, _super);
  73368. function DistanceJoint(jointData) {
  73369. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73370. }
  73371. /**
  73372. * Update the predefined distance.
  73373. */
  73374. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73375. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73376. };
  73377. return DistanceJoint;
  73378. }(PhysicsJoint));
  73379. BABYLON.DistanceJoint = DistanceJoint;
  73380. var MotorEnabledJoint = /** @class */ (function (_super) {
  73381. __extends(MotorEnabledJoint, _super);
  73382. function MotorEnabledJoint(type, jointData) {
  73383. return _super.call(this, type, jointData) || this;
  73384. }
  73385. /**
  73386. * Set the motor values.
  73387. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73388. * @param {number} force the force to apply
  73389. * @param {number} maxForce max force for this motor.
  73390. */
  73391. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73392. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73393. };
  73394. /**
  73395. * Set the motor's limits.
  73396. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73397. */
  73398. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73399. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73400. };
  73401. return MotorEnabledJoint;
  73402. }(PhysicsJoint));
  73403. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73404. /**
  73405. * This class represents a single hinge physics joint
  73406. */
  73407. var HingeJoint = /** @class */ (function (_super) {
  73408. __extends(HingeJoint, _super);
  73409. function HingeJoint(jointData) {
  73410. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73411. }
  73412. /**
  73413. * Set the motor values.
  73414. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73415. * @param {number} force the force to apply
  73416. * @param {number} maxForce max force for this motor.
  73417. */
  73418. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73419. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73420. };
  73421. /**
  73422. * Set the motor's limits.
  73423. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73424. */
  73425. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73426. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73427. };
  73428. return HingeJoint;
  73429. }(MotorEnabledJoint));
  73430. BABYLON.HingeJoint = HingeJoint;
  73431. /**
  73432. * This class represents a dual hinge physics joint (same as wheel joint)
  73433. */
  73434. var Hinge2Joint = /** @class */ (function (_super) {
  73435. __extends(Hinge2Joint, _super);
  73436. function Hinge2Joint(jointData) {
  73437. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73438. }
  73439. /**
  73440. * Set the motor values.
  73441. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73442. * @param {number} force the force to apply
  73443. * @param {number} maxForce max force for this motor.
  73444. * @param {motorIndex} the motor's index, 0 or 1.
  73445. */
  73446. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73447. if (motorIndex === void 0) { motorIndex = 0; }
  73448. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73449. };
  73450. /**
  73451. * Set the motor limits.
  73452. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73453. * @param {number} upperLimit the upper limit
  73454. * @param {number} lowerLimit lower limit
  73455. * @param {motorIndex} the motor's index, 0 or 1.
  73456. */
  73457. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73458. if (motorIndex === void 0) { motorIndex = 0; }
  73459. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73460. };
  73461. return Hinge2Joint;
  73462. }(MotorEnabledJoint));
  73463. BABYLON.Hinge2Joint = Hinge2Joint;
  73464. })(BABYLON || (BABYLON = {}));
  73465. //# sourceMappingURL=babylon.physicsJoint.js.map
  73466. var BABYLON;
  73467. (function (BABYLON) {
  73468. var PhysicsImpostor = /** @class */ (function () {
  73469. function PhysicsImpostor(object, type, _options, _scene) {
  73470. if (_options === void 0) { _options = { mass: 0 }; }
  73471. var _this = this;
  73472. this.object = object;
  73473. this.type = type;
  73474. this._options = _options;
  73475. this._scene = _scene;
  73476. this._bodyUpdateRequired = false;
  73477. this._onBeforePhysicsStepCallbacks = new Array();
  73478. this._onAfterPhysicsStepCallbacks = new Array();
  73479. this._onPhysicsCollideCallbacks = [];
  73480. this._deltaPosition = BABYLON.Vector3.Zero();
  73481. this._isDisposed = false;
  73482. //temp variables for parent rotation calculations
  73483. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73484. this._tmpQuat = new BABYLON.Quaternion();
  73485. this._tmpQuat2 = new BABYLON.Quaternion();
  73486. /**
  73487. * this function is executed by the physics engine.
  73488. */
  73489. this.beforeStep = function () {
  73490. if (!_this._physicsEngine) {
  73491. return;
  73492. }
  73493. _this.object.translate(_this._deltaPosition, -1);
  73494. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73495. _this.object.computeWorldMatrix(false);
  73496. if (_this.object.parent && _this.object.rotationQuaternion) {
  73497. _this.getParentsRotation();
  73498. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73499. }
  73500. else {
  73501. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73502. }
  73503. if (!_this._options.disableBidirectionalTransformation) {
  73504. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73505. }
  73506. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73507. func(_this);
  73508. });
  73509. };
  73510. /**
  73511. * this function is executed by the physics engine.
  73512. */
  73513. this.afterStep = function () {
  73514. if (!_this._physicsEngine) {
  73515. return;
  73516. }
  73517. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73518. func(_this);
  73519. });
  73520. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73521. // object has now its world rotation. needs to be converted to local.
  73522. if (_this.object.parent && _this.object.rotationQuaternion) {
  73523. _this.getParentsRotation();
  73524. _this._tmpQuat.conjugateInPlace();
  73525. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73526. }
  73527. // take the position set and make it the absolute position of this object.
  73528. _this.object.setAbsolutePosition(_this.object.position);
  73529. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  73530. _this.object.translate(_this._deltaPosition, 1);
  73531. };
  73532. /**
  73533. * Legacy collision detection event support
  73534. */
  73535. this.onCollideEvent = null;
  73536. //event and body object due to cannon's event-based architecture.
  73537. this.onCollide = function (e) {
  73538. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  73539. return;
  73540. }
  73541. if (!_this._physicsEngine) {
  73542. return;
  73543. }
  73544. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  73545. if (otherImpostor) {
  73546. // Legacy collision detection event support
  73547. if (_this.onCollideEvent) {
  73548. _this.onCollideEvent(_this, otherImpostor);
  73549. }
  73550. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  73551. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  73552. }).forEach(function (obj) {
  73553. obj.callback(_this, otherImpostor);
  73554. });
  73555. }
  73556. };
  73557. //sanity check!
  73558. if (!this.object) {
  73559. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  73560. return;
  73561. }
  73562. //legacy support for old syntax.
  73563. if (!this._scene && object.getScene) {
  73564. this._scene = object.getScene();
  73565. }
  73566. if (!this._scene) {
  73567. return;
  73568. }
  73569. this._physicsEngine = this._scene.getPhysicsEngine();
  73570. if (!this._physicsEngine) {
  73571. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  73572. }
  73573. else {
  73574. //set the object's quaternion, if not set
  73575. if (!this.object.rotationQuaternion) {
  73576. if (this.object.rotation) {
  73577. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  73578. }
  73579. else {
  73580. this.object.rotationQuaternion = new BABYLON.Quaternion();
  73581. }
  73582. }
  73583. //default options params
  73584. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  73585. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  73586. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  73587. this._joints = [];
  73588. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  73589. if (!this.object.parent || this._options.ignoreParent) {
  73590. this._init();
  73591. }
  73592. else if (this.object.parent.physicsImpostor) {
  73593. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  73594. }
  73595. }
  73596. }
  73597. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  73598. get: function () {
  73599. return this._isDisposed;
  73600. },
  73601. enumerable: true,
  73602. configurable: true
  73603. });
  73604. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  73605. get: function () {
  73606. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  73607. },
  73608. set: function (value) {
  73609. this.setMass(value);
  73610. },
  73611. enumerable: true,
  73612. configurable: true
  73613. });
  73614. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  73615. get: function () {
  73616. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  73617. },
  73618. set: function (value) {
  73619. if (!this._physicsEngine) {
  73620. return;
  73621. }
  73622. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  73623. },
  73624. enumerable: true,
  73625. configurable: true
  73626. });
  73627. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  73628. get: function () {
  73629. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  73630. },
  73631. set: function (value) {
  73632. if (!this._physicsEngine) {
  73633. return;
  73634. }
  73635. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  73636. },
  73637. enumerable: true,
  73638. configurable: true
  73639. });
  73640. /**
  73641. * This function will completly initialize this impostor.
  73642. * It will create a new body - but only if this mesh has no parent.
  73643. * If it has, this impostor will not be used other than to define the impostor
  73644. * of the child mesh.
  73645. */
  73646. PhysicsImpostor.prototype._init = function () {
  73647. if (!this._physicsEngine) {
  73648. return;
  73649. }
  73650. this._physicsEngine.removeImpostor(this);
  73651. this.physicsBody = null;
  73652. this._parent = this._parent || this._getPhysicsParent();
  73653. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  73654. this._physicsEngine.addImpostor(this);
  73655. }
  73656. };
  73657. PhysicsImpostor.prototype._getPhysicsParent = function () {
  73658. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  73659. var parentMesh = this.object.parent;
  73660. return parentMesh.physicsImpostor;
  73661. }
  73662. return null;
  73663. };
  73664. /**
  73665. * Should a new body be generated.
  73666. */
  73667. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  73668. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  73669. };
  73670. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  73671. this.forceUpdate();
  73672. };
  73673. /**
  73674. * Force a regeneration of this or the parent's impostor's body.
  73675. * Use under cautious - This will remove all joints already implemented.
  73676. */
  73677. PhysicsImpostor.prototype.forceUpdate = function () {
  73678. this._init();
  73679. if (this.parent && !this._options.ignoreParent) {
  73680. this.parent.forceUpdate();
  73681. }
  73682. };
  73683. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  73684. /*public get mesh(): AbstractMesh {
  73685. return this._mesh;
  73686. }*/
  73687. /**
  73688. * Gets the body that holds this impostor. Either its own, or its parent.
  73689. */
  73690. get: function () {
  73691. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  73692. },
  73693. /**
  73694. * Set the physics body. Used mainly by the physics engine/plugin
  73695. */
  73696. set: function (physicsBody) {
  73697. if (this._physicsBody && this._physicsEngine) {
  73698. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  73699. }
  73700. this._physicsBody = physicsBody;
  73701. this.resetUpdateFlags();
  73702. },
  73703. enumerable: true,
  73704. configurable: true
  73705. });
  73706. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  73707. get: function () {
  73708. return !this._options.ignoreParent && this._parent ? this._parent : null;
  73709. },
  73710. set: function (value) {
  73711. this._parent = value;
  73712. },
  73713. enumerable: true,
  73714. configurable: true
  73715. });
  73716. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  73717. this._bodyUpdateRequired = false;
  73718. };
  73719. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  73720. if (this.object.getBoundingInfo) {
  73721. var q = this.object.rotationQuaternion;
  73722. //reset rotation
  73723. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  73724. //calculate the world matrix with no rotation
  73725. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73726. var boundingInfo = this.object.getBoundingInfo();
  73727. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  73728. //bring back the rotation
  73729. this.object.rotationQuaternion = q;
  73730. //calculate the world matrix with the new rotation
  73731. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  73732. return size;
  73733. }
  73734. else {
  73735. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  73736. }
  73737. };
  73738. PhysicsImpostor.prototype.getObjectCenter = function () {
  73739. if (this.object.getBoundingInfo) {
  73740. var boundingInfo = this.object.getBoundingInfo();
  73741. return boundingInfo.boundingBox.centerWorld;
  73742. }
  73743. else {
  73744. return this.object.position;
  73745. }
  73746. };
  73747. /**
  73748. * Get a specific parametes from the options parameter.
  73749. */
  73750. PhysicsImpostor.prototype.getParam = function (paramName) {
  73751. return this._options[paramName];
  73752. };
  73753. /**
  73754. * Sets a specific parameter in the options given to the physics plugin
  73755. */
  73756. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  73757. this._options[paramName] = value;
  73758. this._bodyUpdateRequired = true;
  73759. };
  73760. /**
  73761. * Specifically change the body's mass option. Won't recreate the physics body object
  73762. */
  73763. PhysicsImpostor.prototype.setMass = function (mass) {
  73764. if (this.getParam("mass") !== mass) {
  73765. this.setParam("mass", mass);
  73766. }
  73767. if (this._physicsEngine) {
  73768. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  73769. }
  73770. };
  73771. PhysicsImpostor.prototype.getLinearVelocity = function () {
  73772. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  73773. };
  73774. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  73775. if (this._physicsEngine) {
  73776. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  73777. }
  73778. };
  73779. PhysicsImpostor.prototype.getAngularVelocity = function () {
  73780. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  73781. };
  73782. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  73783. if (this._physicsEngine) {
  73784. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  73785. }
  73786. };
  73787. /**
  73788. * Execute a function with the physics plugin native code.
  73789. * Provide a function the will have two variables - the world object and the physics body object.
  73790. */
  73791. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  73792. if (this._physicsEngine) {
  73793. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  73794. }
  73795. };
  73796. /**
  73797. * Register a function that will be executed before the physics world is stepping forward.
  73798. */
  73799. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  73800. this._onBeforePhysicsStepCallbacks.push(func);
  73801. };
  73802. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  73803. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  73804. if (index > -1) {
  73805. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  73806. }
  73807. else {
  73808. BABYLON.Tools.Warn("Function to remove was not found");
  73809. }
  73810. };
  73811. /**
  73812. * Register a function that will be executed after the physics step
  73813. */
  73814. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  73815. this._onAfterPhysicsStepCallbacks.push(func);
  73816. };
  73817. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  73818. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  73819. if (index > -1) {
  73820. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  73821. }
  73822. else {
  73823. BABYLON.Tools.Warn("Function to remove was not found");
  73824. }
  73825. };
  73826. /**
  73827. * register a function that will be executed when this impostor collides against a different body.
  73828. */
  73829. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  73830. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73831. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  73832. };
  73833. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  73834. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  73835. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  73836. if (index > -1) {
  73837. this._onPhysicsCollideCallbacks.splice(index, 1);
  73838. }
  73839. else {
  73840. BABYLON.Tools.Warn("Function to remove was not found");
  73841. }
  73842. };
  73843. PhysicsImpostor.prototype.getParentsRotation = function () {
  73844. var parent = this.object.parent;
  73845. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  73846. while (parent) {
  73847. if (parent.rotationQuaternion) {
  73848. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  73849. }
  73850. else {
  73851. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  73852. }
  73853. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  73854. parent = parent.parent;
  73855. }
  73856. return this._tmpQuat;
  73857. };
  73858. /**
  73859. * Apply a force
  73860. */
  73861. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  73862. if (this._physicsEngine) {
  73863. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  73864. }
  73865. return this;
  73866. };
  73867. /**
  73868. * Apply an impulse
  73869. */
  73870. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  73871. if (this._physicsEngine) {
  73872. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  73873. }
  73874. return this;
  73875. };
  73876. /**
  73877. * A help function to create a joint.
  73878. */
  73879. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  73880. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  73881. this.addJoint(otherImpostor, joint);
  73882. return this;
  73883. };
  73884. /**
  73885. * Add a joint to this impostor with a different impostor.
  73886. */
  73887. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  73888. this._joints.push({
  73889. otherImpostor: otherImpostor,
  73890. joint: joint
  73891. });
  73892. if (this._physicsEngine) {
  73893. this._physicsEngine.addJoint(this, otherImpostor, joint);
  73894. }
  73895. return this;
  73896. };
  73897. /**
  73898. * Will keep this body still, in a sleep mode.
  73899. */
  73900. PhysicsImpostor.prototype.sleep = function () {
  73901. if (this._physicsEngine) {
  73902. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  73903. }
  73904. return this;
  73905. };
  73906. /**
  73907. * Wake the body up.
  73908. */
  73909. PhysicsImpostor.prototype.wakeUp = function () {
  73910. if (this._physicsEngine) {
  73911. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  73912. }
  73913. return this;
  73914. };
  73915. PhysicsImpostor.prototype.clone = function (newObject) {
  73916. if (!newObject)
  73917. return null;
  73918. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  73919. };
  73920. PhysicsImpostor.prototype.dispose = function () {
  73921. var _this = this;
  73922. //no dispose if no physics engine is available.
  73923. if (!this._physicsEngine) {
  73924. return;
  73925. }
  73926. this._joints.forEach(function (j) {
  73927. if (_this._physicsEngine) {
  73928. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  73929. }
  73930. });
  73931. //dispose the physics body
  73932. this._physicsEngine.removeImpostor(this);
  73933. if (this.parent) {
  73934. this.parent.forceUpdate();
  73935. }
  73936. else {
  73937. /*this._object.getChildMeshes().forEach(function(mesh) {
  73938. if (mesh.physicsImpostor) {
  73939. if (disposeChildren) {
  73940. mesh.physicsImpostor.dispose();
  73941. mesh.physicsImpostor = null;
  73942. }
  73943. }
  73944. })*/
  73945. }
  73946. this._isDisposed = true;
  73947. };
  73948. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  73949. this._deltaPosition.copyFrom(position);
  73950. };
  73951. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  73952. if (!this._deltaRotation) {
  73953. this._deltaRotation = new BABYLON.Quaternion();
  73954. }
  73955. this._deltaRotation.copyFrom(rotation);
  73956. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  73957. };
  73958. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  73959. if (this._physicsEngine) {
  73960. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  73961. }
  73962. return this;
  73963. };
  73964. PhysicsImpostor.prototype.getRadius = function () {
  73965. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  73966. };
  73967. /**
  73968. * Sync a bone with this impostor
  73969. * @param bone The bone to sync to the impostor.
  73970. * @param boneMesh The mesh that the bone is influencing.
  73971. * @param jointPivot The pivot of the joint / bone in local space.
  73972. * @param distToJoint Optional distance from the impostor to the joint.
  73973. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  73974. */
  73975. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  73976. var tempVec = PhysicsImpostor._tmpVecs[0];
  73977. var mesh = this.object;
  73978. if (mesh.rotationQuaternion) {
  73979. if (adjustRotation) {
  73980. var tempQuat = PhysicsImpostor._tmpQuat;
  73981. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  73982. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  73983. }
  73984. else {
  73985. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  73986. }
  73987. }
  73988. tempVec.x = 0;
  73989. tempVec.y = 0;
  73990. tempVec.z = 0;
  73991. if (jointPivot) {
  73992. tempVec.x = jointPivot.x;
  73993. tempVec.y = jointPivot.y;
  73994. tempVec.z = jointPivot.z;
  73995. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  73996. if (distToJoint === undefined || distToJoint === null) {
  73997. distToJoint = jointPivot.length();
  73998. }
  73999. tempVec.x *= distToJoint;
  74000. tempVec.y *= distToJoint;
  74001. tempVec.z *= distToJoint;
  74002. }
  74003. if (bone.getParent()) {
  74004. tempVec.addInPlace(mesh.getAbsolutePosition());
  74005. bone.setAbsolutePosition(tempVec, boneMesh);
  74006. }
  74007. else {
  74008. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  74009. boneMesh.position.x -= tempVec.x;
  74010. boneMesh.position.y -= tempVec.y;
  74011. boneMesh.position.z -= tempVec.z;
  74012. }
  74013. };
  74014. /**
  74015. * Sync impostor to a bone
  74016. * @param bone The bone that the impostor will be synced to.
  74017. * @param boneMesh The mesh that the bone is influencing.
  74018. * @param jointPivot The pivot of the joint / bone in local space.
  74019. * @param distToJoint Optional distance from the impostor to the joint.
  74020. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  74021. * @param boneAxis Optional vector3 axis the bone is aligned with
  74022. */
  74023. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  74024. var mesh = this.object;
  74025. if (mesh.rotationQuaternion) {
  74026. if (adjustRotation) {
  74027. var tempQuat = PhysicsImpostor._tmpQuat;
  74028. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  74029. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  74030. }
  74031. else {
  74032. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  74033. }
  74034. }
  74035. var pos = PhysicsImpostor._tmpVecs[0];
  74036. var boneDir = PhysicsImpostor._tmpVecs[1];
  74037. if (!boneAxis) {
  74038. boneAxis = PhysicsImpostor._tmpVecs[2];
  74039. boneAxis.x = 0;
  74040. boneAxis.y = 1;
  74041. boneAxis.z = 0;
  74042. }
  74043. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  74044. bone.getAbsolutePositionToRef(boneMesh, pos);
  74045. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  74046. distToJoint = jointPivot.length();
  74047. }
  74048. if (distToJoint !== undefined && distToJoint !== null) {
  74049. pos.x += boneDir.x * distToJoint;
  74050. pos.y += boneDir.y * distToJoint;
  74051. pos.z += boneDir.z * distToJoint;
  74052. }
  74053. mesh.setAbsolutePosition(pos);
  74054. };
  74055. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  74056. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  74057. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74058. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  74059. //Impostor types
  74060. PhysicsImpostor.NoImpostor = 0;
  74061. PhysicsImpostor.SphereImpostor = 1;
  74062. PhysicsImpostor.BoxImpostor = 2;
  74063. PhysicsImpostor.PlaneImpostor = 3;
  74064. PhysicsImpostor.MeshImpostor = 4;
  74065. PhysicsImpostor.CylinderImpostor = 7;
  74066. PhysicsImpostor.ParticleImpostor = 8;
  74067. PhysicsImpostor.HeightmapImpostor = 9;
  74068. return PhysicsImpostor;
  74069. }());
  74070. BABYLON.PhysicsImpostor = PhysicsImpostor;
  74071. })(BABYLON || (BABYLON = {}));
  74072. //# sourceMappingURL=babylon.physicsImpostor.js.map
  74073. var BABYLON;
  74074. (function (BABYLON) {
  74075. var PhysicsEngine = /** @class */ (function () {
  74076. function PhysicsEngine(gravity, _physicsPlugin) {
  74077. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  74078. this._physicsPlugin = _physicsPlugin;
  74079. //new methods and parameters
  74080. this._impostors = [];
  74081. this._joints = [];
  74082. if (!this._physicsPlugin.isSupported()) {
  74083. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  74084. + "Please make sure it is included.");
  74085. }
  74086. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  74087. this.setGravity(gravity);
  74088. this.setTimeStep();
  74089. }
  74090. PhysicsEngine.prototype.setGravity = function (gravity) {
  74091. this.gravity = gravity;
  74092. this._physicsPlugin.setGravity(this.gravity);
  74093. };
  74094. /**
  74095. * Set the time step of the physics engine.
  74096. * default is 1/60.
  74097. * To slow it down, enter 1/600 for example.
  74098. * To speed it up, 1/30
  74099. * @param {number} newTimeStep the new timestep to apply to this world.
  74100. */
  74101. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  74102. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  74103. this._physicsPlugin.setTimeStep(newTimeStep);
  74104. };
  74105. /**
  74106. * Get the time step of the physics engine.
  74107. */
  74108. PhysicsEngine.prototype.getTimeStep = function () {
  74109. return this._physicsPlugin.getTimeStep();
  74110. };
  74111. PhysicsEngine.prototype.dispose = function () {
  74112. this._impostors.forEach(function (impostor) {
  74113. impostor.dispose();
  74114. });
  74115. this._physicsPlugin.dispose();
  74116. };
  74117. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  74118. return this._physicsPlugin.name;
  74119. };
  74120. /**
  74121. * Adding a new impostor for the impostor tracking.
  74122. * This will be done by the impostor itself.
  74123. * @param {PhysicsImpostor} impostor the impostor to add
  74124. */
  74125. PhysicsEngine.prototype.addImpostor = function (impostor) {
  74126. impostor.uniqueId = this._impostors.push(impostor);
  74127. //if no parent, generate the body
  74128. if (!impostor.parent) {
  74129. this._physicsPlugin.generatePhysicsBody(impostor);
  74130. }
  74131. };
  74132. /**
  74133. * Remove an impostor from the engine.
  74134. * This impostor and its mesh will not longer be updated by the physics engine.
  74135. * @param {PhysicsImpostor} impostor the impostor to remove
  74136. */
  74137. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  74138. var index = this._impostors.indexOf(impostor);
  74139. if (index > -1) {
  74140. var removed = this._impostors.splice(index, 1);
  74141. //Is it needed?
  74142. if (removed.length) {
  74143. //this will also remove it from the world.
  74144. removed[0].physicsBody = null;
  74145. }
  74146. }
  74147. };
  74148. /**
  74149. * Add a joint to the physics engine
  74150. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  74151. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  74152. * @param {PhysicsJoint} the joint that will connect both impostors.
  74153. */
  74154. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  74155. var impostorJoint = {
  74156. mainImpostor: mainImpostor,
  74157. connectedImpostor: connectedImpostor,
  74158. joint: joint
  74159. };
  74160. joint.physicsPlugin = this._physicsPlugin;
  74161. this._joints.push(impostorJoint);
  74162. this._physicsPlugin.generateJoint(impostorJoint);
  74163. };
  74164. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  74165. var matchingJoints = this._joints.filter(function (impostorJoint) {
  74166. return (impostorJoint.connectedImpostor === connectedImpostor
  74167. && impostorJoint.joint === joint
  74168. && impostorJoint.mainImpostor === mainImpostor);
  74169. });
  74170. if (matchingJoints.length) {
  74171. this._physicsPlugin.removeJoint(matchingJoints[0]);
  74172. //TODO remove it from the list as well
  74173. }
  74174. };
  74175. /**
  74176. * Called by the scene. no need to call it.
  74177. */
  74178. PhysicsEngine.prototype._step = function (delta) {
  74179. var _this = this;
  74180. //check if any mesh has no body / requires an update
  74181. this._impostors.forEach(function (impostor) {
  74182. if (impostor.isBodyInitRequired()) {
  74183. _this._physicsPlugin.generatePhysicsBody(impostor);
  74184. }
  74185. });
  74186. if (delta > 0.1) {
  74187. delta = 0.1;
  74188. }
  74189. else if (delta <= 0) {
  74190. delta = 1.0 / 60.0;
  74191. }
  74192. this._physicsPlugin.executeStep(delta, this._impostors);
  74193. };
  74194. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  74195. return this._physicsPlugin;
  74196. };
  74197. PhysicsEngine.prototype.getImpostors = function () {
  74198. return this._impostors;
  74199. };
  74200. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  74201. for (var i = 0; i < this._impostors.length; ++i) {
  74202. if (this._impostors[i].object === object) {
  74203. return this._impostors[i];
  74204. }
  74205. }
  74206. return null;
  74207. };
  74208. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  74209. for (var i = 0; i < this._impostors.length; ++i) {
  74210. if (this._impostors[i].physicsBody === body) {
  74211. return this._impostors[i];
  74212. }
  74213. }
  74214. return null;
  74215. };
  74216. // Statics
  74217. PhysicsEngine.Epsilon = 0.001;
  74218. return PhysicsEngine;
  74219. }());
  74220. BABYLON.PhysicsEngine = PhysicsEngine;
  74221. })(BABYLON || (BABYLON = {}));
  74222. //# sourceMappingURL=babylon.physicsEngine.js.map
  74223. var BABYLON;
  74224. (function (BABYLON) {
  74225. var PhysicsHelper = /** @class */ (function () {
  74226. function PhysicsHelper(scene) {
  74227. this._scene = scene;
  74228. this._physicsEngine = this._scene.getPhysicsEngine();
  74229. if (!this._physicsEngine) {
  74230. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  74231. }
  74232. }
  74233. /**
  74234. * @param {Vector3} origin the origin of the explosion
  74235. * @param {number} radius the explosion radius
  74236. * @param {number} strength the explosion strength
  74237. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74238. */
  74239. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  74240. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74241. if (!this._physicsEngine) {
  74242. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  74243. return null;
  74244. }
  74245. var impostors = this._physicsEngine.getImpostors();
  74246. if (impostors.length === 0) {
  74247. return null;
  74248. }
  74249. var event = new PhysicsRadialExplosionEvent(this._scene);
  74250. impostors.forEach(function (impostor) {
  74251. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74252. if (!impostorForceAndContactPoint) {
  74253. return;
  74254. }
  74255. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74256. });
  74257. event.dispose(false);
  74258. return event;
  74259. };
  74260. /**
  74261. * @param {Vector3} origin the origin of the explosion
  74262. * @param {number} radius the explosion radius
  74263. * @param {number} strength the explosion strength
  74264. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74265. */
  74266. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  74267. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74268. if (!this._physicsEngine) {
  74269. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74270. return null;
  74271. }
  74272. var impostors = this._physicsEngine.getImpostors();
  74273. if (impostors.length === 0) {
  74274. return null;
  74275. }
  74276. var event = new PhysicsRadialExplosionEvent(this._scene);
  74277. impostors.forEach(function (impostor) {
  74278. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74279. if (!impostorForceAndContactPoint) {
  74280. return;
  74281. }
  74282. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74283. });
  74284. event.dispose(false);
  74285. return event;
  74286. };
  74287. /**
  74288. * @param {Vector3} origin the origin of the explosion
  74289. * @param {number} radius the explosion radius
  74290. * @param {number} strength the explosion strength
  74291. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74292. */
  74293. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  74294. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74295. if (!this._physicsEngine) {
  74296. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74297. return null;
  74298. }
  74299. var impostors = this._physicsEngine.getImpostors();
  74300. if (impostors.length === 0) {
  74301. return null;
  74302. }
  74303. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  74304. event.dispose(false);
  74305. return event;
  74306. };
  74307. /**
  74308. * @param {Vector3} origin the origin of the updraft
  74309. * @param {number} radius the radius of the updraft
  74310. * @param {number} strength the strength of the updraft
  74311. * @param {number} height the height of the updraft
  74312. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  74313. */
  74314. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  74315. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  74316. if (!this._physicsEngine) {
  74317. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74318. return null;
  74319. }
  74320. if (this._physicsEngine.getImpostors().length === 0) {
  74321. return null;
  74322. }
  74323. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  74324. event.dispose(false);
  74325. return event;
  74326. };
  74327. /**
  74328. * @param {Vector3} origin the of the vortex
  74329. * @param {number} radius the radius of the vortex
  74330. * @param {number} strength the strength of the vortex
  74331. * @param {number} height the height of the vortex
  74332. */
  74333. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  74334. if (!this._physicsEngine) {
  74335. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74336. return null;
  74337. }
  74338. if (this._physicsEngine.getImpostors().length === 0) {
  74339. return null;
  74340. }
  74341. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  74342. event.dispose(false);
  74343. return event;
  74344. };
  74345. return PhysicsHelper;
  74346. }());
  74347. BABYLON.PhysicsHelper = PhysicsHelper;
  74348. /***** Radial explosion *****/
  74349. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74350. function PhysicsRadialExplosionEvent(scene) {
  74351. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74352. this._rays = [];
  74353. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74354. this._scene = scene;
  74355. }
  74356. /**
  74357. * Returns the data related to the radial explosion event (sphere & rays).
  74358. * @returns {PhysicsRadialExplosionEventData}
  74359. */
  74360. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74361. this._dataFetched = true;
  74362. return {
  74363. sphere: this._sphere,
  74364. rays: this._rays,
  74365. };
  74366. };
  74367. /**
  74368. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74369. * @param impostor
  74370. * @param {Vector3} origin the origin of the explosion
  74371. * @param {number} radius the explosion radius
  74372. * @param {number} strength the explosion strength
  74373. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74374. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74375. */
  74376. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74377. if (impostor.mass === 0) {
  74378. return null;
  74379. }
  74380. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74381. return null;
  74382. }
  74383. if (impostor.object.getClassName() !== 'Mesh') {
  74384. return null;
  74385. }
  74386. var impostorObject = impostor.object;
  74387. var impostorObjectCenter = impostor.getObjectCenter();
  74388. var direction = impostorObjectCenter.subtract(origin);
  74389. var ray = new BABYLON.Ray(origin, direction, radius);
  74390. this._rays.push(ray);
  74391. var hit = ray.intersectsMesh(impostorObject);
  74392. var contactPoint = hit.pickedPoint;
  74393. if (!contactPoint) {
  74394. return null;
  74395. }
  74396. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74397. if (distanceFromOrigin > radius) {
  74398. return null;
  74399. }
  74400. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74401. ? strength
  74402. : strength * (1 - (distanceFromOrigin / radius));
  74403. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74404. return { force: force, contactPoint: contactPoint };
  74405. };
  74406. /**
  74407. * Disposes the sphere.
  74408. * @param {bolean} force
  74409. */
  74410. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74411. var _this = this;
  74412. if (force === void 0) { force = true; }
  74413. if (force) {
  74414. this._sphere.dispose();
  74415. }
  74416. else {
  74417. setTimeout(function () {
  74418. if (!_this._dataFetched) {
  74419. _this._sphere.dispose();
  74420. }
  74421. }, 0);
  74422. }
  74423. };
  74424. /*** Helpers ***/
  74425. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74426. if (!this._sphere) {
  74427. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74428. this._sphere.isVisible = false;
  74429. }
  74430. };
  74431. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74432. var impostorObject = impostor.object;
  74433. this._prepareSphere();
  74434. this._sphere.position = origin;
  74435. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74436. this._sphere._updateBoundingInfo();
  74437. this._sphere.computeWorldMatrix(true);
  74438. return this._sphere.intersectsMesh(impostorObject, true);
  74439. };
  74440. return PhysicsRadialExplosionEvent;
  74441. }());
  74442. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74443. /***** Gravitational Field *****/
  74444. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74445. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74446. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74447. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74448. this._physicsHelper = physicsHelper;
  74449. this._scene = scene;
  74450. this._origin = origin;
  74451. this._radius = radius;
  74452. this._strength = strength;
  74453. this._falloff = falloff;
  74454. this._tickCallback = this._tick.bind(this);
  74455. }
  74456. /**
  74457. * Returns the data related to the gravitational field event (sphere).
  74458. * @returns {PhysicsGravitationalFieldEventData}
  74459. */
  74460. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74461. this._dataFetched = true;
  74462. return {
  74463. sphere: this._sphere,
  74464. };
  74465. };
  74466. /**
  74467. * Enables the gravitational field.
  74468. */
  74469. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74470. this._tickCallback.call(this);
  74471. this._scene.registerBeforeRender(this._tickCallback);
  74472. };
  74473. /**
  74474. * Disables the gravitational field.
  74475. */
  74476. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74477. this._scene.unregisterBeforeRender(this._tickCallback);
  74478. };
  74479. /**
  74480. * Disposes the sphere.
  74481. * @param {bolean} force
  74482. */
  74483. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74484. var _this = this;
  74485. if (force === void 0) { force = true; }
  74486. if (force) {
  74487. this._sphere.dispose();
  74488. }
  74489. else {
  74490. setTimeout(function () {
  74491. if (!_this._dataFetched) {
  74492. _this._sphere.dispose();
  74493. }
  74494. }, 0);
  74495. }
  74496. };
  74497. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74498. // Since the params won't change, we fetch the event only once
  74499. if (this._sphere) {
  74500. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74501. }
  74502. else {
  74503. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74504. if (radialExplosionEvent) {
  74505. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74506. }
  74507. }
  74508. };
  74509. return PhysicsGravitationalFieldEvent;
  74510. }());
  74511. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74512. /***** Updraft *****/
  74513. var PhysicsUpdraftEvent = /** @class */ (function () {
  74514. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74515. this._scene = _scene;
  74516. this._origin = _origin;
  74517. this._radius = _radius;
  74518. this._strength = _strength;
  74519. this._height = _height;
  74520. this._updraftMode = _updraftMode;
  74521. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74522. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74523. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74524. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74525. this._physicsEngine = this._scene.getPhysicsEngine();
  74526. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74527. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74528. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74529. this._originDirection = this._origin.subtract(this._originTop).normalize();
  74530. }
  74531. this._tickCallback = this._tick.bind(this);
  74532. }
  74533. /**
  74534. * Returns the data related to the updraft event (cylinder).
  74535. * @returns {PhysicsUpdraftEventData}
  74536. */
  74537. PhysicsUpdraftEvent.prototype.getData = function () {
  74538. this._dataFetched = true;
  74539. return {
  74540. cylinder: this._cylinder,
  74541. };
  74542. };
  74543. /**
  74544. * Enables the updraft.
  74545. */
  74546. PhysicsUpdraftEvent.prototype.enable = function () {
  74547. this._tickCallback.call(this);
  74548. this._scene.registerBeforeRender(this._tickCallback);
  74549. };
  74550. /**
  74551. * Disables the cortex.
  74552. */
  74553. PhysicsUpdraftEvent.prototype.disable = function () {
  74554. this._scene.unregisterBeforeRender(this._tickCallback);
  74555. };
  74556. /**
  74557. * Disposes the sphere.
  74558. * @param {bolean} force
  74559. */
  74560. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  74561. var _this = this;
  74562. if (force === void 0) { force = true; }
  74563. if (force) {
  74564. this._cylinder.dispose();
  74565. }
  74566. else {
  74567. setTimeout(function () {
  74568. if (!_this._dataFetched) {
  74569. _this._cylinder.dispose();
  74570. }
  74571. }, 0);
  74572. }
  74573. };
  74574. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74575. if (impostor.mass === 0) {
  74576. return null;
  74577. }
  74578. if (!this._intersectsWithCylinder(impostor)) {
  74579. return null;
  74580. }
  74581. var impostorObjectCenter = impostor.getObjectCenter();
  74582. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74583. var direction = this._originDirection;
  74584. }
  74585. else {
  74586. var direction = impostorObjectCenter.subtract(this._originTop);
  74587. }
  74588. var multiplier = this._strength * -1;
  74589. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74590. return { force: force, contactPoint: impostorObjectCenter };
  74591. };
  74592. PhysicsUpdraftEvent.prototype._tick = function () {
  74593. var _this = this;
  74594. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74595. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74596. if (!impostorForceAndContactPoint) {
  74597. return;
  74598. }
  74599. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74600. });
  74601. };
  74602. /*** Helpers ***/
  74603. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  74604. if (!this._cylinder) {
  74605. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  74606. height: this._height,
  74607. diameter: this._radius * 2,
  74608. }, this._scene);
  74609. this._cylinder.isVisible = false;
  74610. }
  74611. };
  74612. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  74613. var impostorObject = impostor.object;
  74614. this._prepareCylinder();
  74615. this._cylinder.position = this._cylinderPosition;
  74616. return this._cylinder.intersectsMesh(impostorObject, true);
  74617. };
  74618. return PhysicsUpdraftEvent;
  74619. }());
  74620. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  74621. /***** Vortex *****/
  74622. var PhysicsVortexEvent = /** @class */ (function () {
  74623. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  74624. this._scene = _scene;
  74625. this._origin = _origin;
  74626. this._radius = _radius;
  74627. this._strength = _strength;
  74628. this._height = _height;
  74629. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74630. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  74631. this._updraftMultiplier = 0.02;
  74632. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74633. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74634. this._physicsEngine = this._scene.getPhysicsEngine();
  74635. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74636. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74637. this._tickCallback = this._tick.bind(this);
  74638. }
  74639. /**
  74640. * Returns the data related to the vortex event (cylinder).
  74641. * @returns {PhysicsVortexEventData}
  74642. */
  74643. PhysicsVortexEvent.prototype.getData = function () {
  74644. this._dataFetched = true;
  74645. return {
  74646. cylinder: this._cylinder,
  74647. };
  74648. };
  74649. /**
  74650. * Enables the vortex.
  74651. */
  74652. PhysicsVortexEvent.prototype.enable = function () {
  74653. this._tickCallback.call(this);
  74654. this._scene.registerBeforeRender(this._tickCallback);
  74655. };
  74656. /**
  74657. * Disables the cortex.
  74658. */
  74659. PhysicsVortexEvent.prototype.disable = function () {
  74660. this._scene.unregisterBeforeRender(this._tickCallback);
  74661. };
  74662. /**
  74663. * Disposes the sphere.
  74664. * @param {bolean} force
  74665. */
  74666. PhysicsVortexEvent.prototype.dispose = function (force) {
  74667. var _this = this;
  74668. if (force === void 0) { force = true; }
  74669. if (force) {
  74670. this._cylinder.dispose();
  74671. }
  74672. else {
  74673. setTimeout(function () {
  74674. if (!_this._dataFetched) {
  74675. _this._cylinder.dispose();
  74676. }
  74677. }, 0);
  74678. }
  74679. };
  74680. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  74681. if (impostor.mass === 0) {
  74682. return null;
  74683. }
  74684. if (!this._intersectsWithCylinder(impostor)) {
  74685. return null;
  74686. }
  74687. if (impostor.object.getClassName() !== 'Mesh') {
  74688. return null;
  74689. }
  74690. var impostorObject = impostor.object;
  74691. var impostorObjectCenter = impostor.getObjectCenter();
  74692. 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)
  74693. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  74694. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  74695. var hit = ray.intersectsMesh(impostorObject);
  74696. var contactPoint = hit.pickedPoint;
  74697. if (!contactPoint) {
  74698. return null;
  74699. }
  74700. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  74701. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  74702. var directionToOrigin = contactPoint.normalize();
  74703. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74704. directionToOrigin = directionToOrigin.negate();
  74705. }
  74706. // TODO: find a more physically based solution
  74707. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  74708. var forceX = directionToOrigin.x * this._strength / 8;
  74709. var forceY = directionToOrigin.y * this._updraftMultiplier;
  74710. var forceZ = directionToOrigin.z * this._strength / 8;
  74711. }
  74712. else {
  74713. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  74714. var forceY = this._originTop.y * this._updraftMultiplier;
  74715. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  74716. }
  74717. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  74718. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  74719. return { force: force, contactPoint: impostorObjectCenter };
  74720. };
  74721. PhysicsVortexEvent.prototype._tick = function () {
  74722. var _this = this;
  74723. this._physicsEngine.getImpostors().forEach(function (impostor) {
  74724. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  74725. if (!impostorForceAndContactPoint) {
  74726. return;
  74727. }
  74728. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74729. });
  74730. };
  74731. /*** Helpers ***/
  74732. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  74733. if (!this._cylinder) {
  74734. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  74735. height: this._height,
  74736. diameter: this._radius * 2,
  74737. }, this._scene);
  74738. this._cylinder.isVisible = false;
  74739. }
  74740. };
  74741. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  74742. var impostorObject = impostor.object;
  74743. this._prepareCylinder();
  74744. this._cylinder.position = this._cylinderPosition;
  74745. return this._cylinder.intersectsMesh(impostorObject, true);
  74746. };
  74747. return PhysicsVortexEvent;
  74748. }());
  74749. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  74750. /***** Enums *****/
  74751. /**
  74752. * The strenght of the force in correspondence to the distance of the affected object
  74753. */
  74754. var PhysicsRadialImpulseFalloff;
  74755. (function (PhysicsRadialImpulseFalloff) {
  74756. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  74757. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  74758. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  74759. /**
  74760. * The strenght of the force in correspondence to the distance of the affected object
  74761. */
  74762. var PhysicsUpdraftMode;
  74763. (function (PhysicsUpdraftMode) {
  74764. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  74765. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  74766. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  74767. })(BABYLON || (BABYLON = {}));
  74768. //# sourceMappingURL=babylon.physicsHelper.js.map
  74769. var BABYLON;
  74770. (function (BABYLON) {
  74771. var CannonJSPlugin = /** @class */ (function () {
  74772. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  74773. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  74774. if (iterations === void 0) { iterations = 10; }
  74775. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  74776. this.name = "CannonJSPlugin";
  74777. this._physicsMaterials = new Array();
  74778. this._fixedTimeStep = 1 / 60;
  74779. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  74780. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  74781. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  74782. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  74783. this._tmpPosition = BABYLON.Vector3.Zero();
  74784. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  74785. this._tmpUnityRotation = new BABYLON.Quaternion();
  74786. if (!this.isSupported()) {
  74787. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  74788. return;
  74789. }
  74790. this._extendNamespace();
  74791. this.world = new this.BJSCANNON.World();
  74792. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  74793. this.world.solver.iterations = iterations;
  74794. }
  74795. CannonJSPlugin.prototype.setGravity = function (gravity) {
  74796. this.world.gravity.copy(gravity);
  74797. };
  74798. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  74799. this._fixedTimeStep = timeStep;
  74800. };
  74801. CannonJSPlugin.prototype.getTimeStep = function () {
  74802. return this._fixedTimeStep;
  74803. };
  74804. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  74805. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  74806. };
  74807. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  74808. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74809. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74810. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  74811. };
  74812. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  74813. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  74814. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  74815. impostor.physicsBody.applyForce(impulse, worldPoint);
  74816. };
  74817. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  74818. //parent-child relationship. Does this impostor has a parent impostor?
  74819. if (impostor.parent) {
  74820. if (impostor.physicsBody) {
  74821. this.removePhysicsBody(impostor);
  74822. //TODO is that needed?
  74823. impostor.forceUpdate();
  74824. }
  74825. return;
  74826. }
  74827. //should a new body be created for this impostor?
  74828. if (impostor.isBodyInitRequired()) {
  74829. var shape = this._createShape(impostor);
  74830. //unregister events, if body is being changed
  74831. var oldBody = impostor.physicsBody;
  74832. if (oldBody) {
  74833. this.removePhysicsBody(impostor);
  74834. }
  74835. //create the body and material
  74836. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  74837. var bodyCreationObject = {
  74838. mass: impostor.getParam("mass"),
  74839. material: material
  74840. };
  74841. // A simple extend, in case native options were used.
  74842. var nativeOptions = impostor.getParam("nativeOptions");
  74843. for (var key in nativeOptions) {
  74844. if (nativeOptions.hasOwnProperty(key)) {
  74845. bodyCreationObject[key] = nativeOptions[key];
  74846. }
  74847. }
  74848. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  74849. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  74850. this.world.addEventListener("preStep", impostor.beforeStep);
  74851. this.world.addEventListener("postStep", impostor.afterStep);
  74852. impostor.physicsBody.addShape(shape);
  74853. this.world.add(impostor.physicsBody);
  74854. //try to keep the body moving in the right direction by taking old properties.
  74855. //Should be tested!
  74856. if (oldBody) {
  74857. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  74858. impostor.physicsBody[param].copy(oldBody[param]);
  74859. });
  74860. }
  74861. this._processChildMeshes(impostor);
  74862. }
  74863. //now update the body's transformation
  74864. this._updatePhysicsBodyTransformation(impostor);
  74865. };
  74866. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  74867. var _this = this;
  74868. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  74869. var currentRotation = mainImpostor.object.rotationQuaternion;
  74870. if (meshChildren.length) {
  74871. var processMesh = function (localPosition, mesh) {
  74872. if (!currentRotation || !mesh.rotationQuaternion) {
  74873. return;
  74874. }
  74875. var childImpostor = mesh.getPhysicsImpostor();
  74876. if (childImpostor) {
  74877. var parent = childImpostor.parent;
  74878. if (parent !== mainImpostor) {
  74879. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  74880. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  74881. if (childImpostor.physicsBody) {
  74882. _this.removePhysicsBody(childImpostor);
  74883. childImpostor.physicsBody = null;
  74884. }
  74885. childImpostor.parent = mainImpostor;
  74886. childImpostor.resetUpdateFlags();
  74887. 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));
  74888. //Add the mass of the children.
  74889. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  74890. }
  74891. }
  74892. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  74893. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  74894. };
  74895. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  74896. }
  74897. };
  74898. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  74899. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  74900. this.world.removeEventListener("preStep", impostor.beforeStep);
  74901. this.world.removeEventListener("postStep", impostor.afterStep);
  74902. this.world.remove(impostor.physicsBody);
  74903. };
  74904. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  74905. var mainBody = impostorJoint.mainImpostor.physicsBody;
  74906. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  74907. if (!mainBody || !connectedBody) {
  74908. return;
  74909. }
  74910. var constraint;
  74911. var jointData = impostorJoint.joint.jointData;
  74912. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  74913. var constraintData = {
  74914. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  74915. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  74916. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  74917. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  74918. maxForce: jointData.nativeParams.maxForce,
  74919. collideConnected: !!jointData.collision
  74920. };
  74921. switch (impostorJoint.joint.type) {
  74922. case BABYLON.PhysicsJoint.HingeJoint:
  74923. case BABYLON.PhysicsJoint.Hinge2Joint:
  74924. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  74925. break;
  74926. case BABYLON.PhysicsJoint.DistanceJoint:
  74927. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  74928. break;
  74929. case BABYLON.PhysicsJoint.SpringJoint:
  74930. var springData = jointData;
  74931. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  74932. restLength: springData.length,
  74933. stiffness: springData.stiffness,
  74934. damping: springData.damping,
  74935. localAnchorA: constraintData.pivotA,
  74936. localAnchorB: constraintData.pivotB
  74937. });
  74938. break;
  74939. case BABYLON.PhysicsJoint.LockJoint:
  74940. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  74941. break;
  74942. case BABYLON.PhysicsJoint.PointToPointJoint:
  74943. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  74944. default:
  74945. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  74946. break;
  74947. }
  74948. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  74949. constraint.collideConnected = !!jointData.collision;
  74950. impostorJoint.joint.physicsJoint = constraint;
  74951. //don't add spring as constraint, as it is not one.
  74952. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  74953. this.world.addConstraint(constraint);
  74954. }
  74955. else {
  74956. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  74957. constraint.applyForce();
  74958. });
  74959. }
  74960. };
  74961. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  74962. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  74963. };
  74964. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  74965. var index;
  74966. var mat;
  74967. for (index = 0; index < this._physicsMaterials.length; index++) {
  74968. mat = this._physicsMaterials[index];
  74969. if (mat.friction === friction && mat.restitution === restitution) {
  74970. return mat;
  74971. }
  74972. }
  74973. var currentMat = new this.BJSCANNON.Material(name);
  74974. currentMat.friction = friction;
  74975. currentMat.restitution = restitution;
  74976. this._physicsMaterials.push(currentMat);
  74977. return currentMat;
  74978. };
  74979. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  74980. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  74981. };
  74982. CannonJSPlugin.prototype._createShape = function (impostor) {
  74983. var object = impostor.object;
  74984. var returnValue;
  74985. var extendSize = impostor.getObjectExtendSize();
  74986. switch (impostor.type) {
  74987. case BABYLON.PhysicsImpostor.SphereImpostor:
  74988. var radiusX = extendSize.x;
  74989. var radiusY = extendSize.y;
  74990. var radiusZ = extendSize.z;
  74991. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  74992. break;
  74993. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  74994. case BABYLON.PhysicsImpostor.CylinderImpostor:
  74995. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  74996. break;
  74997. case BABYLON.PhysicsImpostor.BoxImpostor:
  74998. var box = extendSize.scale(0.5);
  74999. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  75000. break;
  75001. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75002. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  75003. returnValue = new this.BJSCANNON.Plane();
  75004. break;
  75005. case BABYLON.PhysicsImpostor.MeshImpostor:
  75006. // should transform the vertex data to world coordinates!!
  75007. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  75008. var rawFaces = object.getIndices ? object.getIndices() : [];
  75009. if (!rawVerts)
  75010. return;
  75011. // get only scale! so the object could transform correctly.
  75012. var oldPosition = object.position.clone();
  75013. var oldRotation = object.rotation && object.rotation.clone();
  75014. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  75015. object.position.copyFromFloats(0, 0, 0);
  75016. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  75017. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  75018. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  75019. var transform = object.computeWorldMatrix(true);
  75020. // convert rawVerts to object space
  75021. var temp = new Array();
  75022. var index;
  75023. for (index = 0; index < rawVerts.length; index += 3) {
  75024. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  75025. }
  75026. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  75027. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  75028. //now set back the transformation!
  75029. object.position.copyFrom(oldPosition);
  75030. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  75031. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  75032. break;
  75033. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  75034. var oldPosition2 = object.position.clone();
  75035. var oldRotation2 = object.rotation && object.rotation.clone();
  75036. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  75037. object.position.copyFromFloats(0, 0, 0);
  75038. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  75039. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  75040. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  75041. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  75042. returnValue = this._createHeightmap(object);
  75043. object.position.copyFrom(oldPosition2);
  75044. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  75045. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  75046. object.computeWorldMatrix(true);
  75047. break;
  75048. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75049. returnValue = new this.BJSCANNON.Particle();
  75050. break;
  75051. }
  75052. return returnValue;
  75053. };
  75054. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  75055. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  75056. var transform = object.computeWorldMatrix(true);
  75057. // convert rawVerts to object space
  75058. var temp = new Array();
  75059. var index;
  75060. for (index = 0; index < pos.length; index += 3) {
  75061. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  75062. }
  75063. pos = temp;
  75064. var matrix = new Array();
  75065. //For now pointDepth will not be used and will be automatically calculated.
  75066. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  75067. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  75068. var boundingInfo = object.getBoundingInfo();
  75069. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  75070. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  75071. var elementSize = dim * 2 / arraySize;
  75072. for (var i = 0; i < pos.length; i = i + 3) {
  75073. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  75074. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  75075. var y = -pos[i + 2] + minY;
  75076. if (!matrix[x]) {
  75077. matrix[x] = [];
  75078. }
  75079. if (!matrix[x][z]) {
  75080. matrix[x][z] = y;
  75081. }
  75082. matrix[x][z] = Math.max(y, matrix[x][z]);
  75083. }
  75084. for (var x = 0; x <= arraySize; ++x) {
  75085. if (!matrix[x]) {
  75086. var loc = 1;
  75087. while (!matrix[(x + loc) % arraySize]) {
  75088. loc++;
  75089. }
  75090. matrix[x] = matrix[(x + loc) % arraySize].slice();
  75091. //console.log("missing x", x);
  75092. }
  75093. for (var z = 0; z <= arraySize; ++z) {
  75094. if (!matrix[x][z]) {
  75095. var loc = 1;
  75096. var newValue;
  75097. while (newValue === undefined) {
  75098. newValue = matrix[x][(z + loc++) % arraySize];
  75099. }
  75100. matrix[x][z] = newValue;
  75101. }
  75102. }
  75103. }
  75104. var shape = new this.BJSCANNON.Heightfield(matrix, {
  75105. elementSize: elementSize
  75106. });
  75107. //For future reference, needed for body transformation
  75108. shape.minY = minY;
  75109. return shape;
  75110. };
  75111. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  75112. var object = impostor.object;
  75113. //make sure it is updated...
  75114. object.computeWorldMatrix && object.computeWorldMatrix(true);
  75115. // The delta between the mesh position and the mesh bounding box center
  75116. var bInfo = object.getBoundingInfo();
  75117. if (!bInfo)
  75118. return;
  75119. var center = impostor.getObjectCenter();
  75120. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  75121. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  75122. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  75123. this._tmpPosition.copyFrom(center);
  75124. var quaternion = object.rotationQuaternion;
  75125. if (!quaternion) {
  75126. return;
  75127. }
  75128. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  75129. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  75130. //-90 DEG in X, precalculated
  75131. quaternion = quaternion.multiply(this._minus90X);
  75132. //Invert! (Precalculated, 90 deg in X)
  75133. //No need to clone. this will never change.
  75134. impostor.setDeltaRotation(this._plus90X);
  75135. }
  75136. //If it is a heightfield, if should be centered.
  75137. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  75138. var mesh = object;
  75139. var boundingInfo = mesh.getBoundingInfo();
  75140. //calculate the correct body position:
  75141. var rotationQuaternion = mesh.rotationQuaternion;
  75142. mesh.rotationQuaternion = this._tmpUnityRotation;
  75143. mesh.computeWorldMatrix(true);
  75144. //get original center with no rotation
  75145. var c = center.clone();
  75146. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  75147. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  75148. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  75149. mesh.setPreTransformMatrix(p);
  75150. mesh.computeWorldMatrix(true);
  75151. //calculate the translation
  75152. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  75153. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  75154. //add it inverted to the delta
  75155. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  75156. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  75157. //rotation is back
  75158. mesh.rotationQuaternion = rotationQuaternion;
  75159. mesh.setPreTransformMatrix(oldPivot);
  75160. mesh.computeWorldMatrix(true);
  75161. }
  75162. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  75163. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  75164. //this._tmpPosition.copyFrom(object.position);
  75165. }
  75166. impostor.setDeltaPosition(this._tmpDeltaPosition);
  75167. //Now update the impostor object
  75168. impostor.physicsBody.position.copy(this._tmpPosition);
  75169. impostor.physicsBody.quaternion.copy(quaternion);
  75170. };
  75171. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75172. impostor.object.position.copyFrom(impostor.physicsBody.position);
  75173. if (impostor.object.rotationQuaternion) {
  75174. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  75175. }
  75176. };
  75177. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75178. impostor.physicsBody.position.copy(newPosition);
  75179. impostor.physicsBody.quaternion.copy(newRotation);
  75180. };
  75181. CannonJSPlugin.prototype.isSupported = function () {
  75182. return this.BJSCANNON !== undefined;
  75183. };
  75184. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75185. impostor.physicsBody.velocity.copy(velocity);
  75186. };
  75187. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75188. impostor.physicsBody.angularVelocity.copy(velocity);
  75189. };
  75190. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75191. var v = impostor.physicsBody.velocity;
  75192. if (!v) {
  75193. return null;
  75194. }
  75195. return new BABYLON.Vector3(v.x, v.y, v.z);
  75196. };
  75197. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75198. var v = impostor.physicsBody.angularVelocity;
  75199. if (!v) {
  75200. return null;
  75201. }
  75202. return new BABYLON.Vector3(v.x, v.y, v.z);
  75203. };
  75204. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75205. impostor.physicsBody.mass = mass;
  75206. impostor.physicsBody.updateMassProperties();
  75207. };
  75208. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  75209. return impostor.physicsBody.mass;
  75210. };
  75211. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  75212. return impostor.physicsBody.material.friction;
  75213. };
  75214. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75215. impostor.physicsBody.material.friction = friction;
  75216. };
  75217. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75218. return impostor.physicsBody.material.restitution;
  75219. };
  75220. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75221. impostor.physicsBody.material.restitution = restitution;
  75222. };
  75223. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  75224. impostor.physicsBody.sleep();
  75225. };
  75226. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  75227. impostor.physicsBody.wakeUp();
  75228. };
  75229. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75230. joint.physicsJoint.distance = maxDistance;
  75231. };
  75232. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75233. // if (!motorIndex) {
  75234. // joint.physicsJoint.enableMotor();
  75235. // }
  75236. // }
  75237. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75238. // if (!motorIndex) {
  75239. // joint.physicsJoint.disableMotor();
  75240. // }
  75241. // }
  75242. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75243. if (!motorIndex) {
  75244. joint.physicsJoint.enableMotor();
  75245. joint.physicsJoint.setMotorSpeed(speed);
  75246. if (maxForce) {
  75247. this.setLimit(joint, maxForce);
  75248. }
  75249. }
  75250. };
  75251. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  75252. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  75253. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  75254. };
  75255. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75256. var body = impostor.physicsBody;
  75257. mesh.position.x = body.position.x;
  75258. mesh.position.y = body.position.y;
  75259. mesh.position.z = body.position.z;
  75260. if (mesh.rotationQuaternion) {
  75261. mesh.rotationQuaternion.x = body.quaternion.x;
  75262. mesh.rotationQuaternion.y = body.quaternion.y;
  75263. mesh.rotationQuaternion.z = body.quaternion.z;
  75264. mesh.rotationQuaternion.w = body.quaternion.w;
  75265. }
  75266. };
  75267. CannonJSPlugin.prototype.getRadius = function (impostor) {
  75268. var shape = impostor.physicsBody.shapes[0];
  75269. return shape.boundingSphereRadius;
  75270. };
  75271. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75272. var shape = impostor.physicsBody.shapes[0];
  75273. result.x = shape.halfExtents.x * 2;
  75274. result.y = shape.halfExtents.y * 2;
  75275. result.z = shape.halfExtents.z * 2;
  75276. };
  75277. CannonJSPlugin.prototype.dispose = function () {
  75278. };
  75279. CannonJSPlugin.prototype._extendNamespace = function () {
  75280. //this will force cannon to execute at least one step when using interpolation
  75281. var step_tmp1 = new this.BJSCANNON.Vec3();
  75282. var Engine = this.BJSCANNON;
  75283. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  75284. maxSubSteps = maxSubSteps || 10;
  75285. timeSinceLastCalled = timeSinceLastCalled || 0;
  75286. if (timeSinceLastCalled === 0) {
  75287. this.internalStep(dt);
  75288. this.time += dt;
  75289. }
  75290. else {
  75291. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  75292. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  75293. var t0 = performance.now();
  75294. for (var i = 0; i !== internalSteps; i++) {
  75295. this.internalStep(dt);
  75296. if (performance.now() - t0 > dt * 1000) {
  75297. break;
  75298. }
  75299. }
  75300. this.time += timeSinceLastCalled;
  75301. var h = this.time % dt;
  75302. var h_div_dt = h / dt;
  75303. var interpvelo = step_tmp1;
  75304. var bodies = this.bodies;
  75305. for (var j = 0; j !== bodies.length; j++) {
  75306. var b = bodies[j];
  75307. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  75308. b.position.vsub(b.previousPosition, interpvelo);
  75309. interpvelo.scale(h_div_dt, interpvelo);
  75310. b.position.vadd(interpvelo, b.interpolatedPosition);
  75311. }
  75312. else {
  75313. b.interpolatedPosition.copy(b.position);
  75314. b.interpolatedQuaternion.copy(b.quaternion);
  75315. }
  75316. }
  75317. }
  75318. };
  75319. };
  75320. return CannonJSPlugin;
  75321. }());
  75322. BABYLON.CannonJSPlugin = CannonJSPlugin;
  75323. })(BABYLON || (BABYLON = {}));
  75324. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  75325. var BABYLON;
  75326. (function (BABYLON) {
  75327. var OimoJSPlugin = /** @class */ (function () {
  75328. function OimoJSPlugin(iterations) {
  75329. this.name = "OimoJSPlugin";
  75330. this._tmpImpostorsArray = [];
  75331. this._tmpPositionVector = BABYLON.Vector3.Zero();
  75332. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  75333. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  75334. this.world.worldscale(1);
  75335. this.world.clear();
  75336. //making sure no stats are calculated
  75337. this.world.isNoStat = true;
  75338. }
  75339. OimoJSPlugin.prototype.setGravity = function (gravity) {
  75340. this.world.gravity.copy(gravity);
  75341. };
  75342. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  75343. this.world.timeStep = timeStep;
  75344. };
  75345. OimoJSPlugin.prototype.getTimeStep = function () {
  75346. return this.world.timeStep;
  75347. };
  75348. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75349. var _this = this;
  75350. impostors.forEach(function (impostor) {
  75351. impostor.beforeStep();
  75352. });
  75353. this.world.step();
  75354. impostors.forEach(function (impostor) {
  75355. impostor.afterStep();
  75356. //update the ordered impostors array
  75357. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75358. });
  75359. //check for collisions
  75360. var contact = this.world.contacts;
  75361. while (contact !== null) {
  75362. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75363. contact = contact.next;
  75364. continue;
  75365. }
  75366. //is this body colliding with any other? get the impostor
  75367. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75368. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75369. if (!mainImpostor || !collidingImpostor) {
  75370. contact = contact.next;
  75371. continue;
  75372. }
  75373. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75374. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75375. contact = contact.next;
  75376. }
  75377. };
  75378. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75379. var mass = impostor.physicsBody.massInfo.mass;
  75380. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75381. };
  75382. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75383. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75384. this.applyImpulse(impostor, force, contactPoint);
  75385. };
  75386. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75387. var _this = this;
  75388. //parent-child relationship. Does this impostor has a parent impostor?
  75389. if (impostor.parent) {
  75390. if (impostor.physicsBody) {
  75391. this.removePhysicsBody(impostor);
  75392. //TODO is that needed?
  75393. impostor.forceUpdate();
  75394. }
  75395. return;
  75396. }
  75397. if (impostor.isBodyInitRequired()) {
  75398. var bodyConfig = {
  75399. name: impostor.uniqueId,
  75400. //Oimo must have mass, also for static objects.
  75401. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75402. size: [],
  75403. type: [],
  75404. pos: [],
  75405. rot: [],
  75406. move: impostor.getParam("mass") !== 0,
  75407. //Supporting older versions of Oimo
  75408. world: this.world
  75409. };
  75410. var impostors = [impostor];
  75411. var addToArray = function (parent) {
  75412. if (!parent.getChildMeshes)
  75413. return;
  75414. parent.getChildMeshes().forEach(function (m) {
  75415. if (m.physicsImpostor) {
  75416. impostors.push(m.physicsImpostor);
  75417. //m.physicsImpostor._init();
  75418. }
  75419. });
  75420. };
  75421. addToArray(impostor.object);
  75422. var checkWithEpsilon_1 = function (value) {
  75423. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75424. };
  75425. impostors.forEach(function (i) {
  75426. if (!impostor.object.rotationQuaternion) {
  75427. return;
  75428. }
  75429. //get the correct bounding box
  75430. var oldQuaternion = i.object.rotationQuaternion;
  75431. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75432. x: impostor.object.rotationQuaternion.x,
  75433. y: impostor.object.rotationQuaternion.y,
  75434. z: impostor.object.rotationQuaternion.z,
  75435. s: impostor.object.rotationQuaternion.w
  75436. });
  75437. var extendSize = i.getObjectExtendSize();
  75438. if (i === impostor) {
  75439. var center = impostor.getObjectCenter();
  75440. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75441. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75442. //Can also use Array.prototype.push.apply
  75443. bodyConfig.pos.push(center.x);
  75444. bodyConfig.pos.push(center.y);
  75445. bodyConfig.pos.push(center.z);
  75446. //tmp solution
  75447. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75448. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75449. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75450. }
  75451. else {
  75452. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75453. bodyConfig.pos.push(localPosition.x);
  75454. bodyConfig.pos.push(localPosition.y);
  75455. bodyConfig.pos.push(localPosition.z);
  75456. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75457. bodyConfig.rot.push(0);
  75458. bodyConfig.rot.push(0);
  75459. bodyConfig.rot.push(0);
  75460. }
  75461. // register mesh
  75462. switch (i.type) {
  75463. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75464. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75465. case BABYLON.PhysicsImpostor.SphereImpostor:
  75466. var radiusX = extendSize.x;
  75467. var radiusY = extendSize.y;
  75468. var radiusZ = extendSize.z;
  75469. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75470. bodyConfig.type.push('sphere');
  75471. //due to the way oimo works with compounds, add 3 times
  75472. bodyConfig.size.push(size);
  75473. bodyConfig.size.push(size);
  75474. bodyConfig.size.push(size);
  75475. break;
  75476. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75477. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75478. var sizeY = checkWithEpsilon_1(extendSize.y);
  75479. bodyConfig.type.push('cylinder');
  75480. bodyConfig.size.push(sizeX);
  75481. bodyConfig.size.push(sizeY);
  75482. //due to the way oimo works with compounds, add one more value.
  75483. bodyConfig.size.push(sizeY);
  75484. break;
  75485. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75486. case BABYLON.PhysicsImpostor.BoxImpostor:
  75487. default:
  75488. var sizeX = checkWithEpsilon_1(extendSize.x);
  75489. var sizeY = checkWithEpsilon_1(extendSize.y);
  75490. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75491. bodyConfig.type.push('box');
  75492. bodyConfig.size.push(sizeX);
  75493. bodyConfig.size.push(sizeY);
  75494. bodyConfig.size.push(sizeZ);
  75495. break;
  75496. }
  75497. //actually not needed, but hey...
  75498. i.object.rotationQuaternion = oldQuaternion;
  75499. });
  75500. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75501. }
  75502. else {
  75503. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75504. }
  75505. impostor.setDeltaPosition(this._tmpPositionVector);
  75506. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75507. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75508. };
  75509. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75510. //impostor.physicsBody.dispose();
  75511. //Same as : (older oimo versions)
  75512. this.world.removeRigidBody(impostor.physicsBody);
  75513. };
  75514. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75515. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75516. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75517. if (!mainBody || !connectedBody) {
  75518. return;
  75519. }
  75520. var jointData = impostorJoint.joint.jointData;
  75521. var options = jointData.nativeParams || {};
  75522. var type;
  75523. var nativeJointData = {
  75524. body1: mainBody,
  75525. body2: connectedBody,
  75526. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75527. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75528. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75529. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  75530. min: options.min,
  75531. max: options.max,
  75532. collision: options.collision || jointData.collision,
  75533. spring: options.spring,
  75534. //supporting older version of Oimo
  75535. world: this.world
  75536. };
  75537. switch (impostorJoint.joint.type) {
  75538. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75539. type = "jointBall";
  75540. break;
  75541. case BABYLON.PhysicsJoint.SpringJoint:
  75542. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  75543. var springData = jointData;
  75544. nativeJointData.min = springData.length || nativeJointData.min;
  75545. //Max should also be set, just make sure it is at least min
  75546. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  75547. case BABYLON.PhysicsJoint.DistanceJoint:
  75548. type = "jointDistance";
  75549. nativeJointData.max = jointData.maxDistance;
  75550. break;
  75551. case BABYLON.PhysicsJoint.PrismaticJoint:
  75552. type = "jointPrisme";
  75553. break;
  75554. case BABYLON.PhysicsJoint.SliderJoint:
  75555. type = "jointSlide";
  75556. break;
  75557. case BABYLON.PhysicsJoint.WheelJoint:
  75558. type = "jointWheel";
  75559. break;
  75560. case BABYLON.PhysicsJoint.HingeJoint:
  75561. default:
  75562. type = "jointHinge";
  75563. break;
  75564. }
  75565. nativeJointData.type = type;
  75566. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  75567. };
  75568. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75569. //Bug in Oimo prevents us from disposing a joint in the playground
  75570. //joint.joint.physicsJoint.dispose();
  75571. //So we will bruteforce it!
  75572. try {
  75573. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  75574. }
  75575. catch (e) {
  75576. BABYLON.Tools.Warn(e);
  75577. }
  75578. };
  75579. OimoJSPlugin.prototype.isSupported = function () {
  75580. return this.BJSOIMO !== undefined;
  75581. };
  75582. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75583. if (!impostor.physicsBody.sleeping) {
  75584. //TODO check that
  75585. if (impostor.physicsBody.shapes.next) {
  75586. var parentShape = this._getLastShape(impostor.physicsBody);
  75587. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  75588. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  75589. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  75590. }
  75591. else {
  75592. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  75593. }
  75594. if (impostor.object.rotationQuaternion) {
  75595. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  75596. impostor.object.rotationQuaternion.normalize();
  75597. }
  75598. }
  75599. };
  75600. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75601. var body = impostor.physicsBody;
  75602. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  75603. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  75604. body.syncShapes();
  75605. body.awake();
  75606. };
  75607. OimoJSPlugin.prototype._getLastShape = function (body) {
  75608. var lastShape = body.shapes;
  75609. while (lastShape.next) {
  75610. lastShape = lastShape.next;
  75611. }
  75612. return lastShape;
  75613. };
  75614. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75615. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  75616. };
  75617. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75618. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  75619. };
  75620. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75621. var v = impostor.physicsBody.linearVelocity;
  75622. if (!v) {
  75623. return null;
  75624. }
  75625. return new BABYLON.Vector3(v.x, v.y, v.z);
  75626. };
  75627. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75628. var v = impostor.physicsBody.angularVelocity;
  75629. if (!v) {
  75630. return null;
  75631. }
  75632. return new BABYLON.Vector3(v.x, v.y, v.z);
  75633. };
  75634. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75635. var staticBody = mass === 0;
  75636. //this will actually set the body's density and not its mass.
  75637. //But this is how oimo treats the mass variable.
  75638. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  75639. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  75640. };
  75641. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  75642. return impostor.physicsBody.shapes.density;
  75643. };
  75644. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  75645. return impostor.physicsBody.shapes.friction;
  75646. };
  75647. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75648. impostor.physicsBody.shapes.friction = friction;
  75649. };
  75650. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75651. return impostor.physicsBody.shapes.restitution;
  75652. };
  75653. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75654. impostor.physicsBody.shapes.restitution = restitution;
  75655. };
  75656. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  75657. impostor.physicsBody.sleep();
  75658. };
  75659. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  75660. impostor.physicsBody.awake();
  75661. };
  75662. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75663. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  75664. if (minDistance !== void 0) {
  75665. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  75666. }
  75667. };
  75668. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75669. //TODO separate rotational and transational motors.
  75670. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75671. if (motor) {
  75672. motor.setMotor(speed, maxForce);
  75673. }
  75674. };
  75675. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  75676. //TODO separate rotational and transational motors.
  75677. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  75678. if (motor) {
  75679. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  75680. }
  75681. };
  75682. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75683. var body = impostor.physicsBody;
  75684. mesh.position.x = body.position.x;
  75685. mesh.position.y = body.position.y;
  75686. mesh.position.z = body.position.z;
  75687. if (mesh.rotationQuaternion) {
  75688. mesh.rotationQuaternion.x = body.orientation.x;
  75689. mesh.rotationQuaternion.y = body.orientation.y;
  75690. mesh.rotationQuaternion.z = body.orientation.z;
  75691. mesh.rotationQuaternion.w = body.orientation.s;
  75692. }
  75693. };
  75694. OimoJSPlugin.prototype.getRadius = function (impostor) {
  75695. return impostor.physicsBody.shapes.radius;
  75696. };
  75697. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75698. var shape = impostor.physicsBody.shapes;
  75699. result.x = shape.halfWidth * 2;
  75700. result.y = shape.halfHeight * 2;
  75701. result.z = shape.halfDepth * 2;
  75702. };
  75703. OimoJSPlugin.prototype.dispose = function () {
  75704. this.world.clear();
  75705. };
  75706. return OimoJSPlugin;
  75707. }());
  75708. BABYLON.OimoJSPlugin = OimoJSPlugin;
  75709. })(BABYLON || (BABYLON = {}));
  75710. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  75711. var BABYLON;
  75712. (function (BABYLON) {
  75713. /*
  75714. * Based on jsTGALoader - Javascript loader for TGA file
  75715. * By Vincent Thibault
  75716. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  75717. */
  75718. var TGATools = /** @class */ (function () {
  75719. function TGATools() {
  75720. }
  75721. TGATools.GetTGAHeader = function (data) {
  75722. var offset = 0;
  75723. var header = {
  75724. id_length: data[offset++],
  75725. colormap_type: data[offset++],
  75726. image_type: data[offset++],
  75727. colormap_index: data[offset++] | data[offset++] << 8,
  75728. colormap_length: data[offset++] | data[offset++] << 8,
  75729. colormap_size: data[offset++],
  75730. origin: [
  75731. data[offset++] | data[offset++] << 8,
  75732. data[offset++] | data[offset++] << 8
  75733. ],
  75734. width: data[offset++] | data[offset++] << 8,
  75735. height: data[offset++] | data[offset++] << 8,
  75736. pixel_size: data[offset++],
  75737. flags: data[offset++]
  75738. };
  75739. return header;
  75740. };
  75741. TGATools.UploadContent = function (gl, data) {
  75742. // Not enough data to contain header ?
  75743. if (data.length < 19) {
  75744. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  75745. return;
  75746. }
  75747. // Read Header
  75748. var offset = 18;
  75749. var header = TGATools.GetTGAHeader(data);
  75750. // Assume it's a valid Targa file.
  75751. if (header.id_length + offset > data.length) {
  75752. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  75753. return;
  75754. }
  75755. // Skip not needed data
  75756. offset += header.id_length;
  75757. var use_rle = false;
  75758. var use_pal = false;
  75759. var use_grey = false;
  75760. // Get some informations.
  75761. switch (header.image_type) {
  75762. case TGATools._TYPE_RLE_INDEXED:
  75763. use_rle = true;
  75764. case TGATools._TYPE_INDEXED:
  75765. use_pal = true;
  75766. break;
  75767. case TGATools._TYPE_RLE_RGB:
  75768. use_rle = true;
  75769. case TGATools._TYPE_RGB:
  75770. // use_rgb = true;
  75771. break;
  75772. case TGATools._TYPE_RLE_GREY:
  75773. use_rle = true;
  75774. case TGATools._TYPE_GREY:
  75775. use_grey = true;
  75776. break;
  75777. }
  75778. var pixel_data;
  75779. // var numAlphaBits = header.flags & 0xf;
  75780. var pixel_size = header.pixel_size >> 3;
  75781. var pixel_total = header.width * header.height * pixel_size;
  75782. // Read palettes
  75783. var palettes;
  75784. if (use_pal) {
  75785. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  75786. }
  75787. // Read LRE
  75788. if (use_rle) {
  75789. pixel_data = new Uint8Array(pixel_total);
  75790. var c, count, i;
  75791. var localOffset = 0;
  75792. var pixels = new Uint8Array(pixel_size);
  75793. while (offset < pixel_total && localOffset < pixel_total) {
  75794. c = data[offset++];
  75795. count = (c & 0x7f) + 1;
  75796. // RLE pixels
  75797. if (c & 0x80) {
  75798. // Bind pixel tmp array
  75799. for (i = 0; i < pixel_size; ++i) {
  75800. pixels[i] = data[offset++];
  75801. }
  75802. // Copy pixel array
  75803. for (i = 0; i < count; ++i) {
  75804. pixel_data.set(pixels, localOffset + i * pixel_size);
  75805. }
  75806. localOffset += pixel_size * count;
  75807. }
  75808. else {
  75809. count *= pixel_size;
  75810. for (i = 0; i < count; ++i) {
  75811. pixel_data[localOffset + i] = data[offset++];
  75812. }
  75813. localOffset += count;
  75814. }
  75815. }
  75816. }
  75817. else {
  75818. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  75819. }
  75820. // Load to texture
  75821. var x_start, y_start, x_step, y_step, y_end, x_end;
  75822. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  75823. default:
  75824. case TGATools._ORIGIN_UL:
  75825. x_start = 0;
  75826. x_step = 1;
  75827. x_end = header.width;
  75828. y_start = 0;
  75829. y_step = 1;
  75830. y_end = header.height;
  75831. break;
  75832. case TGATools._ORIGIN_BL:
  75833. x_start = 0;
  75834. x_step = 1;
  75835. x_end = header.width;
  75836. y_start = header.height - 1;
  75837. y_step = -1;
  75838. y_end = -1;
  75839. break;
  75840. case TGATools._ORIGIN_UR:
  75841. x_start = header.width - 1;
  75842. x_step = -1;
  75843. x_end = -1;
  75844. y_start = 0;
  75845. y_step = 1;
  75846. y_end = header.height;
  75847. break;
  75848. case TGATools._ORIGIN_BR:
  75849. x_start = header.width - 1;
  75850. x_step = -1;
  75851. x_end = -1;
  75852. y_start = header.height - 1;
  75853. y_step = -1;
  75854. y_end = -1;
  75855. break;
  75856. }
  75857. // Load the specify method
  75858. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  75859. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  75860. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  75861. };
  75862. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75863. var image = pixel_data, colormap = palettes;
  75864. var width = header.width, height = header.height;
  75865. var color, i = 0, x, y;
  75866. var imageData = new Uint8Array(width * height * 4);
  75867. for (y = y_start; y !== y_end; y += y_step) {
  75868. for (x = x_start; x !== x_end; x += x_step, i++) {
  75869. color = image[i];
  75870. imageData[(x + width * y) * 4 + 3] = 255;
  75871. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  75872. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  75873. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  75874. }
  75875. }
  75876. return imageData;
  75877. };
  75878. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75879. var image = pixel_data;
  75880. var width = header.width, height = header.height;
  75881. var color, i = 0, x, y;
  75882. var imageData = new Uint8Array(width * height * 4);
  75883. for (y = y_start; y !== y_end; y += y_step) {
  75884. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75885. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  75886. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  75887. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  75888. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  75889. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  75890. }
  75891. }
  75892. return imageData;
  75893. };
  75894. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75895. var image = pixel_data;
  75896. var width = header.width, height = header.height;
  75897. var i = 0, x, y;
  75898. var imageData = new Uint8Array(width * height * 4);
  75899. for (y = y_start; y !== y_end; y += y_step) {
  75900. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  75901. imageData[(x + width * y) * 4 + 3] = 255;
  75902. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75903. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75904. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75905. }
  75906. }
  75907. return imageData;
  75908. };
  75909. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75910. var image = pixel_data;
  75911. var width = header.width, height = header.height;
  75912. var i = 0, x, y;
  75913. var imageData = new Uint8Array(width * height * 4);
  75914. for (y = y_start; y !== y_end; y += y_step) {
  75915. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  75916. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75917. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  75918. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  75919. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  75920. }
  75921. }
  75922. return imageData;
  75923. };
  75924. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75925. var image = pixel_data;
  75926. var width = header.width, height = header.height;
  75927. var color, i = 0, x, y;
  75928. var imageData = new Uint8Array(width * height * 4);
  75929. for (y = y_start; y !== y_end; y += y_step) {
  75930. for (x = x_start; x !== x_end; x += x_step, i++) {
  75931. color = image[i];
  75932. imageData[(x + width * y) * 4 + 0] = color;
  75933. imageData[(x + width * y) * 4 + 1] = color;
  75934. imageData[(x + width * y) * 4 + 2] = color;
  75935. imageData[(x + width * y) * 4 + 3] = 255;
  75936. }
  75937. }
  75938. return imageData;
  75939. };
  75940. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  75941. var image = pixel_data;
  75942. var width = header.width, height = header.height;
  75943. var i = 0, x, y;
  75944. var imageData = new Uint8Array(width * height * 4);
  75945. for (y = y_start; y !== y_end; y += y_step) {
  75946. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  75947. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  75948. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  75949. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  75950. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  75951. }
  75952. }
  75953. return imageData;
  75954. };
  75955. //private static _TYPE_NO_DATA = 0;
  75956. TGATools._TYPE_INDEXED = 1;
  75957. TGATools._TYPE_RGB = 2;
  75958. TGATools._TYPE_GREY = 3;
  75959. TGATools._TYPE_RLE_INDEXED = 9;
  75960. TGATools._TYPE_RLE_RGB = 10;
  75961. TGATools._TYPE_RLE_GREY = 11;
  75962. TGATools._ORIGIN_MASK = 0x30;
  75963. TGATools._ORIGIN_SHIFT = 0x04;
  75964. TGATools._ORIGIN_BL = 0x00;
  75965. TGATools._ORIGIN_BR = 0x01;
  75966. TGATools._ORIGIN_UL = 0x02;
  75967. TGATools._ORIGIN_UR = 0x03;
  75968. return TGATools;
  75969. }());
  75970. BABYLON.TGATools = TGATools;
  75971. })(BABYLON || (BABYLON = {}));
  75972. //# sourceMappingURL=babylon.tga.js.map
  75973. var BABYLON;
  75974. (function (BABYLON) {
  75975. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  75976. // All values and structures referenced from:
  75977. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  75978. var DDS_MAGIC = 0x20534444;
  75979. var
  75980. //DDSD_CAPS = 0x1,
  75981. //DDSD_HEIGHT = 0x2,
  75982. //DDSD_WIDTH = 0x4,
  75983. //DDSD_PITCH = 0x8,
  75984. //DDSD_PIXELFORMAT = 0x1000,
  75985. DDSD_MIPMAPCOUNT = 0x20000;
  75986. //DDSD_LINEARSIZE = 0x80000,
  75987. //DDSD_DEPTH = 0x800000;
  75988. // var DDSCAPS_COMPLEX = 0x8,
  75989. // DDSCAPS_MIPMAP = 0x400000,
  75990. // DDSCAPS_TEXTURE = 0x1000;
  75991. var DDSCAPS2_CUBEMAP = 0x200;
  75992. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  75993. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  75994. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  75995. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  75996. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  75997. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  75998. // DDSCAPS2_VOLUME = 0x200000;
  75999. var
  76000. //DDPF_ALPHAPIXELS = 0x1,
  76001. //DDPF_ALPHA = 0x2,
  76002. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  76003. //DDPF_YUV = 0x200,
  76004. DDPF_LUMINANCE = 0x20000;
  76005. function FourCCToInt32(value) {
  76006. return value.charCodeAt(0) +
  76007. (value.charCodeAt(1) << 8) +
  76008. (value.charCodeAt(2) << 16) +
  76009. (value.charCodeAt(3) << 24);
  76010. }
  76011. function Int32ToFourCC(value) {
  76012. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  76013. }
  76014. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  76015. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  76016. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  76017. var FOURCC_DX10 = FourCCToInt32("DX10");
  76018. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  76019. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  76020. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  76021. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  76022. var headerLengthInt = 31; // The header length in 32 bit ints
  76023. // Offsets into the header array
  76024. var off_magic = 0;
  76025. var off_size = 1;
  76026. var off_flags = 2;
  76027. var off_height = 3;
  76028. var off_width = 4;
  76029. var off_mipmapCount = 7;
  76030. var off_pfFlags = 20;
  76031. var off_pfFourCC = 21;
  76032. var off_RGBbpp = 22;
  76033. var off_RMask = 23;
  76034. var off_GMask = 24;
  76035. var off_BMask = 25;
  76036. var off_AMask = 26;
  76037. // var off_caps1 = 27;
  76038. var off_caps2 = 28;
  76039. // var off_caps3 = 29;
  76040. // var off_caps4 = 30;
  76041. var off_dxgiFormat = 32;
  76042. ;
  76043. var DDSTools = /** @class */ (function () {
  76044. function DDSTools() {
  76045. }
  76046. DDSTools.GetDDSInfo = function (arrayBuffer) {
  76047. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76048. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  76049. var mipmapCount = 1;
  76050. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  76051. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76052. }
  76053. var fourCC = header[off_pfFourCC];
  76054. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  76055. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76056. switch (fourCC) {
  76057. case FOURCC_D3DFMT_R16G16B16A16F:
  76058. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76059. break;
  76060. case FOURCC_D3DFMT_R32G32B32A32F:
  76061. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76062. break;
  76063. case FOURCC_DX10:
  76064. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  76065. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76066. break;
  76067. }
  76068. }
  76069. return {
  76070. width: header[off_width],
  76071. height: header[off_height],
  76072. mipmapCount: mipmapCount,
  76073. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  76074. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  76075. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  76076. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  76077. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  76078. dxgiFormat: dxgiFormat,
  76079. textureType: textureType
  76080. };
  76081. };
  76082. DDSTools._ToHalfFloat = function (value) {
  76083. if (!DDSTools._FloatView) {
  76084. DDSTools._FloatView = new Float32Array(1);
  76085. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  76086. }
  76087. DDSTools._FloatView[0] = value;
  76088. var x = DDSTools._Int32View[0];
  76089. var bits = (x >> 16) & 0x8000; /* Get the sign */
  76090. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  76091. var e = (x >> 23) & 0xff; /* Using int is faster here */
  76092. /* If zero, or denormal, or exponent underflows too much for a denormal
  76093. * half, return signed zero. */
  76094. if (e < 103) {
  76095. return bits;
  76096. }
  76097. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  76098. if (e > 142) {
  76099. bits |= 0x7c00;
  76100. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  76101. * not Inf, so make sure we set one mantissa bit too. */
  76102. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  76103. return bits;
  76104. }
  76105. /* If exponent underflows but not too much, return a denormal */
  76106. if (e < 113) {
  76107. m |= 0x0800;
  76108. /* Extra rounding may overflow and set mantissa to 0 and exponent
  76109. * to 1, which is OK. */
  76110. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  76111. return bits;
  76112. }
  76113. bits |= ((e - 112) << 10) | (m >> 1);
  76114. bits += m & 1;
  76115. return bits;
  76116. };
  76117. DDSTools._FromHalfFloat = function (value) {
  76118. var s = (value & 0x8000) >> 15;
  76119. var e = (value & 0x7C00) >> 10;
  76120. var f = value & 0x03FF;
  76121. if (e === 0) {
  76122. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  76123. }
  76124. else if (e == 0x1F) {
  76125. return f ? NaN : ((s ? -1 : 1) * Infinity);
  76126. }
  76127. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  76128. };
  76129. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76130. var destArray = new Float32Array(dataLength);
  76131. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76132. var index = 0;
  76133. for (var y = 0; y < height; y++) {
  76134. for (var x = 0; x < width; x++) {
  76135. var srcPos = (x + y * width) * 4;
  76136. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  76137. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  76138. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  76139. if (DDSTools.StoreLODInAlphaChannel) {
  76140. destArray[index + 3] = lod;
  76141. }
  76142. else {
  76143. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  76144. }
  76145. index += 4;
  76146. }
  76147. }
  76148. return destArray;
  76149. };
  76150. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76151. if (DDSTools.StoreLODInAlphaChannel) {
  76152. var destArray = new Uint16Array(dataLength);
  76153. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76154. var index = 0;
  76155. for (var y = 0; y < height; y++) {
  76156. for (var x = 0; x < width; x++) {
  76157. var srcPos = (x + y * width) * 4;
  76158. destArray[index] = srcData[srcPos];
  76159. destArray[index + 1] = srcData[srcPos + 1];
  76160. destArray[index + 2] = srcData[srcPos + 2];
  76161. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  76162. index += 4;
  76163. }
  76164. }
  76165. return destArray;
  76166. }
  76167. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  76168. };
  76169. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76170. if (DDSTools.StoreLODInAlphaChannel) {
  76171. var destArray = new Float32Array(dataLength);
  76172. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76173. var index = 0;
  76174. for (var y = 0; y < height; y++) {
  76175. for (var x = 0; x < width; x++) {
  76176. var srcPos = (x + y * width) * 4;
  76177. destArray[index] = srcData[srcPos];
  76178. destArray[index + 1] = srcData[srcPos + 1];
  76179. destArray[index + 2] = srcData[srcPos + 2];
  76180. destArray[index + 3] = lod;
  76181. index += 4;
  76182. }
  76183. }
  76184. return destArray;
  76185. }
  76186. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  76187. };
  76188. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76189. var destArray = new Uint8Array(dataLength);
  76190. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76191. var index = 0;
  76192. for (var y = 0; y < height; y++) {
  76193. for (var x = 0; x < width; x++) {
  76194. var srcPos = (x + y * width) * 4;
  76195. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  76196. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  76197. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  76198. if (DDSTools.StoreLODInAlphaChannel) {
  76199. destArray[index + 3] = lod;
  76200. }
  76201. else {
  76202. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  76203. }
  76204. index += 4;
  76205. }
  76206. }
  76207. return destArray;
  76208. };
  76209. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76210. var destArray = new Uint8Array(dataLength);
  76211. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76212. var index = 0;
  76213. for (var y = 0; y < height; y++) {
  76214. for (var x = 0; x < width; x++) {
  76215. var srcPos = (x + y * width) * 4;
  76216. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  76217. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  76218. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  76219. if (DDSTools.StoreLODInAlphaChannel) {
  76220. destArray[index + 3] = lod;
  76221. }
  76222. else {
  76223. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  76224. }
  76225. index += 4;
  76226. }
  76227. }
  76228. return destArray;
  76229. };
  76230. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  76231. var byteArray = new Uint8Array(dataLength);
  76232. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76233. var index = 0;
  76234. for (var y = 0; y < height; y++) {
  76235. for (var x = 0; x < width; x++) {
  76236. var srcPos = (x + y * width) * 4;
  76237. byteArray[index] = srcData[srcPos + rOffset];
  76238. byteArray[index + 1] = srcData[srcPos + gOffset];
  76239. byteArray[index + 2] = srcData[srcPos + bOffset];
  76240. byteArray[index + 3] = srcData[srcPos + aOffset];
  76241. index += 4;
  76242. }
  76243. }
  76244. return byteArray;
  76245. };
  76246. DDSTools._ExtractLongWordOrder = function (value) {
  76247. if (value === 0 || value === 255 || value === -16777216) {
  76248. return 0;
  76249. }
  76250. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  76251. };
  76252. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  76253. var byteArray = new Uint8Array(dataLength);
  76254. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76255. var index = 0;
  76256. for (var y = 0; y < height; y++) {
  76257. for (var x = 0; x < width; x++) {
  76258. var srcPos = (x + y * width) * 3;
  76259. byteArray[index] = srcData[srcPos + rOffset];
  76260. byteArray[index + 1] = srcData[srcPos + gOffset];
  76261. byteArray[index + 2] = srcData[srcPos + bOffset];
  76262. index += 3;
  76263. }
  76264. }
  76265. return byteArray;
  76266. };
  76267. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  76268. var byteArray = new Uint8Array(dataLength);
  76269. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76270. var index = 0;
  76271. for (var y = 0; y < height; y++) {
  76272. for (var x = 0; x < width; x++) {
  76273. var srcPos = (x + y * width);
  76274. byteArray[index] = srcData[srcPos];
  76275. index++;
  76276. }
  76277. }
  76278. return byteArray;
  76279. };
  76280. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  76281. if (lodIndex === void 0) { lodIndex = -1; }
  76282. var ext = engine.getCaps().s3tc;
  76283. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76284. var fourCC, width, height, dataLength = 0, dataOffset;
  76285. var byteArray, mipmapCount, mip;
  76286. var internalFormat = 0;
  76287. var format = 0;
  76288. var blockBytes = 1;
  76289. if (header[off_magic] !== DDS_MAGIC) {
  76290. BABYLON.Tools.Error("Invalid magic number in DDS header");
  76291. return;
  76292. }
  76293. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  76294. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  76295. return;
  76296. }
  76297. if (info.isCompressed && !ext) {
  76298. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  76299. return;
  76300. }
  76301. var bpp = header[off_RGBbpp];
  76302. dataOffset = header[off_size] + 4;
  76303. var computeFormats = false;
  76304. if (info.isFourCC) {
  76305. fourCC = header[off_pfFourCC];
  76306. switch (fourCC) {
  76307. case FOURCC_DXT1:
  76308. blockBytes = 8;
  76309. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  76310. break;
  76311. case FOURCC_DXT3:
  76312. blockBytes = 16;
  76313. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  76314. break;
  76315. case FOURCC_DXT5:
  76316. blockBytes = 16;
  76317. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  76318. break;
  76319. case FOURCC_D3DFMT_R16G16B16A16F:
  76320. computeFormats = true;
  76321. break;
  76322. case FOURCC_D3DFMT_R32G32B32A32F:
  76323. computeFormats = true;
  76324. break;
  76325. case FOURCC_DX10:
  76326. // There is an additionnal header so dataOffset need to be changed
  76327. dataOffset += 5 * 4; // 5 uints
  76328. var supported = false;
  76329. switch (info.dxgiFormat) {
  76330. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  76331. computeFormats = true;
  76332. supported = true;
  76333. break;
  76334. case DXGI_FORMAT_B8G8R8X8_UNORM:
  76335. info.isRGB = true;
  76336. info.isFourCC = false;
  76337. bpp = 32;
  76338. supported = true;
  76339. break;
  76340. }
  76341. if (supported) {
  76342. break;
  76343. }
  76344. default:
  76345. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76346. return;
  76347. }
  76348. }
  76349. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76350. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76351. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76352. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76353. if (computeFormats) {
  76354. format = engine._getWebGLTextureType(info.textureType);
  76355. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76356. }
  76357. mipmapCount = 1;
  76358. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76359. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76360. }
  76361. for (var face = 0; face < faces; face++) {
  76362. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76363. width = header[off_width];
  76364. height = header[off_height];
  76365. for (mip = 0; mip < mipmapCount; ++mip) {
  76366. if (lodIndex === -1 || lodIndex === mip) {
  76367. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76368. var i = (lodIndex === -1) ? mip : 0;
  76369. if (!info.isCompressed && info.isFourCC) {
  76370. dataLength = width * height * 4;
  76371. var floatArray = null;
  76372. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76373. if (bpp === 128) {
  76374. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76375. }
  76376. else if (bpp === 64) {
  76377. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76378. }
  76379. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76380. format = engine._getWebGLTextureType(info.textureType);
  76381. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76382. }
  76383. else {
  76384. if (bpp === 128) {
  76385. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76386. }
  76387. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76388. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76389. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76390. format = engine._getWebGLTextureType(info.textureType);
  76391. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76392. }
  76393. else {
  76394. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76395. }
  76396. }
  76397. if (floatArray) {
  76398. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76399. }
  76400. }
  76401. else if (info.isRGB) {
  76402. if (bpp === 24) {
  76403. dataLength = width * height * 3;
  76404. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76405. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76406. }
  76407. else {
  76408. dataLength = width * height * 4;
  76409. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76410. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76411. }
  76412. }
  76413. else if (info.isLuminance) {
  76414. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76415. var unpaddedRowSize = width;
  76416. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76417. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76418. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76419. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76420. }
  76421. else {
  76422. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76423. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76424. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76425. }
  76426. }
  76427. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76428. width *= 0.5;
  76429. height *= 0.5;
  76430. width = Math.max(1.0, width);
  76431. height = Math.max(1.0, height);
  76432. }
  76433. if (currentFace !== undefined) {
  76434. // Loading a single face
  76435. break;
  76436. }
  76437. }
  76438. };
  76439. DDSTools.StoreLODInAlphaChannel = false;
  76440. return DDSTools;
  76441. }());
  76442. BABYLON.DDSTools = DDSTools;
  76443. })(BABYLON || (BABYLON = {}));
  76444. //# sourceMappingURL=babylon.dds.js.map
  76445. var BABYLON;
  76446. (function (BABYLON) {
  76447. /**
  76448. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76449. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76450. */
  76451. var KhronosTextureContainer = /** @class */ (function () {
  76452. /**
  76453. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76454. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76455. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76456. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76457. */
  76458. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76459. this.arrayBuffer = arrayBuffer;
  76460. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76461. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76462. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76463. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76464. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76465. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76466. BABYLON.Tools.Error("texture missing KTX identifier");
  76467. return;
  76468. }
  76469. // load the reset of the header in native 32 bit int
  76470. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76471. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76472. var oppositeEndianess = header[0] === 0x01020304;
  76473. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76474. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76475. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76476. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76477. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76478. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76479. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76480. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76481. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76482. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76483. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76484. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76485. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76486. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76487. if (this.glType !== 0) {
  76488. BABYLON.Tools.Error("only compressed formats currently supported");
  76489. return;
  76490. }
  76491. else {
  76492. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76493. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76494. }
  76495. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76496. BABYLON.Tools.Error("only 2D textures currently supported");
  76497. return;
  76498. }
  76499. if (this.numberOfArrayElements !== 0) {
  76500. BABYLON.Tools.Error("texture arrays not currently supported");
  76501. return;
  76502. }
  76503. if (this.numberOfFaces !== facesExpected) {
  76504. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76505. return;
  76506. }
  76507. // we now have a completely validated file, so could use existence of loadType as success
  76508. // would need to make this more elaborate & adjust checks above to support more than one load type
  76509. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76510. }
  76511. // not as fast hardware based, but will probably never need to use
  76512. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76513. return ((val & 0xFF) << 24)
  76514. | ((val & 0xFF00) << 8)
  76515. | ((val >> 8) & 0xFF00)
  76516. | ((val >> 24) & 0xFF);
  76517. };
  76518. /**
  76519. * It is assumed that the texture has already been created & is currently bound
  76520. */
  76521. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76522. switch (this.loadType) {
  76523. case KhronosTextureContainer.COMPRESSED_2D:
  76524. this._upload2DCompressedLevels(gl, loadMipmaps);
  76525. break;
  76526. case KhronosTextureContainer.TEX_2D:
  76527. case KhronosTextureContainer.COMPRESSED_3D:
  76528. case KhronosTextureContainer.TEX_3D:
  76529. }
  76530. };
  76531. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  76532. // initialize width & height for level 1
  76533. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  76534. var width = this.pixelWidth;
  76535. var height = this.pixelHeight;
  76536. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  76537. for (var level = 0; level < mipmapCount; level++) {
  76538. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  76539. for (var face = 0; face < this.numberOfFaces; face++) {
  76540. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  76541. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  76542. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  76543. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  76544. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  76545. }
  76546. width = Math.max(1.0, width * 0.5);
  76547. height = Math.max(1.0, height * 0.5);
  76548. }
  76549. };
  76550. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  76551. // load types
  76552. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  76553. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  76554. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  76555. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  76556. return KhronosTextureContainer;
  76557. }());
  76558. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  76559. })(BABYLON || (BABYLON = {}));
  76560. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  76561. var BABYLON;
  76562. (function (BABYLON) {
  76563. var Debug = /** @class */ (function () {
  76564. function Debug() {
  76565. }
  76566. Debug.AxesViewer = /** @class */ (function () {
  76567. function AxesViewer(scene, scaleLines) {
  76568. if (scaleLines === void 0) { scaleLines = 1; }
  76569. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76570. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76571. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76572. this.scaleLines = 1;
  76573. this.scaleLines = scaleLines;
  76574. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  76575. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  76576. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  76577. this._xmesh.renderingGroupId = 2;
  76578. this._ymesh.renderingGroupId = 2;
  76579. this._zmesh.renderingGroupId = 2;
  76580. this._xmesh.material.checkReadyOnlyOnce = true;
  76581. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  76582. this._ymesh.material.checkReadyOnlyOnce = true;
  76583. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  76584. this._zmesh.material.checkReadyOnlyOnce = true;
  76585. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  76586. this.scene = scene;
  76587. }
  76588. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  76589. var scaleLines = this.scaleLines;
  76590. if (this._xmesh) {
  76591. this._xmesh.position.copyFrom(position);
  76592. }
  76593. if (this._ymesh) {
  76594. this._ymesh.position.copyFrom(position);
  76595. }
  76596. if (this._zmesh) {
  76597. this._zmesh.position.copyFrom(position);
  76598. }
  76599. var point2 = this._xline[1];
  76600. point2.x = xaxis.x * scaleLines;
  76601. point2.y = xaxis.y * scaleLines;
  76602. point2.z = xaxis.z * scaleLines;
  76603. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  76604. point2 = this._yline[1];
  76605. point2.x = yaxis.x * scaleLines;
  76606. point2.y = yaxis.y * scaleLines;
  76607. point2.z = yaxis.z * scaleLines;
  76608. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  76609. point2 = this._zline[1];
  76610. point2.x = zaxis.x * scaleLines;
  76611. point2.y = zaxis.y * scaleLines;
  76612. point2.z = zaxis.z * scaleLines;
  76613. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  76614. };
  76615. AxesViewer.prototype.dispose = function () {
  76616. if (this._xmesh) {
  76617. this._xmesh.dispose();
  76618. }
  76619. if (this._ymesh) {
  76620. this._ymesh.dispose();
  76621. }
  76622. if (this._zmesh) {
  76623. this._zmesh.dispose();
  76624. }
  76625. this._xmesh = null;
  76626. this._ymesh = null;
  76627. this._zmesh = null;
  76628. this.scene = null;
  76629. };
  76630. return AxesViewer;
  76631. }());
  76632. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  76633. __extends(BoneAxesViewer, _super);
  76634. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  76635. if (scaleLines === void 0) { scaleLines = 1; }
  76636. var _this = _super.call(this, scene, scaleLines) || this;
  76637. _this.pos = BABYLON.Vector3.Zero();
  76638. _this.xaxis = BABYLON.Vector3.Zero();
  76639. _this.yaxis = BABYLON.Vector3.Zero();
  76640. _this.zaxis = BABYLON.Vector3.Zero();
  76641. _this.mesh = mesh;
  76642. _this.bone = bone;
  76643. return _this;
  76644. }
  76645. BoneAxesViewer.prototype.update = function () {
  76646. if (!this.mesh || !this.bone) {
  76647. return;
  76648. }
  76649. var bone = this.bone;
  76650. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  76651. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  76652. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  76653. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  76654. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  76655. };
  76656. BoneAxesViewer.prototype.dispose = function () {
  76657. if (this.mesh) {
  76658. this.mesh = null;
  76659. this.bone = null;
  76660. _super.prototype.dispose.call(this);
  76661. }
  76662. };
  76663. return BoneAxesViewer;
  76664. }(Debug.AxesViewer));
  76665. Debug.PhysicsViewer = /** @class */ (function () {
  76666. function PhysicsViewer(scene) {
  76667. this._impostors = [];
  76668. this._meshes = [];
  76669. this._numMeshes = 0;
  76670. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76671. var physicEngine = this._scene.getPhysicsEngine();
  76672. if (physicEngine) {
  76673. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  76674. }
  76675. }
  76676. PhysicsViewer.prototype._updateDebugMeshes = function () {
  76677. var plugin = this._physicsEnginePlugin;
  76678. for (var i = 0; i < this._numMeshes; i++) {
  76679. var impostor = this._impostors[i];
  76680. if (!impostor) {
  76681. continue;
  76682. }
  76683. if (impostor.isDisposed) {
  76684. this.hideImpostor(this._impostors[i--]);
  76685. }
  76686. else {
  76687. var mesh = this._meshes[i];
  76688. if (mesh && plugin) {
  76689. plugin.syncMeshWithImpostor(mesh, impostor);
  76690. }
  76691. }
  76692. }
  76693. };
  76694. PhysicsViewer.prototype.showImpostor = function (impostor) {
  76695. if (!this._scene) {
  76696. return;
  76697. }
  76698. for (var i = 0; i < this._numMeshes; i++) {
  76699. if (this._impostors[i] == impostor) {
  76700. return;
  76701. }
  76702. }
  76703. var debugMesh = this._getDebugMesh(impostor, this._scene);
  76704. if (debugMesh) {
  76705. this._impostors[this._numMeshes] = impostor;
  76706. this._meshes[this._numMeshes] = debugMesh;
  76707. if (this._numMeshes === 0) {
  76708. this._renderFunction = this._updateDebugMeshes.bind(this);
  76709. this._scene.registerBeforeRender(this._renderFunction);
  76710. }
  76711. this._numMeshes++;
  76712. }
  76713. };
  76714. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  76715. if (!impostor || !this._scene) {
  76716. return;
  76717. }
  76718. var removed = false;
  76719. for (var i = 0; i < this._numMeshes; i++) {
  76720. if (this._impostors[i] == impostor) {
  76721. var mesh = this._meshes[i];
  76722. if (!mesh) {
  76723. continue;
  76724. }
  76725. this._scene.removeMesh(mesh);
  76726. mesh.dispose();
  76727. this._numMeshes--;
  76728. if (this._numMeshes > 0) {
  76729. this._meshes[i] = this._meshes[this._numMeshes];
  76730. this._impostors[i] = this._impostors[this._numMeshes];
  76731. this._meshes[this._numMeshes] = null;
  76732. this._impostors[this._numMeshes] = null;
  76733. }
  76734. else {
  76735. this._meshes[0] = null;
  76736. this._impostors[0] = null;
  76737. }
  76738. removed = true;
  76739. break;
  76740. }
  76741. }
  76742. if (removed && this._numMeshes === 0) {
  76743. this._scene.unregisterBeforeRender(this._renderFunction);
  76744. }
  76745. };
  76746. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  76747. if (!this._debugMaterial) {
  76748. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  76749. this._debugMaterial.wireframe = true;
  76750. }
  76751. return this._debugMaterial;
  76752. };
  76753. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  76754. if (!this._debugBoxMesh) {
  76755. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  76756. this._debugBoxMesh.renderingGroupId = 1;
  76757. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76758. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  76759. scene.removeMesh(this._debugBoxMesh);
  76760. }
  76761. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  76762. };
  76763. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  76764. if (!this._debugSphereMesh) {
  76765. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  76766. this._debugSphereMesh.renderingGroupId = 1;
  76767. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  76768. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  76769. scene.removeMesh(this._debugSphereMesh);
  76770. }
  76771. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  76772. };
  76773. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  76774. var mesh = null;
  76775. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  76776. mesh = this._getDebugBoxMesh(scene);
  76777. impostor.getBoxSizeToRef(mesh.scaling);
  76778. }
  76779. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  76780. mesh = this._getDebugSphereMesh(scene);
  76781. var radius = impostor.getRadius();
  76782. mesh.scaling.x = radius * 2;
  76783. mesh.scaling.y = radius * 2;
  76784. mesh.scaling.z = radius * 2;
  76785. }
  76786. return mesh;
  76787. };
  76788. PhysicsViewer.prototype.dispose = function () {
  76789. for (var i = 0; i < this._numMeshes; i++) {
  76790. this.hideImpostor(this._impostors[i]);
  76791. }
  76792. if (this._debugBoxMesh) {
  76793. this._debugBoxMesh.dispose();
  76794. }
  76795. if (this._debugSphereMesh) {
  76796. this._debugSphereMesh.dispose();
  76797. }
  76798. if (this._debugMaterial) {
  76799. this._debugMaterial.dispose();
  76800. }
  76801. this._impostors.length = 0;
  76802. this._scene = null;
  76803. this._physicsEnginePlugin = null;
  76804. };
  76805. return PhysicsViewer;
  76806. }());
  76807. Debug.SkeletonViewer = /** @class */ (function () {
  76808. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  76809. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  76810. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  76811. this.skeleton = skeleton;
  76812. this.mesh = mesh;
  76813. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  76814. this.renderingGroupId = renderingGroupId;
  76815. this.color = BABYLON.Color3.White();
  76816. this._debugLines = new Array();
  76817. this._isEnabled = false;
  76818. this._scene = scene;
  76819. this.update();
  76820. this._renderFunction = this.update.bind(this);
  76821. }
  76822. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  76823. get: function () {
  76824. return this._isEnabled;
  76825. },
  76826. set: function (value) {
  76827. if (this._isEnabled === value) {
  76828. return;
  76829. }
  76830. this._isEnabled = value;
  76831. if (value) {
  76832. this._scene.registerBeforeRender(this._renderFunction);
  76833. }
  76834. else {
  76835. this._scene.unregisterBeforeRender(this._renderFunction);
  76836. }
  76837. },
  76838. enumerable: true,
  76839. configurable: true
  76840. });
  76841. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  76842. if (x === void 0) { x = 0; }
  76843. if (y === void 0) { y = 0; }
  76844. if (z === void 0) { z = 0; }
  76845. var tmat = BABYLON.Tmp.Matrix[0];
  76846. var parentBone = bone.getParent();
  76847. tmat.copyFrom(bone.getLocalMatrix());
  76848. if (x !== 0 || y !== 0 || z !== 0) {
  76849. var tmat2 = BABYLON.Tmp.Matrix[1];
  76850. BABYLON.Matrix.IdentityToRef(tmat2);
  76851. tmat2.m[12] = x;
  76852. tmat2.m[13] = y;
  76853. tmat2.m[14] = z;
  76854. tmat2.multiplyToRef(tmat, tmat);
  76855. }
  76856. if (parentBone) {
  76857. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  76858. }
  76859. tmat.multiplyToRef(meshMat, tmat);
  76860. position.x = tmat.m[12];
  76861. position.y = tmat.m[13];
  76862. position.z = tmat.m[14];
  76863. };
  76864. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  76865. var len = bones.length;
  76866. var meshPos = this.mesh.position;
  76867. for (var i = 0; i < len; i++) {
  76868. var bone = bones[i];
  76869. var points = this._debugLines[i];
  76870. if (!points) {
  76871. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76872. this._debugLines[i] = points;
  76873. }
  76874. this._getBonePosition(points[0], bone, meshMat);
  76875. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  76876. points[0].subtractInPlace(meshPos);
  76877. points[1].subtractInPlace(meshPos);
  76878. }
  76879. };
  76880. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  76881. var len = bones.length;
  76882. var boneNum = 0;
  76883. var meshPos = this.mesh.position;
  76884. for (var i = len - 1; i >= 0; i--) {
  76885. var childBone = bones[i];
  76886. var parentBone = childBone.getParent();
  76887. if (!parentBone) {
  76888. continue;
  76889. }
  76890. var points = this._debugLines[boneNum];
  76891. if (!points) {
  76892. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  76893. this._debugLines[boneNum] = points;
  76894. }
  76895. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  76896. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  76897. points[0].subtractInPlace(meshPos);
  76898. points[1].subtractInPlace(meshPos);
  76899. boneNum++;
  76900. }
  76901. };
  76902. SkeletonViewer.prototype.update = function () {
  76903. if (this.autoUpdateBonesMatrices) {
  76904. this.skeleton.computeAbsoluteTransforms();
  76905. }
  76906. if (this.skeleton.bones[0].length === undefined) {
  76907. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76908. }
  76909. else {
  76910. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  76911. }
  76912. if (!this._debugMesh) {
  76913. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  76914. this._debugMesh.renderingGroupId = this.renderingGroupId;
  76915. }
  76916. else {
  76917. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  76918. }
  76919. this._debugMesh.position.copyFrom(this.mesh.position);
  76920. this._debugMesh.color = this.color;
  76921. };
  76922. SkeletonViewer.prototype.dispose = function () {
  76923. if (this._debugMesh) {
  76924. this.isEnabled = false;
  76925. this._debugMesh.dispose();
  76926. this._debugMesh = null;
  76927. }
  76928. };
  76929. return SkeletonViewer;
  76930. }());
  76931. return Debug;
  76932. }());
  76933. BABYLON.Debug = Debug;
  76934. })(BABYLON || (BABYLON = {}));
  76935. //# sourceMappingURL=babylon.debugModules.js.map
  76936. var BABYLON;
  76937. (function (BABYLON) {
  76938. var RayHelper = /** @class */ (function () {
  76939. function RayHelper(ray) {
  76940. this.ray = ray;
  76941. }
  76942. RayHelper.CreateAndShow = function (ray, scene, color) {
  76943. var helper = new RayHelper(ray);
  76944. helper.show(scene, color);
  76945. return helper;
  76946. };
  76947. RayHelper.prototype.show = function (scene, color) {
  76948. if (!this._renderFunction && this.ray) {
  76949. var ray = this.ray;
  76950. this._renderFunction = this._render.bind(this);
  76951. this._scene = scene;
  76952. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  76953. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  76954. if (this._renderFunction) {
  76955. this._scene.registerBeforeRender(this._renderFunction);
  76956. }
  76957. }
  76958. if (color && this._renderLine) {
  76959. this._renderLine.color.copyFrom(color);
  76960. }
  76961. };
  76962. RayHelper.prototype.hide = function () {
  76963. if (this._renderFunction && this._scene) {
  76964. this._scene.unregisterBeforeRender(this._renderFunction);
  76965. this._scene = null;
  76966. this._renderFunction = null;
  76967. if (this._renderLine) {
  76968. this._renderLine.dispose();
  76969. this._renderLine = null;
  76970. }
  76971. this._renderPoints = [];
  76972. }
  76973. };
  76974. RayHelper.prototype._render = function () {
  76975. var ray = this.ray;
  76976. if (!ray) {
  76977. return;
  76978. }
  76979. var point = this._renderPoints[1];
  76980. var len = Math.min(ray.length, 1000000);
  76981. point.copyFrom(ray.direction);
  76982. point.scaleInPlace(len);
  76983. point.addInPlace(ray.origin);
  76984. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  76985. };
  76986. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  76987. this._attachedToMesh = mesh;
  76988. var ray = this.ray;
  76989. if (!ray) {
  76990. return;
  76991. }
  76992. if (!ray.direction) {
  76993. ray.direction = BABYLON.Vector3.Zero();
  76994. }
  76995. if (!ray.origin) {
  76996. ray.origin = BABYLON.Vector3.Zero();
  76997. }
  76998. if (length) {
  76999. ray.length = length;
  77000. }
  77001. if (!meshSpaceOrigin) {
  77002. meshSpaceOrigin = BABYLON.Vector3.Zero();
  77003. }
  77004. if (!meshSpaceDirection) {
  77005. // -1 so that this will work with Mesh.lookAt
  77006. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  77007. }
  77008. if (!this._meshSpaceDirection) {
  77009. this._meshSpaceDirection = meshSpaceDirection.clone();
  77010. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  77011. }
  77012. else {
  77013. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  77014. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  77015. }
  77016. if (!this._updateToMeshFunction) {
  77017. this._updateToMeshFunction = this._updateToMesh.bind(this);
  77018. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  77019. }
  77020. this._updateToMesh();
  77021. };
  77022. RayHelper.prototype.detachFromMesh = function () {
  77023. if (this._attachedToMesh) {
  77024. if (this._updateToMeshFunction) {
  77025. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  77026. }
  77027. this._attachedToMesh = null;
  77028. this._updateToMeshFunction = null;
  77029. }
  77030. };
  77031. RayHelper.prototype._updateToMesh = function () {
  77032. var ray = this.ray;
  77033. if (!this._attachedToMesh || !ray) {
  77034. return;
  77035. }
  77036. if (this._attachedToMesh._isDisposed) {
  77037. this.detachFromMesh();
  77038. return;
  77039. }
  77040. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  77041. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  77042. };
  77043. RayHelper.prototype.dispose = function () {
  77044. this.hide();
  77045. this.detachFromMesh();
  77046. this.ray = null;
  77047. };
  77048. return RayHelper;
  77049. }());
  77050. BABYLON.RayHelper = RayHelper;
  77051. })(BABYLON || (BABYLON = {}));
  77052. //# sourceMappingURL=babylon.rayHelper.js.map
  77053. var BABYLON;
  77054. (function (BABYLON) {
  77055. // load the inspector using require, if not present in the global namespace.
  77056. var DebugLayer = /** @class */ (function () {
  77057. function DebugLayer(scene) {
  77058. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77059. this._scene = scene;
  77060. // load inspector using require, if it doesn't exist on the global namespace.
  77061. }
  77062. /** Creates the inspector window. */
  77063. DebugLayer.prototype._createInspector = function (config) {
  77064. if (config === void 0) { config = {}; }
  77065. var popup = config.popup || false;
  77066. var initialTab = config.initialTab || 0;
  77067. var parentElement = config.parentElement || null;
  77068. if (!this._inspector) {
  77069. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77070. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  77071. } // else nothing to do,; instance is already existing
  77072. };
  77073. DebugLayer.prototype.isVisible = function () {
  77074. if (!this._inspector) {
  77075. return false;
  77076. }
  77077. return true;
  77078. };
  77079. DebugLayer.prototype.hide = function () {
  77080. if (this._inspector) {
  77081. try {
  77082. this._inspector.dispose();
  77083. }
  77084. catch (e) {
  77085. // If the inspector has been removed directly from the inspector tool
  77086. }
  77087. this._inspector = null;
  77088. }
  77089. };
  77090. DebugLayer.prototype.show = function (config) {
  77091. if (config === void 0) { config = {}; }
  77092. if (typeof this.BJSINSPECTOR == 'undefined') {
  77093. // Load inspector and add it to the DOM
  77094. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  77095. }
  77096. else {
  77097. // Otherwise creates the inspector
  77098. this._createInspector(config);
  77099. }
  77100. };
  77101. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  77102. return DebugLayer;
  77103. }());
  77104. BABYLON.DebugLayer = DebugLayer;
  77105. })(BABYLON || (BABYLON = {}));
  77106. //# sourceMappingURL=babylon.debugLayer.js.map
  77107. var BABYLON;
  77108. (function (BABYLON) {
  77109. var BoundingBoxRenderer = /** @class */ (function () {
  77110. function BoundingBoxRenderer(scene) {
  77111. this.frontColor = new BABYLON.Color3(1, 1, 1);
  77112. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  77113. this.showBackLines = true;
  77114. this.renderList = new BABYLON.SmartArray(32);
  77115. this._vertexBuffers = {};
  77116. this._scene = scene;
  77117. }
  77118. BoundingBoxRenderer.prototype._prepareRessources = function () {
  77119. if (this._colorShader) {
  77120. return;
  77121. }
  77122. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  77123. attributes: [BABYLON.VertexBuffer.PositionKind],
  77124. uniforms: ["world", "viewProjection", "color"]
  77125. });
  77126. var engine = this._scene.getEngine();
  77127. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  77128. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  77129. this._createIndexBuffer();
  77130. };
  77131. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  77132. var engine = this._scene.getEngine();
  77133. 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]);
  77134. };
  77135. BoundingBoxRenderer.prototype._rebuild = function () {
  77136. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77137. if (vb) {
  77138. vb._rebuild();
  77139. }
  77140. this._createIndexBuffer();
  77141. };
  77142. BoundingBoxRenderer.prototype.reset = function () {
  77143. this.renderList.reset();
  77144. };
  77145. BoundingBoxRenderer.prototype.render = function () {
  77146. if (this.renderList.length === 0) {
  77147. return;
  77148. }
  77149. this._prepareRessources();
  77150. if (!this._colorShader.isReady()) {
  77151. return;
  77152. }
  77153. var engine = this._scene.getEngine();
  77154. engine.setDepthWrite(false);
  77155. this._colorShader._preBind();
  77156. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  77157. var boundingBox = this.renderList.data[boundingBoxIndex];
  77158. var min = boundingBox.minimum;
  77159. var max = boundingBox.maximum;
  77160. var diff = max.subtract(min);
  77161. var median = min.add(diff.scale(0.5));
  77162. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77163. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77164. .multiply(boundingBox.getWorldMatrix());
  77165. // VBOs
  77166. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77167. if (this.showBackLines) {
  77168. // Back
  77169. engine.setDepthFunctionToGreaterOrEqual();
  77170. this._scene.resetCachedMaterial();
  77171. this._colorShader.setColor4("color", this.backColor.toColor4());
  77172. this._colorShader.bind(worldMatrix);
  77173. // Draw order
  77174. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77175. }
  77176. // Front
  77177. engine.setDepthFunctionToLess();
  77178. this._scene.resetCachedMaterial();
  77179. this._colorShader.setColor4("color", this.frontColor.toColor4());
  77180. this._colorShader.bind(worldMatrix);
  77181. // Draw order
  77182. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77183. }
  77184. this._colorShader.unbind();
  77185. engine.setDepthFunctionToLessOrEqual();
  77186. engine.setDepthWrite(true);
  77187. };
  77188. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  77189. this._prepareRessources();
  77190. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  77191. return;
  77192. }
  77193. var engine = this._scene.getEngine();
  77194. engine.setDepthWrite(false);
  77195. engine.setColorWrite(false);
  77196. this._colorShader._preBind();
  77197. var boundingBox = mesh._boundingInfo.boundingBox;
  77198. var min = boundingBox.minimum;
  77199. var max = boundingBox.maximum;
  77200. var diff = max.subtract(min);
  77201. var median = min.add(diff.scale(0.5));
  77202. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77203. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77204. .multiply(boundingBox.getWorldMatrix());
  77205. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77206. engine.setDepthFunctionToLess();
  77207. this._scene.resetCachedMaterial();
  77208. this._colorShader.bind(worldMatrix);
  77209. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77210. this._colorShader.unbind();
  77211. engine.setDepthFunctionToLessOrEqual();
  77212. engine.setDepthWrite(true);
  77213. engine.setColorWrite(true);
  77214. };
  77215. BoundingBoxRenderer.prototype.dispose = function () {
  77216. if (!this._colorShader) {
  77217. return;
  77218. }
  77219. this.renderList.dispose();
  77220. this._colorShader.dispose();
  77221. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77222. if (buffer) {
  77223. buffer.dispose();
  77224. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77225. }
  77226. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77227. };
  77228. return BoundingBoxRenderer;
  77229. }());
  77230. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  77231. })(BABYLON || (BABYLON = {}));
  77232. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  77233. var BABYLON;
  77234. (function (BABYLON) {
  77235. var MorphTarget = /** @class */ (function () {
  77236. function MorphTarget(name, influence) {
  77237. if (influence === void 0) { influence = 0; }
  77238. this.name = name;
  77239. this.animations = new Array();
  77240. this._positions = null;
  77241. this._normals = null;
  77242. this._tangents = null;
  77243. this.onInfluenceChanged = new BABYLON.Observable();
  77244. this.influence = influence;
  77245. }
  77246. Object.defineProperty(MorphTarget.prototype, "influence", {
  77247. get: function () {
  77248. return this._influence;
  77249. },
  77250. set: function (influence) {
  77251. if (this._influence === influence) {
  77252. return;
  77253. }
  77254. var previous = this._influence;
  77255. this._influence = influence;
  77256. if (this.onInfluenceChanged.hasObservers) {
  77257. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  77258. }
  77259. },
  77260. enumerable: true,
  77261. configurable: true
  77262. });
  77263. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  77264. get: function () {
  77265. return !!this._positions;
  77266. },
  77267. enumerable: true,
  77268. configurable: true
  77269. });
  77270. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  77271. get: function () {
  77272. return !!this._normals;
  77273. },
  77274. enumerable: true,
  77275. configurable: true
  77276. });
  77277. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  77278. get: function () {
  77279. return !!this._tangents;
  77280. },
  77281. enumerable: true,
  77282. configurable: true
  77283. });
  77284. MorphTarget.prototype.setPositions = function (data) {
  77285. this._positions = data;
  77286. };
  77287. MorphTarget.prototype.getPositions = function () {
  77288. return this._positions;
  77289. };
  77290. MorphTarget.prototype.setNormals = function (data) {
  77291. this._normals = data;
  77292. };
  77293. MorphTarget.prototype.getNormals = function () {
  77294. return this._normals;
  77295. };
  77296. MorphTarget.prototype.setTangents = function (data) {
  77297. this._tangents = data;
  77298. };
  77299. MorphTarget.prototype.getTangents = function () {
  77300. return this._tangents;
  77301. };
  77302. /**
  77303. * Serializes the current target into a Serialization object.
  77304. * Returns the serialized object.
  77305. */
  77306. MorphTarget.prototype.serialize = function () {
  77307. var serializationObject = {};
  77308. serializationObject.name = this.name;
  77309. serializationObject.influence = this.influence;
  77310. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  77311. if (this.hasNormals) {
  77312. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  77313. }
  77314. if (this.hasTangents) {
  77315. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  77316. }
  77317. // Animations
  77318. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  77319. return serializationObject;
  77320. };
  77321. // Statics
  77322. MorphTarget.Parse = function (serializationObject) {
  77323. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  77324. result.setPositions(serializationObject.positions);
  77325. if (serializationObject.normals) {
  77326. result.setNormals(serializationObject.normals);
  77327. }
  77328. if (serializationObject.tangents) {
  77329. result.setTangents(serializationObject.tangents);
  77330. }
  77331. // Animations
  77332. if (serializationObject.animations) {
  77333. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  77334. var parsedAnimation = serializationObject.animations[animationIndex];
  77335. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  77336. }
  77337. }
  77338. return result;
  77339. };
  77340. MorphTarget.FromMesh = function (mesh, name, influence) {
  77341. if (!name) {
  77342. name = mesh.name;
  77343. }
  77344. var result = new MorphTarget(name, influence);
  77345. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77346. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77347. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77348. }
  77349. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77350. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77351. }
  77352. return result;
  77353. };
  77354. return MorphTarget;
  77355. }());
  77356. BABYLON.MorphTarget = MorphTarget;
  77357. })(BABYLON || (BABYLON = {}));
  77358. //# sourceMappingURL=babylon.morphTarget.js.map
  77359. var BABYLON;
  77360. (function (BABYLON) {
  77361. var MorphTargetManager = /** @class */ (function () {
  77362. function MorphTargetManager(scene) {
  77363. if (scene === void 0) { scene = null; }
  77364. this._targets = new Array();
  77365. this._targetObservable = new Array();
  77366. this._activeTargets = new BABYLON.SmartArray(16);
  77367. this._supportsNormals = false;
  77368. this._supportsTangents = false;
  77369. this._vertexCount = 0;
  77370. this._uniqueId = 0;
  77371. this._tempInfluences = new Array();
  77372. if (!scene) {
  77373. scene = BABYLON.Engine.LastCreatedScene;
  77374. }
  77375. this._scene = scene;
  77376. if (this._scene) {
  77377. this._scene.morphTargetManagers.push(this);
  77378. this._uniqueId = this._scene.getUniqueId();
  77379. }
  77380. }
  77381. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77382. get: function () {
  77383. return this._uniqueId;
  77384. },
  77385. enumerable: true,
  77386. configurable: true
  77387. });
  77388. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77389. get: function () {
  77390. return this._vertexCount;
  77391. },
  77392. enumerable: true,
  77393. configurable: true
  77394. });
  77395. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77396. get: function () {
  77397. return this._supportsNormals;
  77398. },
  77399. enumerable: true,
  77400. configurable: true
  77401. });
  77402. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77403. get: function () {
  77404. return this._supportsTangents;
  77405. },
  77406. enumerable: true,
  77407. configurable: true
  77408. });
  77409. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77410. get: function () {
  77411. return this._targets.length;
  77412. },
  77413. enumerable: true,
  77414. configurable: true
  77415. });
  77416. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77417. get: function () {
  77418. return this._activeTargets.length;
  77419. },
  77420. enumerable: true,
  77421. configurable: true
  77422. });
  77423. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77424. get: function () {
  77425. return this._influences;
  77426. },
  77427. enumerable: true,
  77428. configurable: true
  77429. });
  77430. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77431. return this._activeTargets.data[index];
  77432. };
  77433. MorphTargetManager.prototype.getTarget = function (index) {
  77434. return this._targets[index];
  77435. };
  77436. MorphTargetManager.prototype.addTarget = function (target) {
  77437. var _this = this;
  77438. this._targets.push(target);
  77439. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77440. _this._syncActiveTargets(needUpdate);
  77441. }));
  77442. this._syncActiveTargets(true);
  77443. };
  77444. MorphTargetManager.prototype.removeTarget = function (target) {
  77445. var index = this._targets.indexOf(target);
  77446. if (index >= 0) {
  77447. this._targets.splice(index, 1);
  77448. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77449. this._syncActiveTargets(true);
  77450. }
  77451. };
  77452. /**
  77453. * Serializes the current manager into a Serialization object.
  77454. * Returns the serialized object.
  77455. */
  77456. MorphTargetManager.prototype.serialize = function () {
  77457. var serializationObject = {};
  77458. serializationObject.id = this.uniqueId;
  77459. serializationObject.targets = [];
  77460. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77461. var target = _a[_i];
  77462. serializationObject.targets.push(target.serialize());
  77463. }
  77464. return serializationObject;
  77465. };
  77466. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77467. var influenceCount = 0;
  77468. this._activeTargets.reset();
  77469. this._supportsNormals = true;
  77470. this._supportsTangents = true;
  77471. this._vertexCount = 0;
  77472. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77473. var target = _a[_i];
  77474. this._activeTargets.push(target);
  77475. this._tempInfluences[influenceCount++] = target.influence;
  77476. var positions = target.getPositions();
  77477. if (positions) {
  77478. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77479. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77480. var vertexCount = positions.length / 3;
  77481. if (this._vertexCount === 0) {
  77482. this._vertexCount = vertexCount;
  77483. }
  77484. else if (this._vertexCount !== vertexCount) {
  77485. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77486. return;
  77487. }
  77488. }
  77489. }
  77490. if (!this._influences || this._influences.length !== influenceCount) {
  77491. this._influences = new Float32Array(influenceCount);
  77492. }
  77493. for (var index = 0; index < influenceCount; index++) {
  77494. this._influences[index] = this._tempInfluences[index];
  77495. }
  77496. if (needUpdate && this._scene) {
  77497. // Flag meshes as dirty to resync with the active targets
  77498. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77499. var mesh = _c[_b];
  77500. if (mesh.morphTargetManager === this) {
  77501. mesh._syncGeometryWithMorphTargetManager();
  77502. }
  77503. }
  77504. }
  77505. };
  77506. // Statics
  77507. MorphTargetManager.Parse = function (serializationObject, scene) {
  77508. var result = new MorphTargetManager(scene);
  77509. result._uniqueId = serializationObject.id;
  77510. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77511. var targetData = _a[_i];
  77512. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77513. }
  77514. return result;
  77515. };
  77516. return MorphTargetManager;
  77517. }());
  77518. BABYLON.MorphTargetManager = MorphTargetManager;
  77519. })(BABYLON || (BABYLON = {}));
  77520. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77521. var BABYLON;
  77522. (function (BABYLON) {
  77523. var Octree = /** @class */ (function () {
  77524. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77525. if (maxDepth === void 0) { maxDepth = 2; }
  77526. this.maxDepth = maxDepth;
  77527. this.dynamicContent = new Array();
  77528. this._maxBlockCapacity = maxBlockCapacity || 64;
  77529. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  77530. this._creationFunc = creationFunc;
  77531. }
  77532. // Methods
  77533. Octree.prototype.update = function (worldMin, worldMax, entries) {
  77534. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  77535. };
  77536. Octree.prototype.addMesh = function (entry) {
  77537. for (var index = 0; index < this.blocks.length; index++) {
  77538. var block = this.blocks[index];
  77539. block.addEntry(entry);
  77540. }
  77541. };
  77542. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  77543. this._selectionContent.reset();
  77544. for (var index = 0; index < this.blocks.length; index++) {
  77545. var block = this.blocks[index];
  77546. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  77547. }
  77548. if (allowDuplicate) {
  77549. this._selectionContent.concat(this.dynamicContent);
  77550. }
  77551. else {
  77552. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77553. }
  77554. return this._selectionContent;
  77555. };
  77556. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  77557. this._selectionContent.reset();
  77558. for (var index = 0; index < this.blocks.length; index++) {
  77559. var block = this.blocks[index];
  77560. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  77561. }
  77562. if (allowDuplicate) {
  77563. this._selectionContent.concat(this.dynamicContent);
  77564. }
  77565. else {
  77566. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77567. }
  77568. return this._selectionContent;
  77569. };
  77570. Octree.prototype.intersectsRay = function (ray) {
  77571. this._selectionContent.reset();
  77572. for (var index = 0; index < this.blocks.length; index++) {
  77573. var block = this.blocks[index];
  77574. block.intersectsRay(ray, this._selectionContent);
  77575. }
  77576. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  77577. return this._selectionContent;
  77578. };
  77579. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  77580. target.blocks = new Array();
  77581. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  77582. // Segmenting space
  77583. for (var x = 0; x < 2; x++) {
  77584. for (var y = 0; y < 2; y++) {
  77585. for (var z = 0; z < 2; z++) {
  77586. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  77587. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  77588. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  77589. block.addEntries(entries);
  77590. target.blocks.push(block);
  77591. }
  77592. }
  77593. }
  77594. };
  77595. Octree.CreationFuncForMeshes = function (entry, block) {
  77596. var boundingInfo = entry.getBoundingInfo();
  77597. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77598. block.entries.push(entry);
  77599. }
  77600. };
  77601. Octree.CreationFuncForSubMeshes = function (entry, block) {
  77602. var boundingInfo = entry.getBoundingInfo();
  77603. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  77604. block.entries.push(entry);
  77605. }
  77606. };
  77607. return Octree;
  77608. }());
  77609. BABYLON.Octree = Octree;
  77610. })(BABYLON || (BABYLON = {}));
  77611. //# sourceMappingURL=babylon.octree.js.map
  77612. var BABYLON;
  77613. (function (BABYLON) {
  77614. var OctreeBlock = /** @class */ (function () {
  77615. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  77616. this.entries = new Array();
  77617. this._boundingVectors = new Array();
  77618. this._capacity = capacity;
  77619. this._depth = depth;
  77620. this._maxDepth = maxDepth;
  77621. this._creationFunc = creationFunc;
  77622. this._minPoint = minPoint;
  77623. this._maxPoint = maxPoint;
  77624. this._boundingVectors.push(minPoint.clone());
  77625. this._boundingVectors.push(maxPoint.clone());
  77626. this._boundingVectors.push(minPoint.clone());
  77627. this._boundingVectors[2].x = maxPoint.x;
  77628. this._boundingVectors.push(minPoint.clone());
  77629. this._boundingVectors[3].y = maxPoint.y;
  77630. this._boundingVectors.push(minPoint.clone());
  77631. this._boundingVectors[4].z = maxPoint.z;
  77632. this._boundingVectors.push(maxPoint.clone());
  77633. this._boundingVectors[5].z = minPoint.z;
  77634. this._boundingVectors.push(maxPoint.clone());
  77635. this._boundingVectors[6].x = minPoint.x;
  77636. this._boundingVectors.push(maxPoint.clone());
  77637. this._boundingVectors[7].y = minPoint.y;
  77638. }
  77639. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  77640. // Property
  77641. get: function () {
  77642. return this._capacity;
  77643. },
  77644. enumerable: true,
  77645. configurable: true
  77646. });
  77647. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  77648. get: function () {
  77649. return this._minPoint;
  77650. },
  77651. enumerable: true,
  77652. configurable: true
  77653. });
  77654. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  77655. get: function () {
  77656. return this._maxPoint;
  77657. },
  77658. enumerable: true,
  77659. configurable: true
  77660. });
  77661. // Methods
  77662. OctreeBlock.prototype.addEntry = function (entry) {
  77663. if (this.blocks) {
  77664. for (var index = 0; index < this.blocks.length; index++) {
  77665. var block = this.blocks[index];
  77666. block.addEntry(entry);
  77667. }
  77668. return;
  77669. }
  77670. this._creationFunc(entry, this);
  77671. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  77672. this.createInnerBlocks();
  77673. }
  77674. };
  77675. OctreeBlock.prototype.addEntries = function (entries) {
  77676. for (var index = 0; index < entries.length; index++) {
  77677. var mesh = entries[index];
  77678. this.addEntry(mesh);
  77679. }
  77680. };
  77681. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  77682. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  77683. if (this.blocks) {
  77684. for (var index = 0; index < this.blocks.length; index++) {
  77685. var block = this.blocks[index];
  77686. block.select(frustumPlanes, selection, allowDuplicate);
  77687. }
  77688. return;
  77689. }
  77690. if (allowDuplicate) {
  77691. selection.concat(this.entries);
  77692. }
  77693. else {
  77694. selection.concatWithNoDuplicate(this.entries);
  77695. }
  77696. }
  77697. };
  77698. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  77699. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  77700. if (this.blocks) {
  77701. for (var index = 0; index < this.blocks.length; index++) {
  77702. var block = this.blocks[index];
  77703. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  77704. }
  77705. return;
  77706. }
  77707. if (allowDuplicate) {
  77708. selection.concat(this.entries);
  77709. }
  77710. else {
  77711. selection.concatWithNoDuplicate(this.entries);
  77712. }
  77713. }
  77714. };
  77715. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  77716. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  77717. if (this.blocks) {
  77718. for (var index = 0; index < this.blocks.length; index++) {
  77719. var block = this.blocks[index];
  77720. block.intersectsRay(ray, selection);
  77721. }
  77722. return;
  77723. }
  77724. selection.concatWithNoDuplicate(this.entries);
  77725. }
  77726. };
  77727. OctreeBlock.prototype.createInnerBlocks = function () {
  77728. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  77729. };
  77730. return OctreeBlock;
  77731. }());
  77732. BABYLON.OctreeBlock = OctreeBlock;
  77733. })(BABYLON || (BABYLON = {}));
  77734. //# sourceMappingURL=babylon.octreeBlock.js.map
  77735. var BABYLON;
  77736. (function (BABYLON) {
  77737. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  77738. __extends(VRDistortionCorrectionPostProcess, _super);
  77739. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  77740. var _this = _super.call(this, name, "vrDistortionCorrection", [
  77741. 'LensCenter',
  77742. 'Scale',
  77743. 'ScaleIn',
  77744. 'HmdWarpParam'
  77745. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  77746. _this._isRightEye = isRightEye;
  77747. _this._distortionFactors = vrMetrics.distortionK;
  77748. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  77749. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  77750. _this.adaptScaleToCurrentViewport = true;
  77751. _this.onSizeChangedObservable.add(function () {
  77752. _this.aspectRatio = _this.width * .5 / _this.height;
  77753. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  77754. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  77755. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  77756. });
  77757. _this.onApplyObservable.add(function (effect) {
  77758. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  77759. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  77760. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  77761. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  77762. });
  77763. return _this;
  77764. }
  77765. return VRDistortionCorrectionPostProcess;
  77766. }(BABYLON.PostProcess));
  77767. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  77768. })(BABYLON || (BABYLON = {}));
  77769. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  77770. var BABYLON;
  77771. (function (BABYLON) {
  77772. var AnaglyphPostProcess = /** @class */ (function (_super) {
  77773. __extends(AnaglyphPostProcess, _super);
  77774. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  77775. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  77776. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77777. _this.onApplyObservable.add(function (effect) {
  77778. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  77779. });
  77780. return _this;
  77781. }
  77782. return AnaglyphPostProcess;
  77783. }(BABYLON.PostProcess));
  77784. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  77785. })(BABYLON || (BABYLON = {}));
  77786. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  77787. var BABYLON;
  77788. (function (BABYLON) {
  77789. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  77790. __extends(StereoscopicInterlacePostProcess, _super);
  77791. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  77792. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  77793. _this._passedProcess = rigCameras[0]._rigPostProcess;
  77794. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77795. _this.onSizeChangedObservable.add(function () {
  77796. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  77797. });
  77798. _this.onApplyObservable.add(function (effect) {
  77799. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  77800. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  77801. });
  77802. return _this;
  77803. }
  77804. return StereoscopicInterlacePostProcess;
  77805. }(BABYLON.PostProcess));
  77806. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  77807. })(BABYLON || (BABYLON = {}));
  77808. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  77809. var BABYLON;
  77810. (function (BABYLON) {
  77811. /**
  77812. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  77813. * Screen rotation is taken into account.
  77814. */
  77815. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  77816. function FreeCameraDeviceOrientationInput() {
  77817. var _this = this;
  77818. this._screenOrientationAngle = 0;
  77819. this._screenQuaternion = new BABYLON.Quaternion();
  77820. this._alpha = 0;
  77821. this._beta = 0;
  77822. this._gamma = 0;
  77823. this._orientationChanged = function () {
  77824. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  77825. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  77826. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  77827. };
  77828. this._deviceOrientation = function (evt) {
  77829. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  77830. _this._beta = evt.beta !== null ? evt.beta : 0;
  77831. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  77832. };
  77833. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  77834. this._orientationChanged();
  77835. }
  77836. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  77837. get: function () {
  77838. return this._camera;
  77839. },
  77840. set: function (camera) {
  77841. this._camera = camera;
  77842. if (this._camera != null && !this._camera.rotationQuaternion) {
  77843. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  77844. }
  77845. },
  77846. enumerable: true,
  77847. configurable: true
  77848. });
  77849. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77850. window.addEventListener("orientationchange", this._orientationChanged);
  77851. window.addEventListener("deviceorientation", this._deviceOrientation);
  77852. //In certain cases, the attach control is called AFTER orientation was changed,
  77853. //So this is needed.
  77854. this._orientationChanged();
  77855. };
  77856. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  77857. window.removeEventListener("orientationchange", this._orientationChanged);
  77858. window.removeEventListener("deviceorientation", this._deviceOrientation);
  77859. };
  77860. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  77861. //if no device orientation provided, don't update the rotation.
  77862. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  77863. if (!this._alpha)
  77864. return;
  77865. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  77866. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  77867. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  77868. //Mirror on XY Plane
  77869. this._camera.rotationQuaternion.z *= -1;
  77870. this._camera.rotationQuaternion.w *= -1;
  77871. };
  77872. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  77873. return "FreeCameraDeviceOrientationInput";
  77874. };
  77875. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  77876. return "deviceOrientation";
  77877. };
  77878. return FreeCameraDeviceOrientationInput;
  77879. }());
  77880. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  77881. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  77882. })(BABYLON || (BABYLON = {}));
  77883. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  77884. var BABYLON;
  77885. (function (BABYLON) {
  77886. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  77887. function ArcRotateCameraVRDeviceOrientationInput() {
  77888. this.alphaCorrection = 1;
  77889. this.betaCorrection = 1;
  77890. this.gammaCorrection = 1;
  77891. this._alpha = 0;
  77892. this._gamma = 0;
  77893. this._dirty = false;
  77894. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  77895. }
  77896. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  77897. this.camera.attachControl(element, noPreventDefault);
  77898. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  77899. };
  77900. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  77901. if (evt.alpha !== null) {
  77902. this._alpha = +evt.alpha | 0;
  77903. }
  77904. if (evt.gamma !== null) {
  77905. this._gamma = +evt.gamma | 0;
  77906. }
  77907. this._dirty = true;
  77908. };
  77909. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  77910. if (this._dirty) {
  77911. this._dirty = false;
  77912. if (this._gamma < 0) {
  77913. this._gamma = 180 + this._gamma;
  77914. }
  77915. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  77916. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  77917. }
  77918. };
  77919. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  77920. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  77921. };
  77922. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  77923. return "ArcRotateCameraVRDeviceOrientationInput";
  77924. };
  77925. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  77926. return "VRDeviceOrientation";
  77927. };
  77928. return ArcRotateCameraVRDeviceOrientationInput;
  77929. }());
  77930. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  77931. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  77932. })(BABYLON || (BABYLON = {}));
  77933. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  77934. var BABYLON;
  77935. (function (BABYLON) {
  77936. var VRCameraMetrics = /** @class */ (function () {
  77937. function VRCameraMetrics() {
  77938. this.compensateDistortion = true;
  77939. }
  77940. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  77941. get: function () {
  77942. return this.hResolution / (2 * this.vResolution);
  77943. },
  77944. enumerable: true,
  77945. configurable: true
  77946. });
  77947. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  77948. get: function () {
  77949. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  77950. },
  77951. enumerable: true,
  77952. configurable: true
  77953. });
  77954. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  77955. get: function () {
  77956. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77957. var h = (4 * meters) / this.hScreenSize;
  77958. return BABYLON.Matrix.Translation(h, 0, 0);
  77959. },
  77960. enumerable: true,
  77961. configurable: true
  77962. });
  77963. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  77964. get: function () {
  77965. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  77966. var h = (4 * meters) / this.hScreenSize;
  77967. return BABYLON.Matrix.Translation(-h, 0, 0);
  77968. },
  77969. enumerable: true,
  77970. configurable: true
  77971. });
  77972. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  77973. get: function () {
  77974. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  77975. },
  77976. enumerable: true,
  77977. configurable: true
  77978. });
  77979. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  77980. get: function () {
  77981. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  77982. },
  77983. enumerable: true,
  77984. configurable: true
  77985. });
  77986. VRCameraMetrics.GetDefault = function () {
  77987. var result = new VRCameraMetrics();
  77988. result.hResolution = 1280;
  77989. result.vResolution = 800;
  77990. result.hScreenSize = 0.149759993;
  77991. result.vScreenSize = 0.0935999975;
  77992. result.vScreenCenter = 0.0467999987;
  77993. result.eyeToScreenDistance = 0.0410000011;
  77994. result.lensSeparationDistance = 0.0635000020;
  77995. result.interpupillaryDistance = 0.0640000030;
  77996. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  77997. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  77998. result.postProcessScaleFactor = 1.714605507808412;
  77999. result.lensCenterOffset = 0.151976421;
  78000. return result;
  78001. };
  78002. return VRCameraMetrics;
  78003. }());
  78004. BABYLON.VRCameraMetrics = VRCameraMetrics;
  78005. })(BABYLON || (BABYLON = {}));
  78006. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  78007. var BABYLON;
  78008. (function (BABYLON) {
  78009. /**
  78010. * This represents a WebVR camera.
  78011. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  78012. * @example http://doc.babylonjs.com/how_to/webvr_camera
  78013. */
  78014. var WebVRFreeCamera = /** @class */ (function (_super) {
  78015. __extends(WebVRFreeCamera, _super);
  78016. /**
  78017. * Instantiates a WebVRFreeCamera.
  78018. * @param name The name of the WebVRFreeCamera
  78019. * @param position The starting anchor position for the camera
  78020. * @param scene The scene the camera belongs to
  78021. * @param webVROptions a set of customizable options for the webVRCamera
  78022. */
  78023. function WebVRFreeCamera(name, position, scene, webVROptions) {
  78024. if (webVROptions === void 0) { webVROptions = {}; }
  78025. var _this = _super.call(this, name, position, scene) || this;
  78026. _this.webVROptions = webVROptions;
  78027. /**
  78028. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  78029. */
  78030. _this._vrDevice = null;
  78031. /**
  78032. * The rawPose of the vrDevice.
  78033. */
  78034. _this.rawPose = null;
  78035. _this._specsVersion = "1.1";
  78036. _this._attached = false;
  78037. _this._descendants = [];
  78038. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78039. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78040. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  78041. _this._standingMatrix = null;
  78042. /**
  78043. * Represents device position in babylon space.
  78044. */
  78045. _this.devicePosition = BABYLON.Vector3.Zero();
  78046. /**
  78047. * Represents device rotation in babylon space.
  78048. */
  78049. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  78050. /**
  78051. * The scale of the device to be used when translating from device space to babylon space.
  78052. */
  78053. _this.deviceScaleFactor = 1;
  78054. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78055. _this._worldToDevice = BABYLON.Matrix.Identity();
  78056. /**
  78057. * References to the webVR controllers for the vrDevice.
  78058. */
  78059. _this.controllers = [];
  78060. /**
  78061. * Emits an event when a controller is attached.
  78062. */
  78063. _this.onControllersAttachedObservable = new BABYLON.Observable();
  78064. /**
  78065. * Emits an event when a controller's mesh has been loaded;
  78066. */
  78067. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78068. /**
  78069. * If the rig cameras be used as parent instead of this camera.
  78070. */
  78071. _this.rigParenting = true;
  78072. _this._defaultHeight = undefined;
  78073. _this._workingVector = BABYLON.Vector3.Zero();
  78074. _this._oneVector = BABYLON.Vector3.One();
  78075. _this._workingMatrix = BABYLON.Matrix.Identity();
  78076. _this._cache.position = BABYLON.Vector3.Zero();
  78077. if (webVROptions.defaultHeight) {
  78078. _this._defaultHeight = webVROptions.defaultHeight;
  78079. _this.position.y = _this._defaultHeight;
  78080. }
  78081. _this.minZ = 0.1;
  78082. //legacy support - the compensation boolean was removed.
  78083. if (arguments.length === 5) {
  78084. _this.webVROptions = arguments[4];
  78085. }
  78086. // default webVR options
  78087. if (_this.webVROptions.trackPosition == undefined) {
  78088. _this.webVROptions.trackPosition = true;
  78089. }
  78090. if (_this.webVROptions.controllerMeshes == undefined) {
  78091. _this.webVROptions.controllerMeshes = true;
  78092. }
  78093. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  78094. _this.webVROptions.defaultLightingOnControllers = true;
  78095. }
  78096. _this.rotationQuaternion = new BABYLON.Quaternion();
  78097. if (_this.webVROptions && _this.webVROptions.positionScale) {
  78098. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  78099. }
  78100. //enable VR
  78101. var engine = _this.getEngine();
  78102. _this._onVREnabled = function (success) { if (success) {
  78103. _this.initControllers();
  78104. } };
  78105. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  78106. engine.initWebVR().add(function (event) {
  78107. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  78108. return;
  78109. }
  78110. _this._vrDevice = event.vrDisplay;
  78111. //reset the rig parameters.
  78112. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  78113. if (_this._attached) {
  78114. _this.getEngine().enableVR();
  78115. }
  78116. });
  78117. if (typeof (VRFrameData) !== "undefined")
  78118. _this._frameData = new VRFrameData();
  78119. /**
  78120. * The idea behind the following lines:
  78121. * objects that have the camera as parent should actually have the rig cameras as a parent.
  78122. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  78123. * the second will not show it correctly.
  78124. *
  78125. * To solve this - each object that has the camera as parent will be added to a protected array.
  78126. * When the rig camera renders, it will take this array and set all of those to be its children.
  78127. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  78128. * Amazing!
  78129. */
  78130. scene.onBeforeCameraRenderObservable.add(function (camera) {
  78131. if (camera.parent === _this && _this.rigParenting) {
  78132. _this._descendants = _this.getDescendants(true, function (n) {
  78133. // don't take the cameras or the controllers!
  78134. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  78135. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  78136. return !isController && !isRigCamera;
  78137. });
  78138. _this._descendants.forEach(function (node) {
  78139. node.parent = camera;
  78140. });
  78141. }
  78142. });
  78143. scene.onAfterCameraRenderObservable.add(function (camera) {
  78144. if (camera.parent === _this && _this.rigParenting) {
  78145. _this._descendants.forEach(function (node) {
  78146. node.parent = _this;
  78147. });
  78148. }
  78149. });
  78150. return _this;
  78151. }
  78152. /**
  78153. * Gets the device distance from the ground in meters.
  78154. * @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.
  78155. */
  78156. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  78157. if (this._standingMatrix) {
  78158. // Add standing matrix offset to get real offset from ground in room
  78159. this._standingMatrix.getTranslationToRef(this._workingVector);
  78160. return this._deviceRoomPosition.y + this._workingVector.y;
  78161. }
  78162. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  78163. return this._defaultHeight || 0;
  78164. };
  78165. /**
  78166. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78167. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  78168. */
  78169. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  78170. var _this = this;
  78171. if (callback === void 0) { callback = function (bool) { }; }
  78172. // Use standing matrix if available
  78173. this.getEngine().initWebVRAsync().then(function (result) {
  78174. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  78175. callback(false);
  78176. }
  78177. else {
  78178. _this._standingMatrix = new BABYLON.Matrix();
  78179. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  78180. if (!_this.getScene().useRightHandedSystem) {
  78181. [2, 6, 8, 9, 14].forEach(function (num) {
  78182. if (_this._standingMatrix) {
  78183. _this._standingMatrix.m[num] *= -1;
  78184. }
  78185. });
  78186. }
  78187. callback(true);
  78188. }
  78189. });
  78190. };
  78191. /**
  78192. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78193. * @returns A promise with a boolean set to if the standing matrix is supported.
  78194. */
  78195. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  78196. var _this = this;
  78197. return new Promise(function (res, rej) {
  78198. _this.useStandingMatrix(function (supported) {
  78199. res(supported);
  78200. });
  78201. });
  78202. };
  78203. /**
  78204. * Disposes the camera
  78205. */
  78206. WebVRFreeCamera.prototype.dispose = function () {
  78207. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  78208. _super.prototype.dispose.call(this);
  78209. };
  78210. /**
  78211. * Gets a vrController by name.
  78212. * @param name The name of the controller to retreive
  78213. * @returns the controller matching the name specified or null if not found
  78214. */
  78215. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  78216. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  78217. var gp = _a[_i];
  78218. if (gp.hand === name) {
  78219. return gp;
  78220. }
  78221. }
  78222. return null;
  78223. };
  78224. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  78225. /**
  78226. * The controller corrisponding to the users left hand.
  78227. */
  78228. get: function () {
  78229. if (!this._leftController) {
  78230. this._leftController = this.getControllerByName("left");
  78231. }
  78232. return this._leftController;
  78233. },
  78234. enumerable: true,
  78235. configurable: true
  78236. });
  78237. ;
  78238. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  78239. /**
  78240. * The controller corrisponding to the users right hand.
  78241. */
  78242. get: function () {
  78243. if (!this._rightController) {
  78244. this._rightController = this.getControllerByName("right");
  78245. }
  78246. return this._rightController;
  78247. },
  78248. enumerable: true,
  78249. configurable: true
  78250. });
  78251. ;
  78252. /**
  78253. * Casts a ray forward from the vrCamera's gaze.
  78254. * @param length Length of the ray (default: 100)
  78255. * @returns the ray corrisponding to the gaze
  78256. */
  78257. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  78258. if (length === void 0) { length = 100; }
  78259. if (this.leftCamera) {
  78260. // Use left eye to avoid computation to compute center on every call
  78261. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  78262. }
  78263. else {
  78264. return _super.prototype.getForwardRay.call(this, length);
  78265. }
  78266. };
  78267. /**
  78268. * Updates the camera based on device's frame data
  78269. */
  78270. WebVRFreeCamera.prototype._checkInputs = function () {
  78271. if (this._vrDevice && this._vrDevice.isPresenting) {
  78272. this._vrDevice.getFrameData(this._frameData);
  78273. this.updateFromDevice(this._frameData.pose);
  78274. }
  78275. _super.prototype._checkInputs.call(this);
  78276. };
  78277. /**
  78278. * Updates the poseControlled values based on the input device pose.
  78279. * @param poseData Pose coming from the device
  78280. */
  78281. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  78282. if (poseData && poseData.orientation) {
  78283. this.rawPose = poseData;
  78284. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  78285. if (this.getScene().useRightHandedSystem) {
  78286. this._deviceRoomRotationQuaternion.z *= -1;
  78287. this._deviceRoomRotationQuaternion.w *= -1;
  78288. }
  78289. if (this.webVROptions.trackPosition && this.rawPose.position) {
  78290. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  78291. if (this.getScene().useRightHandedSystem) {
  78292. this._deviceRoomPosition.z *= -1;
  78293. }
  78294. }
  78295. }
  78296. };
  78297. /**
  78298. * WebVR's attach control will start broadcasting frames to the device.
  78299. * Note that in certain browsers (chrome for example) this function must be called
  78300. * within a user-interaction callback. Example:
  78301. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  78302. *
  78303. * @param element html element to attach the vrDevice to
  78304. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  78305. */
  78306. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  78307. _super.prototype.attachControl.call(this, element, noPreventDefault);
  78308. this._attached = true;
  78309. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  78310. if (this._vrDevice) {
  78311. this.getEngine().enableVR();
  78312. }
  78313. };
  78314. /**
  78315. * Detaches the camera from the html element and disables VR
  78316. *
  78317. * @param element html element to detach from
  78318. */
  78319. WebVRFreeCamera.prototype.detachControl = function (element) {
  78320. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78321. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78322. _super.prototype.detachControl.call(this, element);
  78323. this._attached = false;
  78324. this.getEngine().disableVR();
  78325. };
  78326. /**
  78327. * @returns the name of this class
  78328. */
  78329. WebVRFreeCamera.prototype.getClassName = function () {
  78330. return "WebVRFreeCamera";
  78331. };
  78332. /**
  78333. * Calls resetPose on the vrDisplay
  78334. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  78335. */
  78336. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  78337. //uses the vrDisplay's "resetPose()".
  78338. //pitch and roll won't be affected.
  78339. this._vrDevice.resetPose();
  78340. };
  78341. /**
  78342. * Updates the rig cameras (left and right eye)
  78343. */
  78344. WebVRFreeCamera.prototype._updateRigCameras = function () {
  78345. var camLeft = this._rigCameras[0];
  78346. var camRight = this._rigCameras[1];
  78347. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78348. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78349. camLeft.position.copyFrom(this._deviceRoomPosition);
  78350. camRight.position.copyFrom(this._deviceRoomPosition);
  78351. };
  78352. /**
  78353. * Updates the cached values of the camera
  78354. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78355. */
  78356. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78357. var _this = this;
  78358. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78359. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78360. if (!this.updateCacheCalled) {
  78361. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78362. this.updateCacheCalled = true;
  78363. this.update();
  78364. }
  78365. // Set working vector to the device position in room space rotated by the new rotation
  78366. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78367. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78368. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78369. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78370. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78371. // Add translation from anchor position
  78372. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78373. this._workingVector.addInPlace(this.position);
  78374. this._workingVector.subtractInPlace(this._cache.position);
  78375. this._deviceToWorld.setTranslation(this._workingVector);
  78376. // Set an inverted matrix to be used when updating the camera
  78377. this._deviceToWorld.invertToRef(this._worldToDevice);
  78378. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78379. this.controllers.forEach(function (controller) {
  78380. controller._deviceToWorld = _this._deviceToWorld;
  78381. controller.update();
  78382. });
  78383. }
  78384. if (!ignoreParentClass) {
  78385. _super.prototype._updateCache.call(this);
  78386. }
  78387. this.updateCacheCalled = false;
  78388. };
  78389. /**
  78390. * Updates the current device position and rotation in the babylon world
  78391. */
  78392. WebVRFreeCamera.prototype.update = function () {
  78393. // Get current device position in babylon world
  78394. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78395. // Get current device rotation in babylon world
  78396. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78397. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78398. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78399. _super.prototype.update.call(this);
  78400. };
  78401. /**
  78402. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78403. * @returns an identity matrix
  78404. */
  78405. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78406. return BABYLON.Matrix.Identity();
  78407. };
  78408. /**
  78409. * This function is called by the two RIG cameras.
  78410. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78411. */
  78412. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78413. var _this = this;
  78414. //WebVR 1.1
  78415. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78416. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78417. if (!this.getScene().useRightHandedSystem) {
  78418. [2, 6, 8, 9, 14].forEach(function (num) {
  78419. _this._webvrViewMatrix.m[num] *= -1;
  78420. });
  78421. }
  78422. // update the camera rotation matrix
  78423. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78424. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78425. // Computing target and final matrix
  78426. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78427. var parentCamera = this._cameraRigParams["parentCamera"];
  78428. // should the view matrix be updated with scale and position offset?
  78429. if (parentCamera.deviceScaleFactor !== 1) {
  78430. this._webvrViewMatrix.invert();
  78431. // scale the position, if set
  78432. if (parentCamera.deviceScaleFactor) {
  78433. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78434. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78435. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78436. }
  78437. this._webvrViewMatrix.invert();
  78438. }
  78439. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78440. return this._webvrViewMatrix;
  78441. };
  78442. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78443. var _this = this;
  78444. var parentCamera = this.parent;
  78445. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78446. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78447. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78448. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78449. //babylon compatible matrix
  78450. if (!this.getScene().useRightHandedSystem) {
  78451. [8, 9, 10, 11].forEach(function (num) {
  78452. _this._projectionMatrix.m[num] *= -1;
  78453. });
  78454. }
  78455. return this._projectionMatrix;
  78456. };
  78457. /**
  78458. * Initializes the controllers and their meshes
  78459. */
  78460. WebVRFreeCamera.prototype.initControllers = function () {
  78461. var _this = this;
  78462. this.controllers = [];
  78463. var manager = this.getScene().gamepadManager;
  78464. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78465. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78466. var webVrController = gamepad;
  78467. if (webVrController.defaultModel) {
  78468. webVrController.defaultModel.setEnabled(false);
  78469. }
  78470. if (webVrController.hand === "right") {
  78471. _this._rightController = null;
  78472. }
  78473. if (webVrController.hand === "left") {
  78474. _this._rightController = null;
  78475. }
  78476. var controllerIndex = _this.controllers.indexOf(webVrController);
  78477. if (controllerIndex !== -1) {
  78478. _this.controllers.splice(controllerIndex, 1);
  78479. }
  78480. }
  78481. });
  78482. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78483. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78484. var webVrController_1 = gamepad;
  78485. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78486. if (_this.webVROptions.controllerMeshes) {
  78487. if (webVrController_1.defaultModel) {
  78488. webVrController_1.defaultModel.setEnabled(true);
  78489. }
  78490. else {
  78491. // Load the meshes
  78492. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78493. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78494. if (_this.webVROptions.defaultLightingOnControllers) {
  78495. if (!_this._lightOnControllers) {
  78496. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78497. }
  78498. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78499. var children = mesh.getChildren();
  78500. if (children.length !== 0) {
  78501. children.forEach(function (mesh) {
  78502. light.includedOnlyMeshes.push(mesh);
  78503. activateLightOnSubMeshes_1(mesh, light);
  78504. });
  78505. }
  78506. };
  78507. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78508. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78509. }
  78510. });
  78511. }
  78512. }
  78513. webVrController_1.attachToPoseControlledCamera(_this);
  78514. // since this is async - sanity check. Is the controller already stored?
  78515. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78516. //add to the controllers array
  78517. _this.controllers.push(webVrController_1);
  78518. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78519. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78520. // So we're overriding setting left & right manually to be sure
  78521. var firstViveWandDetected = false;
  78522. for (var i = 0; i < _this.controllers.length; i++) {
  78523. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78524. if (!firstViveWandDetected) {
  78525. firstViveWandDetected = true;
  78526. _this.controllers[i].hand = "left";
  78527. }
  78528. else {
  78529. _this.controllers[i].hand = "right";
  78530. }
  78531. }
  78532. }
  78533. //did we find enough controllers? Great! let the developer know.
  78534. if (_this.controllers.length >= 2) {
  78535. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  78536. }
  78537. }
  78538. }
  78539. });
  78540. };
  78541. return WebVRFreeCamera;
  78542. }(BABYLON.FreeCamera));
  78543. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  78544. })(BABYLON || (BABYLON = {}));
  78545. //# sourceMappingURL=babylon.webVRCamera.js.map
  78546. var BABYLON;
  78547. (function (BABYLON) {
  78548. // We're mainly based on the logic defined into the FreeCamera code
  78549. /**
  78550. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  78551. * being tilted forward or back and left or right.
  78552. */
  78553. var DeviceOrientationCamera = /** @class */ (function (_super) {
  78554. __extends(DeviceOrientationCamera, _super);
  78555. /**
  78556. * Creates a new device orientation camera. @see DeviceOrientationCamera
  78557. * @param name The name of the camera
  78558. * @param position The start position camera
  78559. * @param scene The scene the camera belongs to
  78560. */
  78561. function DeviceOrientationCamera(name, position, scene) {
  78562. var _this = _super.call(this, name, position, scene) || this;
  78563. _this._quaternionCache = new BABYLON.Quaternion();
  78564. _this.inputs.addDeviceOrientation();
  78565. return _this;
  78566. }
  78567. /**
  78568. * Gets the current instance class name ("DeviceOrientationCamera").
  78569. * This helps avoiding instanceof at run time.
  78570. * @returns the class name
  78571. */
  78572. DeviceOrientationCamera.prototype.getClassName = function () {
  78573. return "DeviceOrientationCamera";
  78574. };
  78575. /**
  78576. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  78577. */
  78578. DeviceOrientationCamera.prototype._checkInputs = function () {
  78579. _super.prototype._checkInputs.call(this);
  78580. this._quaternionCache.copyFrom(this.rotationQuaternion);
  78581. if (this._initialQuaternion) {
  78582. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78583. }
  78584. };
  78585. /**
  78586. * Reset the camera to its default orientation on the specified axis only.
  78587. * @param axis The axis to reset
  78588. */
  78589. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  78590. var _this = this;
  78591. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  78592. //can only work if this camera has a rotation quaternion already.
  78593. if (!this.rotationQuaternion)
  78594. return;
  78595. if (!this._initialQuaternion) {
  78596. this._initialQuaternion = new BABYLON.Quaternion();
  78597. }
  78598. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  78599. ['x', 'y', 'z'].forEach(function (axisName) {
  78600. if (!axis[axisName]) {
  78601. _this._initialQuaternion[axisName] = 0;
  78602. }
  78603. else {
  78604. _this._initialQuaternion[axisName] *= -1;
  78605. }
  78606. });
  78607. this._initialQuaternion.normalize();
  78608. //force rotation update
  78609. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  78610. };
  78611. return DeviceOrientationCamera;
  78612. }(BABYLON.FreeCamera));
  78613. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  78614. })(BABYLON || (BABYLON = {}));
  78615. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  78616. var BABYLON;
  78617. (function (BABYLON) {
  78618. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  78619. __extends(VRDeviceOrientationFreeCamera, _super);
  78620. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78621. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78622. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78623. var _this = _super.call(this, name, position, scene) || this;
  78624. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78625. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78626. return _this;
  78627. }
  78628. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  78629. return "VRDeviceOrientationFreeCamera";
  78630. };
  78631. return VRDeviceOrientationFreeCamera;
  78632. }(BABYLON.DeviceOrientationCamera));
  78633. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  78634. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  78635. __extends(VRDeviceOrientationGamepadCamera, _super);
  78636. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  78637. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78638. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78639. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  78640. _this.inputs.addGamepad();
  78641. return _this;
  78642. }
  78643. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  78644. return "VRDeviceOrientationGamepadCamera";
  78645. };
  78646. return VRDeviceOrientationGamepadCamera;
  78647. }(VRDeviceOrientationFreeCamera));
  78648. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  78649. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  78650. __extends(VRDeviceOrientationArcRotateCamera, _super);
  78651. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  78652. if (compensateDistortion === void 0) { compensateDistortion = true; }
  78653. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  78654. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78655. vrCameraMetrics.compensateDistortion = compensateDistortion;
  78656. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  78657. _this.inputs.addVRDeviceOrientation();
  78658. return _this;
  78659. }
  78660. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  78661. return "VRDeviceOrientationArcRotateCamera";
  78662. };
  78663. return VRDeviceOrientationArcRotateCamera;
  78664. }(BABYLON.ArcRotateCamera));
  78665. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  78666. })(BABYLON || (BABYLON = {}));
  78667. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  78668. var BABYLON;
  78669. (function (BABYLON) {
  78670. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  78671. __extends(AnaglyphFreeCamera, _super);
  78672. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  78673. var _this = _super.call(this, name, position, scene) || this;
  78674. _this.interaxialDistance = interaxialDistance;
  78675. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78676. return _this;
  78677. }
  78678. AnaglyphFreeCamera.prototype.getClassName = function () {
  78679. return "AnaglyphFreeCamera";
  78680. };
  78681. return AnaglyphFreeCamera;
  78682. }(BABYLON.FreeCamera));
  78683. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  78684. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  78685. __extends(AnaglyphArcRotateCamera, _super);
  78686. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  78687. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78688. _this.interaxialDistance = interaxialDistance;
  78689. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78690. return _this;
  78691. }
  78692. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  78693. return "AnaglyphArcRotateCamera";
  78694. };
  78695. return AnaglyphArcRotateCamera;
  78696. }(BABYLON.ArcRotateCamera));
  78697. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  78698. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  78699. __extends(AnaglyphGamepadCamera, _super);
  78700. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  78701. var _this = _super.call(this, name, position, scene) || this;
  78702. _this.interaxialDistance = interaxialDistance;
  78703. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78704. return _this;
  78705. }
  78706. AnaglyphGamepadCamera.prototype.getClassName = function () {
  78707. return "AnaglyphGamepadCamera";
  78708. };
  78709. return AnaglyphGamepadCamera;
  78710. }(BABYLON.GamepadCamera));
  78711. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  78712. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  78713. __extends(AnaglyphUniversalCamera, _super);
  78714. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  78715. var _this = _super.call(this, name, position, scene) || this;
  78716. _this.interaxialDistance = interaxialDistance;
  78717. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  78718. return _this;
  78719. }
  78720. AnaglyphUniversalCamera.prototype.getClassName = function () {
  78721. return "AnaglyphUniversalCamera";
  78722. };
  78723. return AnaglyphUniversalCamera;
  78724. }(BABYLON.UniversalCamera));
  78725. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  78726. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  78727. __extends(StereoscopicFreeCamera, _super);
  78728. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78729. var _this = _super.call(this, name, position, scene) || this;
  78730. _this.interaxialDistance = interaxialDistance;
  78731. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78732. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78733. return _this;
  78734. }
  78735. StereoscopicFreeCamera.prototype.getClassName = function () {
  78736. return "StereoscopicFreeCamera";
  78737. };
  78738. return StereoscopicFreeCamera;
  78739. }(BABYLON.FreeCamera));
  78740. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  78741. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  78742. __extends(StereoscopicArcRotateCamera, _super);
  78743. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  78744. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  78745. _this.interaxialDistance = interaxialDistance;
  78746. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78747. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78748. return _this;
  78749. }
  78750. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  78751. return "StereoscopicArcRotateCamera";
  78752. };
  78753. return StereoscopicArcRotateCamera;
  78754. }(BABYLON.ArcRotateCamera));
  78755. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  78756. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  78757. __extends(StereoscopicGamepadCamera, _super);
  78758. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78759. var _this = _super.call(this, name, position, scene) || this;
  78760. _this.interaxialDistance = interaxialDistance;
  78761. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78762. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78763. return _this;
  78764. }
  78765. StereoscopicGamepadCamera.prototype.getClassName = function () {
  78766. return "StereoscopicGamepadCamera";
  78767. };
  78768. return StereoscopicGamepadCamera;
  78769. }(BABYLON.GamepadCamera));
  78770. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  78771. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  78772. __extends(StereoscopicUniversalCamera, _super);
  78773. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  78774. var _this = _super.call(this, name, position, scene) || this;
  78775. _this.interaxialDistance = interaxialDistance;
  78776. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  78777. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  78778. return _this;
  78779. }
  78780. StereoscopicUniversalCamera.prototype.getClassName = function () {
  78781. return "StereoscopicUniversalCamera";
  78782. };
  78783. return StereoscopicUniversalCamera;
  78784. }(BABYLON.UniversalCamera));
  78785. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  78786. })(BABYLON || (BABYLON = {}));
  78787. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  78788. var BABYLON;
  78789. (function (BABYLON) {
  78790. /**
  78791. * Helps to quickly add VR support to an existing scene.
  78792. * See http://doc.babylonjs.com/how_to/webvr_helper
  78793. */
  78794. var VRExperienceHelper = /** @class */ (function () {
  78795. /**
  78796. * Instantiates a VRExperienceHelper.
  78797. * Helps to quickly add VR support to an existing scene.
  78798. * @param scene The scene the VRExperienceHelper belongs to.
  78799. * @param webVROptions Options to modify the vr experience helper's behavior.
  78800. */
  78801. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  78802. if (webVROptions === void 0) { webVROptions = {}; }
  78803. var _this = this;
  78804. this.webVROptions = webVROptions;
  78805. // Can the system support WebVR, even if a headset isn't plugged in?
  78806. this._webVRsupported = false;
  78807. // If WebVR is supported, is a headset plugged in and are we ready to present?
  78808. this._webVRready = false;
  78809. // Are we waiting for the requestPresent callback to complete?
  78810. this._webVRrequesting = false;
  78811. // Are we presenting to the headset right now?
  78812. this._webVRpresenting = false;
  78813. // Are we presenting in the fullscreen fallback?
  78814. this._fullscreenVRpresenting = false;
  78815. /**
  78816. * Observable raised when entering VR.
  78817. */
  78818. this.onEnteringVRObservable = new BABYLON.Observable();
  78819. /**
  78820. * Observable raised when exiting VR.
  78821. */
  78822. this.onExitingVRObservable = new BABYLON.Observable();
  78823. /**
  78824. * Observable raised when controller mesh is loaded.
  78825. */
  78826. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78827. this._useCustomVRButton = false;
  78828. this._teleportationRequested = false;
  78829. this._teleportationEnabledOnLeftController = false;
  78830. this._teleportationEnabledOnRightController = false;
  78831. this._interactionsEnabledOnLeftController = false;
  78832. this._interactionsEnabledOnRightController = false;
  78833. this._leftControllerReady = false;
  78834. this._rightControllerReady = false;
  78835. this._floorMeshesCollection = [];
  78836. this._teleportationAllowed = false;
  78837. this._rotationAllowed = true;
  78838. this._teleportationRequestInitiated = false;
  78839. this._teleportationBackRequestInitiated = false;
  78840. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  78841. this._rotationRightAsked = false;
  78842. this._rotationLeftAsked = false;
  78843. this._isDefaultTeleportationTarget = true;
  78844. this._teleportationFillColor = "#444444";
  78845. this._teleportationBorderColor = "#FFFFFF";
  78846. this._rotationAngle = 0;
  78847. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  78848. this._padSensibilityUp = 0.65;
  78849. this._padSensibilityDown = 0.35;
  78850. /**
  78851. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  78852. */
  78853. this.onNewMeshSelected = new BABYLON.Observable();
  78854. /**
  78855. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  78856. */
  78857. this.onNewMeshPicked = new BABYLON.Observable();
  78858. /**
  78859. * Observable raised before camera teleportation
  78860. */
  78861. this.onBeforeCameraTeleport = new BABYLON.Observable();
  78862. /**
  78863. * Observable raised after camera teleportation
  78864. */
  78865. this.onAfterCameraTeleport = new BABYLON.Observable();
  78866. /**
  78867. * Observable raised when current selected mesh gets unselected
  78868. */
  78869. this.onSelectedMeshUnselected = new BABYLON.Observable();
  78870. /**
  78871. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  78872. */
  78873. this.teleportationEnabled = true;
  78874. this._pointerDownOnMeshAsked = false;
  78875. this._isActionableMesh = false;
  78876. this._teleportationInitialized = false;
  78877. this._interactionsEnabled = false;
  78878. this._interactionsRequested = false;
  78879. this._displayGaze = true;
  78880. this._displayLaserPointer = true;
  78881. this._dpadPressed = true;
  78882. this._onResize = function () {
  78883. _this.moveButtonToBottomRight();
  78884. if (_this._fullscreenVRpresenting && _this._webVRready) {
  78885. _this.exitVR();
  78886. }
  78887. };
  78888. this._onFullscreenChange = function () {
  78889. if (document.fullscreen !== undefined) {
  78890. _this._fullscreenVRpresenting = document.fullscreen;
  78891. }
  78892. else if (document.mozFullScreen !== undefined) {
  78893. _this._fullscreenVRpresenting = document.mozFullScreen;
  78894. }
  78895. else if (document.webkitIsFullScreen !== undefined) {
  78896. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  78897. }
  78898. else if (document.msIsFullScreen !== undefined) {
  78899. _this._fullscreenVRpresenting = document.msIsFullScreen;
  78900. }
  78901. if (!_this._fullscreenVRpresenting && _this._canvas) {
  78902. _this.exitVR();
  78903. if (!_this._useCustomVRButton) {
  78904. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  78905. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  78906. }
  78907. }
  78908. };
  78909. this.beforeRender = function () {
  78910. _this._castRayAndSelectObject();
  78911. };
  78912. this._onNewGamepadConnected = function (gamepad) {
  78913. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  78914. if (gamepad.leftStick) {
  78915. gamepad.onleftstickchanged(function (stickValues) {
  78916. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  78917. // Listening to classic/xbox gamepad only if no VR controller is active
  78918. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  78919. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  78920. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  78921. _this._checkTeleportWithRay(stickValues);
  78922. _this._checkTeleportBackwards(stickValues);
  78923. }
  78924. }
  78925. });
  78926. }
  78927. if (gamepad.rightStick) {
  78928. gamepad.onrightstickchanged(function (stickValues) {
  78929. if (_this._teleportationInitialized) {
  78930. _this._checkRotate(stickValues);
  78931. }
  78932. });
  78933. }
  78934. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  78935. gamepad.onbuttondown(function (buttonPressed) {
  78936. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78937. _this._selectionPointerDown();
  78938. }
  78939. });
  78940. gamepad.onbuttonup(function (buttonPressed) {
  78941. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  78942. _this._selectionPointerUp();
  78943. }
  78944. });
  78945. }
  78946. }
  78947. else {
  78948. var webVRController = gamepad;
  78949. _this._tryEnableInteractionOnController(webVRController);
  78950. }
  78951. };
  78952. // 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
  78953. this._tryEnableInteractionOnController = function (webVRController) {
  78954. if (webVRController.hand === "left") {
  78955. _this._leftControllerReady = true;
  78956. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  78957. _this._enableInteractionOnController(webVRController);
  78958. }
  78959. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  78960. _this._enableTeleportationOnController(webVRController);
  78961. }
  78962. }
  78963. if (webVRController.hand === "right") {
  78964. _this._rightControllerReady = true;
  78965. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  78966. _this._enableInteractionOnController(webVRController);
  78967. }
  78968. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  78969. _this._enableTeleportationOnController(webVRController);
  78970. }
  78971. }
  78972. };
  78973. this._onNewGamepadDisconnected = function (gamepad) {
  78974. if (gamepad instanceof BABYLON.WebVRController) {
  78975. if (gamepad.hand === "left") {
  78976. _this._interactionsEnabledOnLeftController = false;
  78977. _this._teleportationEnabledOnLeftController = false;
  78978. _this._leftControllerReady = false;
  78979. if (_this._leftLaserPointer) {
  78980. _this._leftLaserPointer.dispose();
  78981. }
  78982. }
  78983. if (gamepad.hand === "right") {
  78984. _this._interactionsEnabledOnRightController = false;
  78985. _this._teleportationEnabledOnRightController = false;
  78986. _this._rightControllerReady = false;
  78987. if (_this._rightLaserPointer) {
  78988. _this._rightLaserPointer.dispose();
  78989. }
  78990. }
  78991. }
  78992. };
  78993. this._workingVector = BABYLON.Vector3.Zero();
  78994. this._workingQuaternion = BABYLON.Quaternion.Identity();
  78995. this._workingMatrix = BABYLON.Matrix.Identity();
  78996. this._scene = scene;
  78997. this._canvas = scene.getEngine().getRenderingCanvas();
  78998. // Parse options
  78999. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  79000. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  79001. }
  79002. if (webVROptions.createDeviceOrientationCamera === undefined) {
  79003. webVROptions.createDeviceOrientationCamera = true;
  79004. }
  79005. if (webVROptions.defaultHeight === undefined) {
  79006. webVROptions.defaultHeight = 1.7;
  79007. }
  79008. if (webVROptions.useCustomVRButton) {
  79009. this._useCustomVRButton = true;
  79010. if (webVROptions.customVRButton) {
  79011. this._btnVR = webVROptions.customVRButton;
  79012. }
  79013. }
  79014. if (webVROptions.rayLength) {
  79015. this._rayLength = webVROptions.rayLength;
  79016. }
  79017. this._defaultHeight = webVROptions.defaultHeight;
  79018. // Set position
  79019. if (this._scene.activeCamera) {
  79020. this._position = this._scene.activeCamera.position.clone();
  79021. }
  79022. else {
  79023. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  79024. }
  79025. // Set non-vr camera
  79026. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  79027. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  79028. // Copy data from existing camera
  79029. if (this._scene.activeCamera) {
  79030. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  79031. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  79032. // Set rotation from previous camera
  79033. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  79034. var targetCamera = this._scene.activeCamera;
  79035. if (targetCamera.rotationQuaternion) {
  79036. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  79037. }
  79038. else {
  79039. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  79040. }
  79041. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  79042. }
  79043. }
  79044. this._scene.activeCamera = this._deviceOrientationCamera;
  79045. if (this._canvas) {
  79046. this._scene.activeCamera.attachControl(this._canvas);
  79047. }
  79048. }
  79049. else {
  79050. this._existingCamera = this._scene.activeCamera;
  79051. }
  79052. // Create VR cameras
  79053. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79054. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  79055. }
  79056. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  79057. this._webVRCamera.useStandingMatrix();
  79058. // Create default button
  79059. if (!this._useCustomVRButton) {
  79060. this._btnVR = document.createElement("BUTTON");
  79061. this._btnVR.className = "babylonVRicon";
  79062. this._btnVR.id = "babylonVRiconbtn";
  79063. this._btnVR.title = "Click to switch to VR";
  79064. 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) }";
  79065. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  79066. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  79067. // css += ".babylonVRicon.vrdisplaysupported { }";
  79068. // css += ".babylonVRicon.vrdisplayready { }";
  79069. // css += ".babylonVRicon.vrdisplayrequesting { }";
  79070. var style = document.createElement('style');
  79071. style.appendChild(document.createTextNode(css));
  79072. document.getElementsByTagName('head')[0].appendChild(style);
  79073. this.moveButtonToBottomRight();
  79074. }
  79075. // VR button click event
  79076. if (this._btnVR) {
  79077. this._btnVR.addEventListener("click", function () {
  79078. if (!_this.isInVRMode) {
  79079. _this.enterVR();
  79080. }
  79081. else {
  79082. _this.exitVR();
  79083. }
  79084. });
  79085. }
  79086. // Window events
  79087. window.addEventListener("resize", this._onResize);
  79088. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  79089. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  79090. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  79091. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  79092. // Display vr button when headset is connected
  79093. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79094. this.displayVRButton();
  79095. }
  79096. else {
  79097. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  79098. if (e.vrDisplay) {
  79099. _this.displayVRButton();
  79100. }
  79101. });
  79102. }
  79103. // Exiting VR mode using 'ESC' key on desktop
  79104. this._onKeyDown = function (event) {
  79105. if (event.keyCode === 27 && _this.isInVRMode) {
  79106. _this.exitVR();
  79107. }
  79108. };
  79109. document.addEventListener("keydown", this._onKeyDown);
  79110. // Exiting VR mode double tapping the touch screen
  79111. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  79112. if (_this.isInVRMode) {
  79113. _this.exitVR();
  79114. if (_this._fullscreenVRpresenting) {
  79115. _this._scene.getEngine().switchFullscreen(true);
  79116. }
  79117. }
  79118. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  79119. // Listen for WebVR display changes
  79120. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  79121. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  79122. this._onVRRequestPresentStart = function () {
  79123. _this._webVRrequesting = true;
  79124. _this.updateButtonVisibility();
  79125. };
  79126. this._onVRRequestPresentComplete = function (success) {
  79127. _this._webVRrequesting = false;
  79128. _this.updateButtonVisibility();
  79129. };
  79130. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  79131. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  79132. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  79133. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79134. scene.onDisposeObservable.add(function () {
  79135. _this.dispose();
  79136. });
  79137. // Gamepad connection events
  79138. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  79139. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  79140. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  79141. this.updateButtonVisibility();
  79142. //create easing functions
  79143. this._circleEase = new BABYLON.CircleEase();
  79144. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79145. }
  79146. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  79147. /** Return this.onEnteringVRObservable
  79148. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  79149. */
  79150. get: function () {
  79151. return this.onEnteringVRObservable;
  79152. },
  79153. enumerable: true,
  79154. configurable: true
  79155. });
  79156. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  79157. /** Return this.onExitingVRObservable
  79158. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  79159. */
  79160. get: function () {
  79161. return this.onExitingVRObservable;
  79162. },
  79163. enumerable: true,
  79164. configurable: true
  79165. });
  79166. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  79167. /** Return this.onControllerMeshLoadedObservable
  79168. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  79169. */
  79170. get: function () {
  79171. return this.onControllerMeshLoadedObservable;
  79172. },
  79173. enumerable: true,
  79174. configurable: true
  79175. });
  79176. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  79177. /**
  79178. * The mesh used to display where the user is going to teleport.
  79179. */
  79180. get: function () {
  79181. return this._teleportationTarget;
  79182. },
  79183. /**
  79184. * Sets the mesh to be used to display where the user is going to teleport.
  79185. */
  79186. set: function (value) {
  79187. if (value) {
  79188. value.name = "teleportationTarget";
  79189. this._isDefaultTeleportationTarget = false;
  79190. this._teleportationTarget = value;
  79191. }
  79192. },
  79193. enumerable: true,
  79194. configurable: true
  79195. });
  79196. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  79197. /**
  79198. * The mesh used to display where the user is selecting,
  79199. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  79200. * See http://doc.babylonjs.com/resources/baking_transformations
  79201. */
  79202. get: function () {
  79203. return this._gazeTracker;
  79204. },
  79205. set: function (value) {
  79206. if (value) {
  79207. this._gazeTracker = value;
  79208. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79209. this._gazeTracker.isPickable = false;
  79210. this._gazeTracker.isVisible = false;
  79211. }
  79212. },
  79213. enumerable: true,
  79214. configurable: true
  79215. });
  79216. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  79217. /**
  79218. * If the ray of the gaze should be displayed.
  79219. */
  79220. get: function () {
  79221. return this._displayGaze;
  79222. },
  79223. /**
  79224. * Sets if the ray of the gaze should be displayed.
  79225. */
  79226. set: function (value) {
  79227. this._displayGaze = value;
  79228. if (!value) {
  79229. this._gazeTracker.isVisible = false;
  79230. }
  79231. },
  79232. enumerable: true,
  79233. configurable: true
  79234. });
  79235. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  79236. /**
  79237. * If the ray of the LaserPointer should be displayed.
  79238. */
  79239. get: function () {
  79240. return this._displayLaserPointer;
  79241. },
  79242. /**
  79243. * Sets if the ray of the LaserPointer should be displayed.
  79244. */
  79245. set: function (value) {
  79246. this._displayLaserPointer = value;
  79247. if (!value) {
  79248. if (this._rightLaserPointer) {
  79249. this._rightLaserPointer.isVisible = false;
  79250. }
  79251. if (this._leftLaserPointer) {
  79252. this._leftLaserPointer.isVisible = false;
  79253. }
  79254. }
  79255. else {
  79256. if (this._rightLaserPointer) {
  79257. this._rightLaserPointer.isVisible = true;
  79258. }
  79259. else if (this._leftLaserPointer) {
  79260. this._leftLaserPointer.isVisible = true;
  79261. }
  79262. }
  79263. },
  79264. enumerable: true,
  79265. configurable: true
  79266. });
  79267. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  79268. /**
  79269. * The deviceOrientationCamera used as the camera when not in VR.
  79270. */
  79271. get: function () {
  79272. return this._deviceOrientationCamera;
  79273. },
  79274. enumerable: true,
  79275. configurable: true
  79276. });
  79277. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  79278. /**
  79279. * Based on the current WebVR support, returns the current VR camera used.
  79280. */
  79281. get: function () {
  79282. if (this._webVRready) {
  79283. return this._webVRCamera;
  79284. }
  79285. else {
  79286. return this._scene.activeCamera;
  79287. }
  79288. },
  79289. enumerable: true,
  79290. configurable: true
  79291. });
  79292. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  79293. /**
  79294. * The webVRCamera which is used when in VR.
  79295. */
  79296. get: function () {
  79297. return this._webVRCamera;
  79298. },
  79299. enumerable: true,
  79300. configurable: true
  79301. });
  79302. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  79303. /**
  79304. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  79305. */
  79306. get: function () {
  79307. return this._vrDeviceOrientationCamera;
  79308. },
  79309. enumerable: true,
  79310. configurable: true
  79311. });
  79312. // Raised when one of the controller has loaded successfully its associated default mesh
  79313. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  79314. this._tryEnableInteractionOnController(webVRController);
  79315. try {
  79316. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  79317. }
  79318. catch (err) {
  79319. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  79320. }
  79321. };
  79322. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  79323. /**
  79324. * Gets a value indicating if we are currently in VR mode.
  79325. */
  79326. get: function () {
  79327. return this._webVRpresenting || this._fullscreenVRpresenting;
  79328. },
  79329. enumerable: true,
  79330. configurable: true
  79331. });
  79332. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  79333. var vrDisplay = this._scene.getEngine().getVRDevice();
  79334. if (vrDisplay) {
  79335. var wasPresenting = this._webVRpresenting;
  79336. // A VR display is connected
  79337. this._webVRpresenting = vrDisplay.isPresenting;
  79338. if (wasPresenting && !this._webVRpresenting)
  79339. this.exitVR();
  79340. }
  79341. else {
  79342. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  79343. }
  79344. this.updateButtonVisibility();
  79345. };
  79346. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  79347. this._webVRsupported = eventArgs.vrSupported;
  79348. this._webVRready = !!eventArgs.vrDisplay;
  79349. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  79350. this.updateButtonVisibility();
  79351. };
  79352. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79353. if (this._canvas && !this._useCustomVRButton) {
  79354. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79355. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79356. }
  79357. };
  79358. VRExperienceHelper.prototype.displayVRButton = function () {
  79359. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79360. document.body.appendChild(this._btnVR);
  79361. this._btnVRDisplayed = true;
  79362. }
  79363. };
  79364. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79365. if (!this._btnVR || this._useCustomVRButton) {
  79366. return;
  79367. }
  79368. this._btnVR.className = "babylonVRicon";
  79369. if (this.isInVRMode) {
  79370. this._btnVR.className += " vrdisplaypresenting";
  79371. }
  79372. else {
  79373. if (this._webVRready)
  79374. this._btnVR.className += " vrdisplayready";
  79375. if (this._webVRsupported)
  79376. this._btnVR.className += " vrdisplaysupported";
  79377. if (this._webVRrequesting)
  79378. this._btnVR.className += " vrdisplayrequesting";
  79379. }
  79380. };
  79381. /**
  79382. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79383. * Otherwise, will use the fullscreen API.
  79384. */
  79385. VRExperienceHelper.prototype.enterVR = function () {
  79386. if (this.onEnteringVRObservable) {
  79387. try {
  79388. this.onEnteringVRObservable.notifyObservers(this);
  79389. }
  79390. catch (err) {
  79391. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79392. }
  79393. }
  79394. if (this._scene.activeCamera) {
  79395. this._position = this._scene.activeCamera.position.clone();
  79396. // make sure that we return to the last active camera
  79397. this._existingCamera = this._scene.activeCamera;
  79398. }
  79399. if (this._webVRrequesting)
  79400. return;
  79401. // If WebVR is supported and a headset is connected
  79402. if (this._webVRready) {
  79403. if (!this._webVRpresenting) {
  79404. this._webVRCamera.position = this._position;
  79405. this._scene.activeCamera = this._webVRCamera;
  79406. }
  79407. }
  79408. else if (this._vrDeviceOrientationCamera) {
  79409. this._vrDeviceOrientationCamera.position = this._position;
  79410. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79411. this._scene.getEngine().switchFullscreen(true);
  79412. this.updateButtonVisibility();
  79413. }
  79414. if (this._scene.activeCamera && this._canvas) {
  79415. this._scene.activeCamera.attachControl(this._canvas);
  79416. }
  79417. if (this._interactionsEnabled) {
  79418. this._scene.registerBeforeRender(this.beforeRender);
  79419. }
  79420. };
  79421. /**
  79422. * Attempt to exit VR, or fullscreen.
  79423. */
  79424. VRExperienceHelper.prototype.exitVR = function () {
  79425. if (this.onExitingVRObservable) {
  79426. try {
  79427. this.onExitingVRObservable.notifyObservers(this);
  79428. }
  79429. catch (err) {
  79430. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79431. }
  79432. }
  79433. if (this._webVRpresenting) {
  79434. this._scene.getEngine().disableVR();
  79435. }
  79436. if (this._scene.activeCamera) {
  79437. this._position = this._scene.activeCamera.position.clone();
  79438. }
  79439. if (this._deviceOrientationCamera) {
  79440. this._deviceOrientationCamera.position = this._position;
  79441. this._scene.activeCamera = this._deviceOrientationCamera;
  79442. if (this._canvas) {
  79443. this._scene.activeCamera.attachControl(this._canvas);
  79444. }
  79445. }
  79446. else if (this._existingCamera) {
  79447. this._existingCamera.position = this._position;
  79448. this._scene.activeCamera = this._existingCamera;
  79449. }
  79450. this.updateButtonVisibility();
  79451. if (this._interactionsEnabled) {
  79452. this._scene.unregisterBeforeRender(this.beforeRender);
  79453. }
  79454. };
  79455. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79456. /**
  79457. * The position of the vr experience helper.
  79458. */
  79459. get: function () {
  79460. return this._position;
  79461. },
  79462. /**
  79463. * Sets the position of the vr experience helper.
  79464. */
  79465. set: function (value) {
  79466. this._position = value;
  79467. if (this._scene.activeCamera) {
  79468. this._scene.activeCamera.position = value;
  79469. }
  79470. },
  79471. enumerable: true,
  79472. configurable: true
  79473. });
  79474. /**
  79475. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79476. */
  79477. VRExperienceHelper.prototype.enableInteractions = function () {
  79478. var _this = this;
  79479. if (!this._interactionsEnabled) {
  79480. this._interactionsRequested = true;
  79481. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79482. this._enableInteractionOnController(this._webVRCamera.leftController);
  79483. }
  79484. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79485. this._enableInteractionOnController(this._webVRCamera.rightController);
  79486. }
  79487. if (!this._gazeTracker) {
  79488. this._createGazeTracker();
  79489. }
  79490. this.raySelectionPredicate = function (mesh) {
  79491. return mesh.isVisible;
  79492. };
  79493. this.meshSelectionPredicate = function (mesh) {
  79494. return true;
  79495. };
  79496. this._raySelectionPredicate = function (mesh) {
  79497. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79498. && mesh.name.indexOf("teleportationTarget") === -1
  79499. && mesh.name.indexOf("torusTeleportation") === -1
  79500. && mesh.name.indexOf("laserPointer") === -1)) {
  79501. return _this.raySelectionPredicate(mesh);
  79502. }
  79503. return false;
  79504. };
  79505. this._interactionsEnabled = true;
  79506. }
  79507. };
  79508. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79509. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79510. if (this._floorMeshesCollection[i].id === mesh.id) {
  79511. return true;
  79512. }
  79513. }
  79514. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79515. return true;
  79516. }
  79517. return false;
  79518. };
  79519. /**
  79520. * Adds a floor mesh to be used for teleportation.
  79521. * @param floorMesh the mesh to be used for teleportation.
  79522. */
  79523. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79524. if (!this._floorMeshesCollection) {
  79525. return;
  79526. }
  79527. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79528. return;
  79529. }
  79530. this._floorMeshesCollection.push(floorMesh);
  79531. };
  79532. /**
  79533. * Removes a floor mesh from being used for teleportation.
  79534. * @param floorMesh the mesh to be removed.
  79535. */
  79536. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  79537. if (!this._floorMeshesCollection) {
  79538. return;
  79539. }
  79540. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  79541. if (meshIndex !== -1) {
  79542. this._floorMeshesCollection.splice(meshIndex, 1);
  79543. }
  79544. };
  79545. /**
  79546. * Enables interactions and teleportation using the VR controllers and gaze.
  79547. * @param vrTeleportationOptions options to modify teleportation behavior.
  79548. */
  79549. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  79550. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  79551. if (!this._teleportationInitialized) {
  79552. this._teleportationRequested = true;
  79553. this.enableInteractions();
  79554. if (vrTeleportationOptions.floorMeshName) {
  79555. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  79556. }
  79557. if (vrTeleportationOptions.floorMeshes) {
  79558. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  79559. }
  79560. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79561. this._enableTeleportationOnController(this._webVRCamera.leftController);
  79562. }
  79563. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79564. this._enableTeleportationOnController(this._webVRCamera.rightController);
  79565. }
  79566. // Creates an image processing post process for the vignette not relying
  79567. // on the main scene configuration for image processing to reduce setup and spaces
  79568. // (gamma/linear) conflicts.
  79569. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  79570. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  79571. imageProcessingConfiguration.vignetteEnabled = true;
  79572. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  79573. this._webVRCamera.detachPostProcess(this._postProcessMove);
  79574. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  79575. this._teleportationInitialized = true;
  79576. if (this._isDefaultTeleportationTarget) {
  79577. this._createTeleportationCircles();
  79578. }
  79579. }
  79580. };
  79581. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  79582. var _this = this;
  79583. var controllerMesh = webVRController.mesh;
  79584. if (controllerMesh) {
  79585. var makeNotPick = function (root) {
  79586. root.name += " laserPointer";
  79587. root.getChildMeshes().forEach(function (c) {
  79588. makeNotPick(c);
  79589. });
  79590. };
  79591. makeNotPick(controllerMesh);
  79592. var childMeshes = controllerMesh.getChildMeshes();
  79593. for (var i = 0; i < childMeshes.length; i++) {
  79594. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  79595. controllerMesh = childMeshes[i];
  79596. break;
  79597. }
  79598. }
  79599. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  79600. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  79601. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79602. laserPointerMaterial.alpha = 0.6;
  79603. laserPointer.material = laserPointerMaterial;
  79604. laserPointer.rotation.x = Math.PI / 2;
  79605. laserPointer.parent = controllerMesh;
  79606. laserPointer.position.z = -0.5;
  79607. laserPointer.isVisible = false;
  79608. if (webVRController.hand === "left") {
  79609. this._leftLaserPointer = laserPointer;
  79610. this._interactionsEnabledOnLeftController = true;
  79611. if (!this._rightLaserPointer) {
  79612. this._leftLaserPointer.isVisible = true;
  79613. }
  79614. }
  79615. else {
  79616. this._rightLaserPointer = laserPointer;
  79617. this._interactionsEnabledOnRightController = true;
  79618. if (!this._leftLaserPointer) {
  79619. this._rightLaserPointer.isVisible = true;
  79620. }
  79621. }
  79622. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  79623. // Enabling / disabling laserPointer
  79624. if (_this._displayLaserPointer && stateObject.value === 1) {
  79625. laserPointer.isVisible = !laserPointer.isVisible;
  79626. // Laser pointer can only be active on left or right, not both at the same time
  79627. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  79628. _this._rightLaserPointer.isVisible = false;
  79629. }
  79630. else if (_this._leftLaserPointer) {
  79631. _this._leftLaserPointer.isVisible = false;
  79632. }
  79633. }
  79634. });
  79635. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  79636. if (!_this._pointerDownOnMeshAsked) {
  79637. if (stateObject.value > _this._padSensibilityUp) {
  79638. _this._selectionPointerDown();
  79639. }
  79640. }
  79641. else if (stateObject.value < _this._padSensibilityDown) {
  79642. _this._selectionPointerUp();
  79643. }
  79644. });
  79645. }
  79646. };
  79647. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  79648. if (webVRController === void 0) { webVRController = null; }
  79649. if (!this._teleportationRequestInitiated) {
  79650. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  79651. if (webVRController) {
  79652. // If laser pointer wasn't enabled yet
  79653. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  79654. this._leftLaserPointer.isVisible = true;
  79655. if (this._rightLaserPointer) {
  79656. this._rightLaserPointer.isVisible = false;
  79657. }
  79658. }
  79659. else if (this._displayLaserPointer && this._rightLaserPointer) {
  79660. this._rightLaserPointer.isVisible = true;
  79661. if (this._leftLaserPointer) {
  79662. this._leftLaserPointer.isVisible = false;
  79663. }
  79664. }
  79665. }
  79666. this._teleportationRequestInitiated = true;
  79667. }
  79668. }
  79669. else {
  79670. // Listening to the proper controller values changes to confirm teleportation
  79671. if (webVRController == null
  79672. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  79673. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  79674. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  79675. if (this._teleportationAllowed) {
  79676. this._teleportationAllowed = false;
  79677. this._teleportCamera();
  79678. }
  79679. this._teleportationRequestInitiated = false;
  79680. }
  79681. }
  79682. }
  79683. };
  79684. VRExperienceHelper.prototype._selectionPointerDown = function () {
  79685. this._pointerDownOnMeshAsked = true;
  79686. if (this._currentMeshSelected && this._currentHit) {
  79687. this._scene.simulatePointerDown(this._currentHit);
  79688. }
  79689. };
  79690. VRExperienceHelper.prototype._selectionPointerUp = function () {
  79691. if (this._currentMeshSelected && this._currentHit) {
  79692. this._scene.simulatePointerUp(this._currentHit);
  79693. }
  79694. this._pointerDownOnMeshAsked = false;
  79695. };
  79696. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  79697. // Only rotate when user is not currently selecting a teleportation location
  79698. if (this._teleportationRequestInitiated) {
  79699. return;
  79700. }
  79701. if (!this._rotationLeftAsked) {
  79702. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  79703. this._rotationLeftAsked = true;
  79704. if (this._rotationAllowed) {
  79705. this._rotateCamera(false);
  79706. }
  79707. }
  79708. }
  79709. else {
  79710. if (stateObject.x > -this._padSensibilityDown) {
  79711. this._rotationLeftAsked = false;
  79712. }
  79713. }
  79714. if (!this._rotationRightAsked) {
  79715. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  79716. this._rotationRightAsked = true;
  79717. if (this._rotationAllowed) {
  79718. this._rotateCamera(true);
  79719. }
  79720. }
  79721. }
  79722. else {
  79723. if (stateObject.x < this._padSensibilityDown) {
  79724. this._rotationRightAsked = false;
  79725. }
  79726. }
  79727. };
  79728. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  79729. // Only teleport backwards when user is not currently selecting a teleportation location
  79730. if (this._teleportationRequestInitiated) {
  79731. return;
  79732. }
  79733. // Teleport backwards
  79734. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  79735. if (!this._teleportationBackRequestInitiated) {
  79736. if (!this.currentVRCamera) {
  79737. return;
  79738. }
  79739. // Get rotation and position of the current camera
  79740. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  79741. var position = this.currentVRCamera.position;
  79742. // If the camera has device position, use that instead
  79743. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  79744. rotation = this.currentVRCamera.deviceRotationQuaternion;
  79745. position = this.currentVRCamera.devicePosition;
  79746. }
  79747. // Get matrix with only the y rotation of the device rotation
  79748. rotation.toEulerAnglesToRef(this._workingVector);
  79749. this._workingVector.z = 0;
  79750. this._workingVector.x = 0;
  79751. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  79752. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  79753. // Rotate backwards ray by device rotation to cast at the ground behind the user
  79754. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  79755. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  79756. var ray = new BABYLON.Ray(position, this._workingVector);
  79757. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  79758. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  79759. this._teleportCamera(hit.pickedPoint);
  79760. }
  79761. this._teleportationBackRequestInitiated = true;
  79762. }
  79763. }
  79764. else {
  79765. this._teleportationBackRequestInitiated = false;
  79766. }
  79767. };
  79768. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  79769. var _this = this;
  79770. var controllerMesh = webVRController.mesh;
  79771. if (controllerMesh) {
  79772. if (webVRController.hand === "left") {
  79773. if (!this._interactionsEnabledOnLeftController) {
  79774. this._enableInteractionOnController(webVRController);
  79775. }
  79776. this._teleportationEnabledOnLeftController = true;
  79777. }
  79778. else {
  79779. if (!this._interactionsEnabledOnRightController) {
  79780. this._enableInteractionOnController(webVRController);
  79781. }
  79782. this._teleportationEnabledOnRightController = true;
  79783. }
  79784. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79785. this._dpadPressed = false;
  79786. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  79787. _this._dpadPressed = stateObject.pressed;
  79788. if (!_this._dpadPressed) {
  79789. _this._rotationLeftAsked = false;
  79790. _this._rotationRightAsked = false;
  79791. _this._teleportationBackRequestInitiated = false;
  79792. }
  79793. });
  79794. }
  79795. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  79796. if (_this.teleportationEnabled) {
  79797. _this._checkTeleportBackwards(stateObject);
  79798. _this._checkTeleportWithRay(stateObject, webVRController);
  79799. }
  79800. _this._checkRotate(stateObject);
  79801. });
  79802. }
  79803. };
  79804. // Gaze support used to point to teleport or to interact with an object
  79805. VRExperienceHelper.prototype._createGazeTracker = function () {
  79806. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  79807. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79808. this._gazeTracker.isPickable = false;
  79809. this._gazeTracker.isVisible = false;
  79810. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  79811. targetMat.specularColor = BABYLON.Color3.Black();
  79812. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  79813. targetMat.backFaceCulling = false;
  79814. this._gazeTracker.material = targetMat;
  79815. };
  79816. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  79817. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  79818. this._teleportationTarget.isPickable = false;
  79819. var length = 512;
  79820. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  79821. dynamicTexture.hasAlpha = true;
  79822. var context = dynamicTexture.getContext();
  79823. var centerX = length / 2;
  79824. var centerY = length / 2;
  79825. var radius = 200;
  79826. context.beginPath();
  79827. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  79828. context.fillStyle = this._teleportationFillColor;
  79829. context.fill();
  79830. context.lineWidth = 10;
  79831. context.strokeStyle = this._teleportationBorderColor;
  79832. context.stroke();
  79833. context.closePath();
  79834. dynamicTexture.update();
  79835. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  79836. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  79837. this._teleportationTarget.material = teleportationCircleMaterial;
  79838. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  79839. torus.isPickable = false;
  79840. torus.parent = this._teleportationTarget;
  79841. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  79842. var keys = [];
  79843. keys.push({
  79844. frame: 0,
  79845. value: 0
  79846. });
  79847. keys.push({
  79848. frame: 30,
  79849. value: 0.4
  79850. });
  79851. keys.push({
  79852. frame: 60,
  79853. value: 0
  79854. });
  79855. animationInnerCircle.setKeys(keys);
  79856. var easingFunction = new BABYLON.SineEase();
  79857. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79858. animationInnerCircle.setEasingFunction(easingFunction);
  79859. torus.animations = [];
  79860. torus.animations.push(animationInnerCircle);
  79861. this._scene.beginAnimation(torus, 0, 60, true);
  79862. this._hideTeleportationTarget();
  79863. };
  79864. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  79865. if (this._teleportationInitialized) {
  79866. this._teleportationTarget.isVisible = true;
  79867. if (this._isDefaultTeleportationTarget) {
  79868. this._teleportationTarget.getChildren()[0].isVisible = true;
  79869. }
  79870. }
  79871. };
  79872. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  79873. if (this._teleportationInitialized) {
  79874. this._teleportationTarget.isVisible = false;
  79875. if (this._isDefaultTeleportationTarget) {
  79876. this._teleportationTarget.getChildren()[0].isVisible = false;
  79877. }
  79878. }
  79879. };
  79880. VRExperienceHelper.prototype._rotateCamera = function (right) {
  79881. var _this = this;
  79882. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79883. return;
  79884. }
  79885. if (right) {
  79886. this._rotationAngle++;
  79887. }
  79888. else {
  79889. this._rotationAngle--;
  79890. }
  79891. this.currentVRCamera.animations = [];
  79892. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  79893. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79894. var animationRotationKeys = [];
  79895. animationRotationKeys.push({
  79896. frame: 0,
  79897. value: this.currentVRCamera.rotationQuaternion
  79898. });
  79899. animationRotationKeys.push({
  79900. frame: 6,
  79901. value: target
  79902. });
  79903. animationRotation.setKeys(animationRotationKeys);
  79904. animationRotation.setEasingFunction(this._circleEase);
  79905. this.currentVRCamera.animations.push(animationRotation);
  79906. this._postProcessMove.animations = [];
  79907. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79908. var vignetteWeightKeys = [];
  79909. vignetteWeightKeys.push({
  79910. frame: 0,
  79911. value: 0
  79912. });
  79913. vignetteWeightKeys.push({
  79914. frame: 3,
  79915. value: 4
  79916. });
  79917. vignetteWeightKeys.push({
  79918. frame: 6,
  79919. value: 0
  79920. });
  79921. animationPP.setKeys(vignetteWeightKeys);
  79922. animationPP.setEasingFunction(this._circleEase);
  79923. this._postProcessMove.animations.push(animationPP);
  79924. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79925. var vignetteStretchKeys = [];
  79926. vignetteStretchKeys.push({
  79927. frame: 0,
  79928. value: 0
  79929. });
  79930. vignetteStretchKeys.push({
  79931. frame: 3,
  79932. value: 10
  79933. });
  79934. vignetteStretchKeys.push({
  79935. frame: 6,
  79936. value: 0
  79937. });
  79938. animationPP2.setKeys(vignetteStretchKeys);
  79939. animationPP2.setEasingFunction(this._circleEase);
  79940. this._postProcessMove.animations.push(animationPP2);
  79941. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  79942. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  79943. this._webVRCamera.attachPostProcess(this._postProcessMove);
  79944. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  79945. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  79946. });
  79947. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  79948. };
  79949. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  79950. if (hit.pickedPoint) {
  79951. this._teleportationAllowed = true;
  79952. if (this._teleportationRequestInitiated) {
  79953. this._displayTeleportationTarget();
  79954. }
  79955. else {
  79956. this._hideTeleportationTarget();
  79957. }
  79958. this._haloCenter.copyFrom(hit.pickedPoint);
  79959. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  79960. var pickNormal = hit.getNormal(true, false);
  79961. if (pickNormal) {
  79962. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  79963. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  79964. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  79965. }
  79966. this._teleportationTarget.position.y += 0.1;
  79967. }
  79968. };
  79969. VRExperienceHelper.prototype._teleportCamera = function (location) {
  79970. var _this = this;
  79971. if (location === void 0) { location = null; }
  79972. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  79973. return;
  79974. }
  79975. if (!location) {
  79976. location = this._haloCenter;
  79977. }
  79978. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  79979. // offset of the headset from the anchor.
  79980. if (this.webVRCamera.leftCamera) {
  79981. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  79982. this._workingVector.subtractInPlace(this.webVRCamera.position);
  79983. location.subtractToRef(this._workingVector, this._workingVector);
  79984. }
  79985. else {
  79986. this._workingVector.copyFrom(location);
  79987. }
  79988. // Add height to account for user's height offset
  79989. if (this.isInVRMode) {
  79990. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  79991. }
  79992. else {
  79993. this._workingVector.y += this._defaultHeight;
  79994. }
  79995. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  79996. // Create animation from the camera's position to the new location
  79997. this.currentVRCamera.animations = [];
  79998. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  79999. var animationCameraTeleportationKeys = [{
  80000. frame: 0,
  80001. value: this.currentVRCamera.position
  80002. },
  80003. {
  80004. frame: 11,
  80005. value: this._workingVector
  80006. }
  80007. ];
  80008. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  80009. animationCameraTeleportation.setEasingFunction(this._circleEase);
  80010. this.currentVRCamera.animations.push(animationCameraTeleportation);
  80011. this._postProcessMove.animations = [];
  80012. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80013. var vignetteWeightKeys = [];
  80014. vignetteWeightKeys.push({
  80015. frame: 0,
  80016. value: 0
  80017. });
  80018. vignetteWeightKeys.push({
  80019. frame: 5,
  80020. value: 8
  80021. });
  80022. vignetteWeightKeys.push({
  80023. frame: 11,
  80024. value: 0
  80025. });
  80026. animationPP.setKeys(vignetteWeightKeys);
  80027. this._postProcessMove.animations.push(animationPP);
  80028. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80029. var vignetteStretchKeys = [];
  80030. vignetteStretchKeys.push({
  80031. frame: 0,
  80032. value: 0
  80033. });
  80034. vignetteStretchKeys.push({
  80035. frame: 5,
  80036. value: 10
  80037. });
  80038. vignetteStretchKeys.push({
  80039. frame: 11,
  80040. value: 0
  80041. });
  80042. animationPP2.setKeys(vignetteStretchKeys);
  80043. this._postProcessMove.animations.push(animationPP2);
  80044. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  80045. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  80046. this._webVRCamera.attachPostProcess(this._postProcessMove);
  80047. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  80048. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  80049. });
  80050. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  80051. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  80052. });
  80053. };
  80054. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  80055. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80056. return;
  80057. }
  80058. var ray;
  80059. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  80060. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  80061. }
  80062. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  80063. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  80064. }
  80065. else {
  80066. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  80067. }
  80068. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80069. // Moving the gazeTracker on the mesh face targetted
  80070. if (hit && hit.pickedPoint) {
  80071. if (this._displayGaze) {
  80072. var multiplier = 1;
  80073. this._gazeTracker.isVisible = true;
  80074. if (this._isActionableMesh) {
  80075. multiplier = 3;
  80076. }
  80077. this._gazeTracker.scaling.x = hit.distance * multiplier;
  80078. this._gazeTracker.scaling.y = hit.distance * multiplier;
  80079. this._gazeTracker.scaling.z = hit.distance * multiplier;
  80080. var pickNormal = hit.getNormal();
  80081. // To avoid z-fighting
  80082. var deltaFighting = 0.002;
  80083. if (pickNormal) {
  80084. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  80085. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80086. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  80087. }
  80088. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  80089. if (this._gazeTracker.position.x < 0) {
  80090. this._gazeTracker.position.x += deltaFighting;
  80091. }
  80092. else {
  80093. this._gazeTracker.position.x -= deltaFighting;
  80094. }
  80095. if (this._gazeTracker.position.y < 0) {
  80096. this._gazeTracker.position.y += deltaFighting;
  80097. }
  80098. else {
  80099. this._gazeTracker.position.y -= deltaFighting;
  80100. }
  80101. if (this._gazeTracker.position.z < 0) {
  80102. this._gazeTracker.position.z += deltaFighting;
  80103. }
  80104. else {
  80105. this._gazeTracker.position.z -= deltaFighting;
  80106. }
  80107. }
  80108. // Changing the size of the laser pointer based on the distance from the targetted point
  80109. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  80110. this._rightLaserPointer.scaling.y = hit.distance;
  80111. this._rightLaserPointer.position.z = -hit.distance / 2;
  80112. }
  80113. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  80114. this._leftLaserPointer.scaling.y = hit.distance;
  80115. this._leftLaserPointer.position.z = -hit.distance / 2;
  80116. }
  80117. }
  80118. else {
  80119. this._gazeTracker.isVisible = false;
  80120. }
  80121. if (hit && hit.pickedMesh) {
  80122. this._currentHit = hit;
  80123. if (this._pointerDownOnMeshAsked) {
  80124. this._scene.simulatePointerMove(this._currentHit);
  80125. }
  80126. // The object selected is the floor, we're in a teleportation scenario
  80127. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  80128. // Moving the teleportation area to this targetted point
  80129. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  80130. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  80131. this._notifySelectedMeshUnselected();
  80132. }
  80133. this._currentMeshSelected = null;
  80134. this._moveTeleportationSelectorTo(hit);
  80135. return;
  80136. }
  80137. // If not, we're in a selection scenario
  80138. this._hideTeleportationTarget();
  80139. this._teleportationAllowed = false;
  80140. if (hit.pickedMesh !== this._currentMeshSelected) {
  80141. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  80142. this.onNewMeshPicked.notifyObservers(hit);
  80143. this._currentMeshSelected = hit.pickedMesh;
  80144. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  80145. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  80146. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  80147. this._isActionableMesh = true;
  80148. }
  80149. else {
  80150. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80151. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80152. this._isActionableMesh = false;
  80153. }
  80154. try {
  80155. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  80156. }
  80157. catch (err) {
  80158. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  80159. }
  80160. }
  80161. else {
  80162. this._notifySelectedMeshUnselected();
  80163. this._currentMeshSelected = null;
  80164. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80165. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80166. }
  80167. }
  80168. }
  80169. else {
  80170. this._currentHit = null;
  80171. this._notifySelectedMeshUnselected();
  80172. this._currentMeshSelected = null;
  80173. this._teleportationAllowed = false;
  80174. this._hideTeleportationTarget();
  80175. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80176. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80177. }
  80178. };
  80179. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  80180. if (this._currentMeshSelected) {
  80181. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  80182. }
  80183. };
  80184. /**
  80185. * Sets the color of the laser ray from the vr controllers.
  80186. * @param color new color for the ray.
  80187. */
  80188. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  80189. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  80190. this._leftLaserPointer.material.emissiveColor = color;
  80191. }
  80192. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  80193. this._rightLaserPointer.material.emissiveColor = color;
  80194. }
  80195. };
  80196. /**
  80197. * Sets the color of the ray from the vr headsets gaze.
  80198. * @param color new color for the ray.
  80199. */
  80200. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  80201. if (this._gazeTracker.material) {
  80202. this._gazeTracker.material.emissiveColor = color;
  80203. }
  80204. };
  80205. /**
  80206. * Exits VR and disposes of the vr experience helper
  80207. */
  80208. VRExperienceHelper.prototype.dispose = function () {
  80209. if (this.isInVRMode) {
  80210. this.exitVR();
  80211. }
  80212. if (this._passProcessMove) {
  80213. this._passProcessMove.dispose();
  80214. }
  80215. if (this._postProcessMove) {
  80216. this._postProcessMove.dispose();
  80217. }
  80218. if (this._webVRCamera) {
  80219. this._webVRCamera.dispose();
  80220. }
  80221. if (this._vrDeviceOrientationCamera) {
  80222. this._vrDeviceOrientationCamera.dispose();
  80223. }
  80224. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  80225. document.body.removeChild(this._btnVR);
  80226. }
  80227. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  80228. this._deviceOrientationCamera.dispose();
  80229. }
  80230. if (this._gazeTracker) {
  80231. this._gazeTracker.dispose();
  80232. }
  80233. if (this._teleportationTarget) {
  80234. this._teleportationTarget.dispose();
  80235. }
  80236. this._floorMeshesCollection = [];
  80237. document.removeEventListener("keydown", this._onKeyDown);
  80238. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80239. window.removeEventListener("resize", this._onResize);
  80240. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  80241. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  80242. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  80243. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  80244. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  80245. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  80246. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  80247. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80248. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  80249. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  80250. this._scene.unregisterBeforeRender(this.beforeRender);
  80251. };
  80252. /**
  80253. * Gets the name of the VRExperienceHelper class
  80254. * @returns "VRExperienceHelper"
  80255. */
  80256. VRExperienceHelper.prototype.getClassName = function () {
  80257. return "VRExperienceHelper";
  80258. };
  80259. return VRExperienceHelper;
  80260. }());
  80261. BABYLON.VRExperienceHelper = VRExperienceHelper;
  80262. })(BABYLON || (BABYLON = {}));
  80263. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  80264. // Mainly based on these 2 articles :
  80265. // 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
  80266. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  80267. var BABYLON;
  80268. (function (BABYLON) {
  80269. var JoystickAxis;
  80270. (function (JoystickAxis) {
  80271. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  80272. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  80273. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  80274. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  80275. var VirtualJoystick = /** @class */ (function () {
  80276. function VirtualJoystick(leftJoystick) {
  80277. var _this = this;
  80278. if (leftJoystick) {
  80279. this._leftJoystick = true;
  80280. }
  80281. else {
  80282. this._leftJoystick = false;
  80283. }
  80284. VirtualJoystick._globalJoystickIndex++;
  80285. // By default left & right arrow keys are moving the X
  80286. // and up & down keys are moving the Y
  80287. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80288. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80289. this.reverseLeftRight = false;
  80290. this.reverseUpDown = false;
  80291. // collections of pointers
  80292. this._touches = new BABYLON.StringDictionary();
  80293. this.deltaPosition = BABYLON.Vector3.Zero();
  80294. this._joystickSensibility = 25;
  80295. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80296. this._onResize = function (evt) {
  80297. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80298. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80299. if (VirtualJoystick.vjCanvas) {
  80300. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  80301. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  80302. }
  80303. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  80304. };
  80305. // injecting a canvas element on top of the canvas 3D game
  80306. if (!VirtualJoystick.vjCanvas) {
  80307. window.addEventListener("resize", this._onResize, false);
  80308. VirtualJoystick.vjCanvas = document.createElement("canvas");
  80309. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80310. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80311. VirtualJoystick.vjCanvas.width = window.innerWidth;
  80312. VirtualJoystick.vjCanvas.height = window.innerHeight;
  80313. VirtualJoystick.vjCanvas.style.width = "100%";
  80314. VirtualJoystick.vjCanvas.style.height = "100%";
  80315. VirtualJoystick.vjCanvas.style.position = "absolute";
  80316. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  80317. VirtualJoystick.vjCanvas.style.top = "0px";
  80318. VirtualJoystick.vjCanvas.style.left = "0px";
  80319. VirtualJoystick.vjCanvas.style.zIndex = "5";
  80320. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  80321. // Support for jQuery PEP polyfill
  80322. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  80323. var context = VirtualJoystick.vjCanvas.getContext('2d');
  80324. if (!context) {
  80325. throw new Error("Unable to create canvas for virtual joystick");
  80326. }
  80327. VirtualJoystick.vjCanvasContext = context;
  80328. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  80329. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80330. document.body.appendChild(VirtualJoystick.vjCanvas);
  80331. }
  80332. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  80333. this.pressed = false;
  80334. // default joystick color
  80335. this._joystickColor = "cyan";
  80336. this._joystickPointerID = -1;
  80337. // current joystick position
  80338. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  80339. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  80340. // origin joystick position
  80341. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  80342. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  80343. this._onPointerDownHandlerRef = function (evt) {
  80344. _this._onPointerDown(evt);
  80345. };
  80346. this._onPointerMoveHandlerRef = function (evt) {
  80347. _this._onPointerMove(evt);
  80348. };
  80349. this._onPointerUpHandlerRef = function (evt) {
  80350. _this._onPointerUp(evt);
  80351. };
  80352. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80353. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80354. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80355. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80356. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80357. evt.preventDefault(); // Disables system menu
  80358. }, false);
  80359. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80360. }
  80361. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80362. this._joystickSensibility = newJoystickSensibility;
  80363. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80364. };
  80365. VirtualJoystick.prototype._onPointerDown = function (e) {
  80366. var positionOnScreenCondition;
  80367. e.preventDefault();
  80368. if (this._leftJoystick === true) {
  80369. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80370. }
  80371. else {
  80372. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80373. }
  80374. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80375. // First contact will be dedicated to the virtual joystick
  80376. this._joystickPointerID = e.pointerId;
  80377. this._joystickPointerStartPos.x = e.clientX;
  80378. this._joystickPointerStartPos.y = e.clientY;
  80379. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80380. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80381. this._deltaJoystickVector.x = 0;
  80382. this._deltaJoystickVector.y = 0;
  80383. this.pressed = true;
  80384. this._touches.add(e.pointerId.toString(), e);
  80385. }
  80386. else {
  80387. // You can only trigger the action buttons with a joystick declared
  80388. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80389. this._action();
  80390. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80391. }
  80392. }
  80393. };
  80394. VirtualJoystick.prototype._onPointerMove = function (e) {
  80395. // If the current pointer is the one associated to the joystick (first touch contact)
  80396. if (this._joystickPointerID == e.pointerId) {
  80397. this._joystickPointerPos.x = e.clientX;
  80398. this._joystickPointerPos.y = e.clientY;
  80399. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80400. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80401. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80402. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80403. switch (this._axisTargetedByLeftAndRight) {
  80404. case JoystickAxis.X:
  80405. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80406. break;
  80407. case JoystickAxis.Y:
  80408. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80409. break;
  80410. case JoystickAxis.Z:
  80411. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80412. break;
  80413. }
  80414. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80415. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80416. switch (this._axisTargetedByUpAndDown) {
  80417. case JoystickAxis.X:
  80418. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80419. break;
  80420. case JoystickAxis.Y:
  80421. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80422. break;
  80423. case JoystickAxis.Z:
  80424. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80425. break;
  80426. }
  80427. }
  80428. else {
  80429. var data = this._touches.get(e.pointerId.toString());
  80430. if (data) {
  80431. data.x = e.clientX;
  80432. data.y = e.clientY;
  80433. }
  80434. }
  80435. };
  80436. VirtualJoystick.prototype._onPointerUp = function (e) {
  80437. if (this._joystickPointerID == e.pointerId) {
  80438. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80439. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80440. this._joystickPointerID = -1;
  80441. this.pressed = false;
  80442. }
  80443. else {
  80444. var touch = this._touches.get(e.pointerId.toString());
  80445. if (touch) {
  80446. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80447. }
  80448. }
  80449. this._deltaJoystickVector.x = 0;
  80450. this._deltaJoystickVector.y = 0;
  80451. this._touches.remove(e.pointerId.toString());
  80452. };
  80453. /**
  80454. * Change the color of the virtual joystick
  80455. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80456. */
  80457. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80458. this._joystickColor = newColor;
  80459. };
  80460. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80461. this._action = action;
  80462. };
  80463. // Define which axis you'd like to control for left & right
  80464. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80465. switch (axis) {
  80466. case JoystickAxis.X:
  80467. case JoystickAxis.Y:
  80468. case JoystickAxis.Z:
  80469. this._axisTargetedByLeftAndRight = axis;
  80470. break;
  80471. default:
  80472. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80473. break;
  80474. }
  80475. };
  80476. // Define which axis you'd like to control for up & down
  80477. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80478. switch (axis) {
  80479. case JoystickAxis.X:
  80480. case JoystickAxis.Y:
  80481. case JoystickAxis.Z:
  80482. this._axisTargetedByUpAndDown = axis;
  80483. break;
  80484. default:
  80485. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80486. break;
  80487. }
  80488. };
  80489. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80490. var _this = this;
  80491. if (this.pressed) {
  80492. this._touches.forEach(function (key, touch) {
  80493. if (touch.pointerId === _this._joystickPointerID) {
  80494. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80495. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80496. VirtualJoystick.vjCanvasContext.beginPath();
  80497. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80498. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80499. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80500. VirtualJoystick.vjCanvasContext.stroke();
  80501. VirtualJoystick.vjCanvasContext.closePath();
  80502. VirtualJoystick.vjCanvasContext.beginPath();
  80503. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80504. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80505. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80506. VirtualJoystick.vjCanvasContext.stroke();
  80507. VirtualJoystick.vjCanvasContext.closePath();
  80508. VirtualJoystick.vjCanvasContext.beginPath();
  80509. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80510. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80511. VirtualJoystick.vjCanvasContext.stroke();
  80512. VirtualJoystick.vjCanvasContext.closePath();
  80513. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80514. }
  80515. else {
  80516. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80517. VirtualJoystick.vjCanvasContext.beginPath();
  80518. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80519. VirtualJoystick.vjCanvasContext.beginPath();
  80520. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80521. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80522. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80523. VirtualJoystick.vjCanvasContext.stroke();
  80524. VirtualJoystick.vjCanvasContext.closePath();
  80525. touch.prevX = touch.x;
  80526. touch.prevY = touch.y;
  80527. }
  80528. ;
  80529. });
  80530. }
  80531. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80532. };
  80533. VirtualJoystick.prototype.releaseCanvas = function () {
  80534. if (VirtualJoystick.vjCanvas) {
  80535. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  80536. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  80537. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  80538. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  80539. window.removeEventListener("resize", this._onResize);
  80540. document.body.removeChild(VirtualJoystick.vjCanvas);
  80541. VirtualJoystick.vjCanvas = null;
  80542. }
  80543. };
  80544. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  80545. VirtualJoystick._globalJoystickIndex = 0;
  80546. return VirtualJoystick;
  80547. }());
  80548. BABYLON.VirtualJoystick = VirtualJoystick;
  80549. })(BABYLON || (BABYLON = {}));
  80550. //# sourceMappingURL=babylon.virtualJoystick.js.map
  80551. var BABYLON;
  80552. (function (BABYLON) {
  80553. // We're mainly based on the logic defined into the FreeCamera code
  80554. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  80555. __extends(VirtualJoysticksCamera, _super);
  80556. function VirtualJoysticksCamera(name, position, scene) {
  80557. var _this = _super.call(this, name, position, scene) || this;
  80558. _this.inputs.addVirtualJoystick();
  80559. return _this;
  80560. }
  80561. VirtualJoysticksCamera.prototype.getClassName = function () {
  80562. return "VirtualJoysticksCamera";
  80563. };
  80564. return VirtualJoysticksCamera;
  80565. }(BABYLON.FreeCamera));
  80566. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  80567. })(BABYLON || (BABYLON = {}));
  80568. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  80569. var BABYLON;
  80570. (function (BABYLON) {
  80571. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  80572. function FreeCameraVirtualJoystickInput() {
  80573. }
  80574. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  80575. return this._leftjoystick;
  80576. };
  80577. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  80578. return this._rightjoystick;
  80579. };
  80580. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  80581. if (this._leftjoystick) {
  80582. var camera = this.camera;
  80583. var speed = camera._computeLocalCameraSpeed() * 50;
  80584. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  80585. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  80586. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  80587. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  80588. if (!this._leftjoystick.pressed) {
  80589. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  80590. }
  80591. if (!this._rightjoystick.pressed) {
  80592. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  80593. }
  80594. }
  80595. };
  80596. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  80597. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  80598. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  80599. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  80600. this._leftjoystick.setJoystickSensibility(0.15);
  80601. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  80602. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  80603. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  80604. this._rightjoystick.reverseUpDown = true;
  80605. this._rightjoystick.setJoystickSensibility(0.05);
  80606. this._rightjoystick.setJoystickColor("yellow");
  80607. };
  80608. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  80609. this._leftjoystick.releaseCanvas();
  80610. this._rightjoystick.releaseCanvas();
  80611. };
  80612. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  80613. return "FreeCameraVirtualJoystickInput";
  80614. };
  80615. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  80616. return "virtualJoystick";
  80617. };
  80618. return FreeCameraVirtualJoystickInput;
  80619. }());
  80620. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  80621. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  80622. })(BABYLON || (BABYLON = {}));
  80623. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  80624. var BABYLON;
  80625. (function (BABYLON) {
  80626. var SimplificationSettings = /** @class */ (function () {
  80627. function SimplificationSettings(quality, distance, optimizeMesh) {
  80628. this.quality = quality;
  80629. this.distance = distance;
  80630. this.optimizeMesh = optimizeMesh;
  80631. }
  80632. return SimplificationSettings;
  80633. }());
  80634. BABYLON.SimplificationSettings = SimplificationSettings;
  80635. var SimplificationQueue = /** @class */ (function () {
  80636. function SimplificationQueue() {
  80637. this.running = false;
  80638. this._simplificationArray = [];
  80639. }
  80640. SimplificationQueue.prototype.addTask = function (task) {
  80641. this._simplificationArray.push(task);
  80642. };
  80643. SimplificationQueue.prototype.executeNext = function () {
  80644. var task = this._simplificationArray.pop();
  80645. if (task) {
  80646. this.running = true;
  80647. this.runSimplification(task);
  80648. }
  80649. else {
  80650. this.running = false;
  80651. }
  80652. };
  80653. SimplificationQueue.prototype.runSimplification = function (task) {
  80654. var _this = this;
  80655. if (task.parallelProcessing) {
  80656. //parallel simplifier
  80657. task.settings.forEach(function (setting) {
  80658. var simplifier = _this.getSimplifier(task);
  80659. simplifier.simplify(setting, function (newMesh) {
  80660. task.mesh.addLODLevel(setting.distance, newMesh);
  80661. newMesh.isVisible = true;
  80662. //check if it is the last
  80663. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  80664. //all done, run the success callback.
  80665. task.successCallback();
  80666. }
  80667. _this.executeNext();
  80668. });
  80669. });
  80670. }
  80671. else {
  80672. //single simplifier.
  80673. var simplifier = this.getSimplifier(task);
  80674. var runDecimation = function (setting, callback) {
  80675. simplifier.simplify(setting, function (newMesh) {
  80676. task.mesh.addLODLevel(setting.distance, newMesh);
  80677. newMesh.isVisible = true;
  80678. //run the next quality level
  80679. callback();
  80680. });
  80681. };
  80682. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  80683. runDecimation(task.settings[loop.index], function () {
  80684. loop.executeNext();
  80685. });
  80686. }, function () {
  80687. //execution ended, run the success callback.
  80688. if (task.successCallback) {
  80689. task.successCallback();
  80690. }
  80691. _this.executeNext();
  80692. });
  80693. }
  80694. };
  80695. SimplificationQueue.prototype.getSimplifier = function (task) {
  80696. switch (task.simplificationType) {
  80697. case SimplificationType.QUADRATIC:
  80698. default:
  80699. return new QuadraticErrorSimplification(task.mesh);
  80700. }
  80701. };
  80702. return SimplificationQueue;
  80703. }());
  80704. BABYLON.SimplificationQueue = SimplificationQueue;
  80705. /**
  80706. * The implemented types of simplification.
  80707. * At the moment only Quadratic Error Decimation is implemented.
  80708. */
  80709. var SimplificationType;
  80710. (function (SimplificationType) {
  80711. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  80712. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  80713. var DecimationTriangle = /** @class */ (function () {
  80714. function DecimationTriangle(vertices) {
  80715. this.vertices = vertices;
  80716. this.error = new Array(4);
  80717. this.deleted = false;
  80718. this.isDirty = false;
  80719. this.deletePending = false;
  80720. this.borderFactor = 0;
  80721. }
  80722. return DecimationTriangle;
  80723. }());
  80724. BABYLON.DecimationTriangle = DecimationTriangle;
  80725. var DecimationVertex = /** @class */ (function () {
  80726. function DecimationVertex(position, id) {
  80727. this.position = position;
  80728. this.id = id;
  80729. this.isBorder = true;
  80730. this.q = new QuadraticMatrix();
  80731. this.triangleCount = 0;
  80732. this.triangleStart = 0;
  80733. this.originalOffsets = [];
  80734. }
  80735. DecimationVertex.prototype.updatePosition = function (newPosition) {
  80736. this.position.copyFrom(newPosition);
  80737. };
  80738. return DecimationVertex;
  80739. }());
  80740. BABYLON.DecimationVertex = DecimationVertex;
  80741. var QuadraticMatrix = /** @class */ (function () {
  80742. function QuadraticMatrix(data) {
  80743. this.data = new Array(10);
  80744. for (var i = 0; i < 10; ++i) {
  80745. if (data && data[i]) {
  80746. this.data[i] = data[i];
  80747. }
  80748. else {
  80749. this.data[i] = 0;
  80750. }
  80751. }
  80752. }
  80753. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  80754. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  80755. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  80756. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  80757. return det;
  80758. };
  80759. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  80760. for (var i = 0; i < 10; ++i) {
  80761. this.data[i] += matrix.data[i];
  80762. }
  80763. };
  80764. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  80765. for (var i = 0; i < 10; ++i) {
  80766. this.data[i] += data[i];
  80767. }
  80768. };
  80769. QuadraticMatrix.prototype.add = function (matrix) {
  80770. var m = new QuadraticMatrix();
  80771. for (var i = 0; i < 10; ++i) {
  80772. m.data[i] = this.data[i] + matrix.data[i];
  80773. }
  80774. return m;
  80775. };
  80776. QuadraticMatrix.FromData = function (a, b, c, d) {
  80777. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  80778. };
  80779. //returning an array to avoid garbage collection
  80780. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  80781. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  80782. };
  80783. return QuadraticMatrix;
  80784. }());
  80785. BABYLON.QuadraticMatrix = QuadraticMatrix;
  80786. var Reference = /** @class */ (function () {
  80787. function Reference(vertexId, triangleId) {
  80788. this.vertexId = vertexId;
  80789. this.triangleId = triangleId;
  80790. }
  80791. return Reference;
  80792. }());
  80793. BABYLON.Reference = Reference;
  80794. /**
  80795. * An implementation of the Quadratic Error simplification algorithm.
  80796. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  80797. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  80798. * @author RaananW
  80799. */
  80800. var QuadraticErrorSimplification = /** @class */ (function () {
  80801. function QuadraticErrorSimplification(_mesh) {
  80802. this._mesh = _mesh;
  80803. this.syncIterations = 5000;
  80804. this.aggressiveness = 7;
  80805. this.decimationIterations = 100;
  80806. this.boundingBoxEpsilon = BABYLON.Epsilon;
  80807. }
  80808. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  80809. var _this = this;
  80810. this.initDecimatedMesh();
  80811. //iterating through the submeshes array, one after the other.
  80812. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  80813. _this.initWithMesh(loop.index, function () {
  80814. _this.runDecimation(settings, loop.index, function () {
  80815. loop.executeNext();
  80816. });
  80817. }, settings.optimizeMesh);
  80818. }, function () {
  80819. setTimeout(function () {
  80820. successCallback(_this._reconstructedMesh);
  80821. }, 0);
  80822. });
  80823. };
  80824. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  80825. var _this = this;
  80826. var targetCount = ~~(this.triangles.length * settings.quality);
  80827. var deletedTriangles = 0;
  80828. var triangleCount = this.triangles.length;
  80829. var iterationFunction = function (iteration, callback) {
  80830. setTimeout(function () {
  80831. if (iteration % 5 === 0) {
  80832. _this.updateMesh(iteration === 0);
  80833. }
  80834. for (var i = 0; i < _this.triangles.length; ++i) {
  80835. _this.triangles[i].isDirty = false;
  80836. }
  80837. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  80838. var trianglesIterator = function (i) {
  80839. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  80840. var t = _this.triangles[tIdx];
  80841. if (!t)
  80842. return;
  80843. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  80844. return;
  80845. }
  80846. for (var j = 0; j < 3; ++j) {
  80847. if (t.error[j] < threshold) {
  80848. var deleted0 = [];
  80849. var deleted1 = [];
  80850. var v0 = t.vertices[j];
  80851. var v1 = t.vertices[(j + 1) % 3];
  80852. if (v0.isBorder || v1.isBorder)
  80853. continue;
  80854. var p = BABYLON.Vector3.Zero();
  80855. var n = BABYLON.Vector3.Zero();
  80856. var uv = BABYLON.Vector2.Zero();
  80857. var color = new BABYLON.Color4(0, 0, 0, 1);
  80858. _this.calculateError(v0, v1, p, n, uv, color);
  80859. var delTr = new Array();
  80860. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  80861. continue;
  80862. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  80863. continue;
  80864. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  80865. continue;
  80866. var uniqueArray = new Array();
  80867. delTr.forEach(function (deletedT) {
  80868. if (uniqueArray.indexOf(deletedT) === -1) {
  80869. deletedT.deletePending = true;
  80870. uniqueArray.push(deletedT);
  80871. }
  80872. });
  80873. if (uniqueArray.length % 2 !== 0) {
  80874. continue;
  80875. }
  80876. v0.q = v1.q.add(v0.q);
  80877. v0.updatePosition(p);
  80878. var tStart = _this.references.length;
  80879. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  80880. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  80881. var tCount = _this.references.length - tStart;
  80882. if (tCount <= v0.triangleCount) {
  80883. if (tCount) {
  80884. for (var c = 0; c < tCount; c++) {
  80885. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  80886. }
  80887. }
  80888. }
  80889. else {
  80890. v0.triangleStart = tStart;
  80891. }
  80892. v0.triangleCount = tCount;
  80893. break;
  80894. }
  80895. }
  80896. };
  80897. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  80898. }, 0);
  80899. };
  80900. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  80901. if (triangleCount - deletedTriangles <= targetCount)
  80902. loop.breakLoop();
  80903. else {
  80904. iterationFunction(loop.index, function () {
  80905. loop.executeNext();
  80906. });
  80907. }
  80908. }, function () {
  80909. setTimeout(function () {
  80910. //reconstruct this part of the mesh
  80911. _this.reconstructMesh(submeshIndex);
  80912. successCallback();
  80913. }, 0);
  80914. });
  80915. };
  80916. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  80917. var _this = this;
  80918. this.vertices = [];
  80919. this.triangles = [];
  80920. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  80921. var indices = this._mesh.getIndices();
  80922. var submesh = this._mesh.subMeshes[submeshIndex];
  80923. var findInVertices = function (positionToSearch) {
  80924. if (optimizeMesh) {
  80925. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  80926. if (_this.vertices[ii].position.equals(positionToSearch)) {
  80927. return _this.vertices[ii];
  80928. }
  80929. }
  80930. }
  80931. return null;
  80932. };
  80933. var vertexReferences = [];
  80934. var vertexInit = function (i) {
  80935. if (!positionData) {
  80936. return;
  80937. }
  80938. var offset = i + submesh.verticesStart;
  80939. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  80940. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  80941. vertex.originalOffsets.push(offset);
  80942. if (vertex.id === _this.vertices.length) {
  80943. _this.vertices.push(vertex);
  80944. }
  80945. vertexReferences.push(vertex.id);
  80946. };
  80947. //var totalVertices = mesh.getTotalVertices();
  80948. var totalVertices = submesh.verticesCount;
  80949. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  80950. var indicesInit = function (i) {
  80951. if (!indices) {
  80952. return;
  80953. }
  80954. var offset = (submesh.indexStart / 3) + i;
  80955. var pos = (offset * 3);
  80956. var i0 = indices[pos + 0];
  80957. var i1 = indices[pos + 1];
  80958. var i2 = indices[pos + 2];
  80959. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  80960. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  80961. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  80962. var triangle = new DecimationTriangle([v0, v1, v2]);
  80963. triangle.originalOffset = pos;
  80964. _this.triangles.push(triangle);
  80965. };
  80966. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  80967. _this.init(callback);
  80968. });
  80969. });
  80970. };
  80971. QuadraticErrorSimplification.prototype.init = function (callback) {
  80972. var _this = this;
  80973. var triangleInit1 = function (i) {
  80974. var t = _this.triangles[i];
  80975. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  80976. for (var j = 0; j < 3; j++) {
  80977. 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))));
  80978. }
  80979. };
  80980. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  80981. var triangleInit2 = function (i) {
  80982. var t = _this.triangles[i];
  80983. for (var j = 0; j < 3; ++j) {
  80984. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  80985. }
  80986. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  80987. };
  80988. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  80989. callback();
  80990. });
  80991. });
  80992. };
  80993. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  80994. var newTriangles = [];
  80995. var i;
  80996. for (i = 0; i < this.vertices.length; ++i) {
  80997. this.vertices[i].triangleCount = 0;
  80998. }
  80999. var t;
  81000. var j;
  81001. for (i = 0; i < this.triangles.length; ++i) {
  81002. if (!this.triangles[i].deleted) {
  81003. t = this.triangles[i];
  81004. for (j = 0; j < 3; ++j) {
  81005. t.vertices[j].triangleCount = 1;
  81006. }
  81007. newTriangles.push(t);
  81008. }
  81009. }
  81010. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  81011. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  81012. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  81013. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  81014. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  81015. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81016. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  81017. var vertexCount = 0;
  81018. for (i = 0; i < this.vertices.length; ++i) {
  81019. var vertex = this.vertices[i];
  81020. vertex.id = vertexCount;
  81021. if (vertex.triangleCount) {
  81022. vertex.originalOffsets.forEach(function (originalOffset) {
  81023. if (!normalData) {
  81024. return;
  81025. }
  81026. newPositionData.push(vertex.position.x);
  81027. newPositionData.push(vertex.position.y);
  81028. newPositionData.push(vertex.position.z);
  81029. newNormalData.push(normalData[originalOffset * 3]);
  81030. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  81031. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  81032. if (uvs && uvs.length) {
  81033. newUVsData.push(uvs[(originalOffset * 2)]);
  81034. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  81035. }
  81036. else if (colorsData && colorsData.length) {
  81037. newColorsData.push(colorsData[(originalOffset * 4)]);
  81038. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  81039. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  81040. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  81041. }
  81042. ++vertexCount;
  81043. });
  81044. }
  81045. }
  81046. var startingIndex = this._reconstructedMesh.getTotalIndices();
  81047. var startingVertex = this._reconstructedMesh.getTotalVertices();
  81048. var submeshesArray = this._reconstructedMesh.subMeshes;
  81049. this._reconstructedMesh.subMeshes = [];
  81050. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  81051. var originalIndices = this._mesh.getIndices();
  81052. for (i = 0; i < newTriangles.length; ++i) {
  81053. t = newTriangles[i]; //now get the new referencing point for each vertex
  81054. [0, 1, 2].forEach(function (idx) {
  81055. var id = originalIndices[t.originalOffset + idx];
  81056. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  81057. if (offset < 0)
  81058. offset = 0;
  81059. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  81060. });
  81061. }
  81062. //overwriting the old vertex buffers and indices.
  81063. this._reconstructedMesh.setIndices(newIndicesArray);
  81064. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  81065. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  81066. if (newUVsData.length > 0)
  81067. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  81068. if (newColorsData.length > 0)
  81069. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  81070. //create submesh
  81071. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  81072. if (submeshIndex > 0) {
  81073. this._reconstructedMesh.subMeshes = [];
  81074. submeshesArray.forEach(function (submesh) {
  81075. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  81076. });
  81077. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  81078. }
  81079. };
  81080. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  81081. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  81082. this._reconstructedMesh.material = this._mesh.material;
  81083. this._reconstructedMesh.parent = this._mesh.parent;
  81084. this._reconstructedMesh.isVisible = false;
  81085. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  81086. };
  81087. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  81088. for (var i = 0; i < vertex1.triangleCount; ++i) {
  81089. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  81090. if (t.deleted)
  81091. continue;
  81092. var s = this.references[vertex1.triangleStart + i].vertexId;
  81093. var v1 = t.vertices[(s + 1) % 3];
  81094. var v2 = t.vertices[(s + 2) % 3];
  81095. if ((v1 === vertex2 || v2 === vertex2)) {
  81096. deletedArray[i] = true;
  81097. delTr.push(t);
  81098. continue;
  81099. }
  81100. var d1 = v1.position.subtract(point);
  81101. d1 = d1.normalize();
  81102. var d2 = v2.position.subtract(point);
  81103. d2 = d2.normalize();
  81104. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  81105. return true;
  81106. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  81107. deletedArray[i] = false;
  81108. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  81109. return true;
  81110. }
  81111. return false;
  81112. };
  81113. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  81114. var newDeleted = deletedTriangles;
  81115. for (var i = 0; i < vertex.triangleCount; ++i) {
  81116. var ref = this.references[vertex.triangleStart + i];
  81117. var t = this.triangles[ref.triangleId];
  81118. if (t.deleted)
  81119. continue;
  81120. if (deletedArray[i] && t.deletePending) {
  81121. t.deleted = true;
  81122. newDeleted++;
  81123. continue;
  81124. }
  81125. t.vertices[ref.vertexId] = origVertex;
  81126. t.isDirty = true;
  81127. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  81128. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  81129. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  81130. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  81131. this.references.push(ref);
  81132. }
  81133. return newDeleted;
  81134. };
  81135. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  81136. for (var i = 0; i < this.vertices.length; ++i) {
  81137. var vCount = [];
  81138. var vId = [];
  81139. var v = this.vertices[i];
  81140. var j;
  81141. for (j = 0; j < v.triangleCount; ++j) {
  81142. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  81143. for (var ii = 0; ii < 3; ii++) {
  81144. var ofs = 0;
  81145. var vv = triangle.vertices[ii];
  81146. while (ofs < vCount.length) {
  81147. if (vId[ofs] === vv.id)
  81148. break;
  81149. ++ofs;
  81150. }
  81151. if (ofs === vCount.length) {
  81152. vCount.push(1);
  81153. vId.push(vv.id);
  81154. }
  81155. else {
  81156. vCount[ofs]++;
  81157. }
  81158. }
  81159. }
  81160. for (j = 0; j < vCount.length; ++j) {
  81161. if (vCount[j] === 1) {
  81162. this.vertices[vId[j]].isBorder = true;
  81163. }
  81164. else {
  81165. this.vertices[vId[j]].isBorder = false;
  81166. }
  81167. }
  81168. }
  81169. };
  81170. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  81171. if (identifyBorders === void 0) { identifyBorders = false; }
  81172. var i;
  81173. if (!identifyBorders) {
  81174. var newTrianglesVector = [];
  81175. for (i = 0; i < this.triangles.length; ++i) {
  81176. if (!this.triangles[i].deleted) {
  81177. newTrianglesVector.push(this.triangles[i]);
  81178. }
  81179. }
  81180. this.triangles = newTrianglesVector;
  81181. }
  81182. for (i = 0; i < this.vertices.length; ++i) {
  81183. this.vertices[i].triangleCount = 0;
  81184. this.vertices[i].triangleStart = 0;
  81185. }
  81186. var t;
  81187. var j;
  81188. var v;
  81189. for (i = 0; i < this.triangles.length; ++i) {
  81190. t = this.triangles[i];
  81191. for (j = 0; j < 3; ++j) {
  81192. v = t.vertices[j];
  81193. v.triangleCount++;
  81194. }
  81195. }
  81196. var tStart = 0;
  81197. for (i = 0; i < this.vertices.length; ++i) {
  81198. this.vertices[i].triangleStart = tStart;
  81199. tStart += this.vertices[i].triangleCount;
  81200. this.vertices[i].triangleCount = 0;
  81201. }
  81202. var newReferences = new Array(this.triangles.length * 3);
  81203. for (i = 0; i < this.triangles.length; ++i) {
  81204. t = this.triangles[i];
  81205. for (j = 0; j < 3; ++j) {
  81206. v = t.vertices[j];
  81207. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  81208. v.triangleCount++;
  81209. }
  81210. }
  81211. this.references = newReferences;
  81212. if (identifyBorders) {
  81213. this.identifyBorder();
  81214. }
  81215. };
  81216. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  81217. var x = point.x;
  81218. var y = point.y;
  81219. var z = point.z;
  81220. 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
  81221. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  81222. };
  81223. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  81224. var q = vertex1.q.add(vertex2.q);
  81225. var border = vertex1.isBorder && vertex2.isBorder;
  81226. var error = 0;
  81227. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  81228. if (qDet !== 0 && !border) {
  81229. if (!pointResult) {
  81230. pointResult = BABYLON.Vector3.Zero();
  81231. }
  81232. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  81233. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  81234. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  81235. error = this.vertexError(q, pointResult);
  81236. }
  81237. else {
  81238. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  81239. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  81240. var error1 = this.vertexError(q, vertex1.position);
  81241. var error2 = this.vertexError(q, vertex2.position);
  81242. var error3 = this.vertexError(q, p3);
  81243. error = Math.min(error1, error2, error3);
  81244. if (error === error1) {
  81245. if (pointResult) {
  81246. pointResult.copyFrom(vertex1.position);
  81247. }
  81248. }
  81249. else if (error === error2) {
  81250. if (pointResult) {
  81251. pointResult.copyFrom(vertex2.position);
  81252. }
  81253. }
  81254. else {
  81255. if (pointResult) {
  81256. pointResult.copyFrom(p3);
  81257. }
  81258. }
  81259. }
  81260. return error;
  81261. };
  81262. return QuadraticErrorSimplification;
  81263. }());
  81264. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  81265. })(BABYLON || (BABYLON = {}));
  81266. //# sourceMappingURL=babylon.meshSimplification.js.map
  81267. var BABYLON;
  81268. (function (BABYLON) {
  81269. var MeshLODLevel = /** @class */ (function () {
  81270. function MeshLODLevel(distance, mesh) {
  81271. this.distance = distance;
  81272. this.mesh = mesh;
  81273. }
  81274. return MeshLODLevel;
  81275. }());
  81276. BABYLON.MeshLODLevel = MeshLODLevel;
  81277. })(BABYLON || (BABYLON = {}));
  81278. //# sourceMappingURL=babylon.meshLODLevel.js.map
  81279. var BABYLON;
  81280. (function (BABYLON) {
  81281. /**
  81282. * Defines the root class used to create scene optimization to use with SceneOptimizer
  81283. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81284. */
  81285. var SceneOptimization = /** @class */ (function () {
  81286. /**
  81287. * Creates the SceneOptimization object
  81288. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81289. * @param desc defines the description associated with the optimization
  81290. */
  81291. function SceneOptimization(
  81292. /**
  81293. * Defines the priority of this optimization (0 by default which means first in the list)
  81294. */
  81295. priority) {
  81296. if (priority === void 0) { priority = 0; }
  81297. this.priority = priority;
  81298. }
  81299. /**
  81300. * Gets a string describing the action executed by the current optimization
  81301. * @returns description string
  81302. */
  81303. SceneOptimization.prototype.getDescription = function () {
  81304. return "";
  81305. };
  81306. /**
  81307. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81308. * @param scene defines the current scene where to apply this optimization
  81309. * @param optimizer defines the current optimizer
  81310. * @returns true if everything that can be done was applied
  81311. */
  81312. SceneOptimization.prototype.apply = function (scene, optimizer) {
  81313. return true;
  81314. };
  81315. ;
  81316. return SceneOptimization;
  81317. }());
  81318. BABYLON.SceneOptimization = SceneOptimization;
  81319. /**
  81320. * Defines an optimization used to reduce the size of render target textures
  81321. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81322. */
  81323. var TextureOptimization = /** @class */ (function (_super) {
  81324. __extends(TextureOptimization, _super);
  81325. /**
  81326. * Creates the TextureOptimization object
  81327. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81328. * @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
  81329. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81330. */
  81331. function TextureOptimization(
  81332. /**
  81333. * Defines the priority of this optimization (0 by default which means first in the list)
  81334. */
  81335. priority,
  81336. /**
  81337. * 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
  81338. */
  81339. maximumSize,
  81340. /**
  81341. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81342. */
  81343. step) {
  81344. if (priority === void 0) { priority = 0; }
  81345. if (maximumSize === void 0) { maximumSize = 1024; }
  81346. if (step === void 0) { step = 0.5; }
  81347. var _this = _super.call(this, priority) || this;
  81348. _this.priority = priority;
  81349. _this.maximumSize = maximumSize;
  81350. _this.step = step;
  81351. return _this;
  81352. }
  81353. /**
  81354. * Gets a string describing the action executed by the current optimization
  81355. * @returns description string
  81356. */
  81357. TextureOptimization.prototype.getDescription = function () {
  81358. return "Reducing render target texture size to " + this.maximumSize;
  81359. };
  81360. /**
  81361. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81362. * @param scene defines the current scene where to apply this optimization
  81363. * @param optimizer defines the current optimizer
  81364. * @returns true if everything that can be done was applied
  81365. */
  81366. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81367. var allDone = true;
  81368. for (var index = 0; index < scene.textures.length; index++) {
  81369. var texture = scene.textures[index];
  81370. if (!texture.canRescale || texture.getContext) {
  81371. continue;
  81372. }
  81373. var currentSize = texture.getSize();
  81374. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81375. if (maxDimension > this.maximumSize) {
  81376. texture.scale(this.step);
  81377. allDone = false;
  81378. }
  81379. }
  81380. return allDone;
  81381. };
  81382. return TextureOptimization;
  81383. }(SceneOptimization));
  81384. BABYLON.TextureOptimization = TextureOptimization;
  81385. /**
  81386. * Defines an optimization used to increase or decrease the rendering resolution
  81387. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81388. */
  81389. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81390. __extends(HardwareScalingOptimization, _super);
  81391. /**
  81392. * Creates the HardwareScalingOptimization object
  81393. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81394. * @param maximumScale defines the maximum scale to use (2 by default)
  81395. * @param step defines the step to use between two passes (0.5 by default)
  81396. */
  81397. function HardwareScalingOptimization(
  81398. /**
  81399. * Defines the priority of this optimization (0 by default which means first in the list)
  81400. */
  81401. priority,
  81402. /**
  81403. * Defines the maximum scale to use (2 by default)
  81404. */
  81405. maximumScale,
  81406. /**
  81407. * Defines the step to use between two passes (0.5 by default)
  81408. */
  81409. step) {
  81410. if (priority === void 0) { priority = 0; }
  81411. if (maximumScale === void 0) { maximumScale = 2; }
  81412. if (step === void 0) { step = 0.25; }
  81413. var _this = _super.call(this, priority) || this;
  81414. _this.priority = priority;
  81415. _this.maximumScale = maximumScale;
  81416. _this.step = step;
  81417. _this._currentScale = -1;
  81418. _this._directionOffset = 1;
  81419. return _this;
  81420. }
  81421. /**
  81422. * Gets a string describing the action executed by the current optimization
  81423. * @return description string
  81424. */
  81425. HardwareScalingOptimization.prototype.getDescription = function () {
  81426. return "Setting hardware scaling level to " + this._currentScale;
  81427. };
  81428. /**
  81429. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81430. * @param scene defines the current scene where to apply this optimization
  81431. * @param optimizer defines the current optimizer
  81432. * @returns true if everything that can be done was applied
  81433. */
  81434. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81435. if (this._currentScale === -1) {
  81436. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81437. if (this._currentScale > this.maximumScale) {
  81438. this._directionOffset = -1;
  81439. }
  81440. }
  81441. this._currentScale += this._directionOffset * this.step;
  81442. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81443. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81444. };
  81445. ;
  81446. return HardwareScalingOptimization;
  81447. }(SceneOptimization));
  81448. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81449. /**
  81450. * Defines an optimization used to remove shadows
  81451. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81452. */
  81453. var ShadowsOptimization = /** @class */ (function (_super) {
  81454. __extends(ShadowsOptimization, _super);
  81455. function ShadowsOptimization() {
  81456. return _super !== null && _super.apply(this, arguments) || this;
  81457. }
  81458. /**
  81459. * Gets a string describing the action executed by the current optimization
  81460. * @return description string
  81461. */
  81462. ShadowsOptimization.prototype.getDescription = function () {
  81463. return "Turning shadows on/off";
  81464. };
  81465. /**
  81466. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81467. * @param scene defines the current scene where to apply this optimization
  81468. * @param optimizer defines the current optimizer
  81469. * @returns true if everything that can be done was applied
  81470. */
  81471. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81472. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81473. return true;
  81474. };
  81475. ;
  81476. return ShadowsOptimization;
  81477. }(SceneOptimization));
  81478. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81479. /**
  81480. * Defines an optimization used to turn post-processes off
  81481. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81482. */
  81483. var PostProcessesOptimization = /** @class */ (function (_super) {
  81484. __extends(PostProcessesOptimization, _super);
  81485. function PostProcessesOptimization() {
  81486. return _super !== null && _super.apply(this, arguments) || this;
  81487. }
  81488. /**
  81489. * Gets a string describing the action executed by the current optimization
  81490. * @return description string
  81491. */
  81492. PostProcessesOptimization.prototype.getDescription = function () {
  81493. return "Turning post-processes on/off";
  81494. };
  81495. /**
  81496. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81497. * @param scene defines the current scene where to apply this optimization
  81498. * @param optimizer defines the current optimizer
  81499. * @returns true if everything that can be done was applied
  81500. */
  81501. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81502. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81503. return true;
  81504. };
  81505. ;
  81506. return PostProcessesOptimization;
  81507. }(SceneOptimization));
  81508. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81509. /**
  81510. * Defines an optimization used to turn lens flares off
  81511. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81512. */
  81513. var LensFlaresOptimization = /** @class */ (function (_super) {
  81514. __extends(LensFlaresOptimization, _super);
  81515. function LensFlaresOptimization() {
  81516. return _super !== null && _super.apply(this, arguments) || this;
  81517. }
  81518. /**
  81519. * Gets a string describing the action executed by the current optimization
  81520. * @return description string
  81521. */
  81522. LensFlaresOptimization.prototype.getDescription = function () {
  81523. return "Turning lens flares on/off";
  81524. };
  81525. /**
  81526. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81527. * @param scene defines the current scene where to apply this optimization
  81528. * @param optimizer defines the current optimizer
  81529. * @returns true if everything that can be done was applied
  81530. */
  81531. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  81532. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  81533. return true;
  81534. };
  81535. ;
  81536. return LensFlaresOptimization;
  81537. }(SceneOptimization));
  81538. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  81539. /**
  81540. * Defines an optimization based on user defined callback.
  81541. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81542. */
  81543. var CustomOptimization = /** @class */ (function (_super) {
  81544. __extends(CustomOptimization, _super);
  81545. function CustomOptimization() {
  81546. return _super !== null && _super.apply(this, arguments) || this;
  81547. }
  81548. /**
  81549. * Gets a string describing the action executed by the current optimization
  81550. * @returns description string
  81551. */
  81552. CustomOptimization.prototype.getDescription = function () {
  81553. if (this.onGetDescription) {
  81554. return this.onGetDescription();
  81555. }
  81556. return "Running user defined callback";
  81557. };
  81558. /**
  81559. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81560. * @param scene defines the current scene where to apply this optimization
  81561. * @param optimizer defines the current optimizer
  81562. * @returns true if everything that can be done was applied
  81563. */
  81564. CustomOptimization.prototype.apply = function (scene, optimizer) {
  81565. if (this.onApply) {
  81566. return this.onApply(scene, optimizer);
  81567. }
  81568. return true;
  81569. };
  81570. ;
  81571. return CustomOptimization;
  81572. }(SceneOptimization));
  81573. BABYLON.CustomOptimization = CustomOptimization;
  81574. /**
  81575. * Defines an optimization used to turn particles off
  81576. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81577. */
  81578. var ParticlesOptimization = /** @class */ (function (_super) {
  81579. __extends(ParticlesOptimization, _super);
  81580. function ParticlesOptimization() {
  81581. return _super !== null && _super.apply(this, arguments) || this;
  81582. }
  81583. /**
  81584. * Gets a string describing the action executed by the current optimization
  81585. * @return description string
  81586. */
  81587. ParticlesOptimization.prototype.getDescription = function () {
  81588. return "Turning particles on/off";
  81589. };
  81590. /**
  81591. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81592. * @param scene defines the current scene where to apply this optimization
  81593. * @param optimizer defines the current optimizer
  81594. * @returns true if everything that can be done was applied
  81595. */
  81596. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  81597. scene.particlesEnabled = optimizer.isInImprovementMode;
  81598. return true;
  81599. };
  81600. ;
  81601. return ParticlesOptimization;
  81602. }(SceneOptimization));
  81603. BABYLON.ParticlesOptimization = ParticlesOptimization;
  81604. /**
  81605. * Defines an optimization used to turn render targets off
  81606. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81607. */
  81608. var RenderTargetsOptimization = /** @class */ (function (_super) {
  81609. __extends(RenderTargetsOptimization, _super);
  81610. function RenderTargetsOptimization() {
  81611. return _super !== null && _super.apply(this, arguments) || this;
  81612. }
  81613. /**
  81614. * Gets a string describing the action executed by the current optimization
  81615. * @return description string
  81616. */
  81617. RenderTargetsOptimization.prototype.getDescription = function () {
  81618. return "Turning render targets off";
  81619. };
  81620. /**
  81621. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81622. * @param scene defines the current scene where to apply this optimization
  81623. * @param optimizer defines the current optimizer
  81624. * @returns true if everything that can be done was applied
  81625. */
  81626. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  81627. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  81628. return true;
  81629. };
  81630. ;
  81631. return RenderTargetsOptimization;
  81632. }(SceneOptimization));
  81633. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  81634. /**
  81635. * Defines an optimization used to merge meshes with compatible materials
  81636. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81637. */
  81638. var MergeMeshesOptimization = /** @class */ (function (_super) {
  81639. __extends(MergeMeshesOptimization, _super);
  81640. function MergeMeshesOptimization() {
  81641. var _this = _super !== null && _super.apply(this, arguments) || this;
  81642. _this._canBeMerged = function (abstractMesh) {
  81643. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  81644. return false;
  81645. }
  81646. var mesh = abstractMesh;
  81647. if (!mesh.isVisible || !mesh.isEnabled()) {
  81648. return false;
  81649. }
  81650. if (mesh.instances.length > 0) {
  81651. return false;
  81652. }
  81653. if (mesh.skeleton || mesh.hasLODLevels) {
  81654. return false;
  81655. }
  81656. if (mesh.parent) {
  81657. return false;
  81658. }
  81659. return true;
  81660. };
  81661. return _this;
  81662. }
  81663. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  81664. /**
  81665. * Gets or sets a boolean which defines if optimization octree has to be updated
  81666. */
  81667. get: function () {
  81668. return MergeMeshesOptimization._UpdateSelectionTree;
  81669. },
  81670. /**
  81671. * Gets or sets a boolean which defines if optimization octree has to be updated
  81672. */
  81673. set: function (value) {
  81674. MergeMeshesOptimization._UpdateSelectionTree = value;
  81675. },
  81676. enumerable: true,
  81677. configurable: true
  81678. });
  81679. /**
  81680. * Gets a string describing the action executed by the current optimization
  81681. * @return description string
  81682. */
  81683. MergeMeshesOptimization.prototype.getDescription = function () {
  81684. return "Merging similar meshes together";
  81685. };
  81686. /**
  81687. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81688. * @param scene defines the current scene where to apply this optimization
  81689. * @param optimizer defines the current optimizer
  81690. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  81691. * @returns true if everything that can be done was applied
  81692. */
  81693. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  81694. var globalPool = scene.meshes.slice(0);
  81695. var globalLength = globalPool.length;
  81696. for (var index = 0; index < globalLength; index++) {
  81697. var currentPool = new Array();
  81698. var current = globalPool[index];
  81699. // Checks
  81700. if (!this._canBeMerged(current)) {
  81701. continue;
  81702. }
  81703. currentPool.push(current);
  81704. // Find compatible meshes
  81705. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  81706. var otherMesh = globalPool[subIndex];
  81707. if (!this._canBeMerged(otherMesh)) {
  81708. continue;
  81709. }
  81710. if (otherMesh.material !== current.material) {
  81711. continue;
  81712. }
  81713. if (otherMesh.checkCollisions !== current.checkCollisions) {
  81714. continue;
  81715. }
  81716. currentPool.push(otherMesh);
  81717. globalLength--;
  81718. globalPool.splice(subIndex, 1);
  81719. subIndex--;
  81720. }
  81721. if (currentPool.length < 2) {
  81722. continue;
  81723. }
  81724. // Merge meshes
  81725. BABYLON.Mesh.MergeMeshes(currentPool);
  81726. }
  81727. if (updateSelectionTree != undefined) {
  81728. if (updateSelectionTree) {
  81729. scene.createOrUpdateSelectionOctree();
  81730. }
  81731. }
  81732. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  81733. scene.createOrUpdateSelectionOctree();
  81734. }
  81735. return true;
  81736. };
  81737. ;
  81738. MergeMeshesOptimization._UpdateSelectionTree = false;
  81739. return MergeMeshesOptimization;
  81740. }(SceneOptimization));
  81741. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  81742. /**
  81743. * Defines a list of options used by SceneOptimizer
  81744. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81745. */
  81746. var SceneOptimizerOptions = /** @class */ (function () {
  81747. /**
  81748. * Creates a new list of options used by SceneOptimizer
  81749. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  81750. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  81751. */
  81752. function SceneOptimizerOptions(
  81753. /**
  81754. * Defines the target frame rate to reach (60 by default)
  81755. */
  81756. targetFrameRate,
  81757. /**
  81758. * Defines the interval between two checkes (2000ms by default)
  81759. */
  81760. trackerDuration) {
  81761. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  81762. if (trackerDuration === void 0) { trackerDuration = 2000; }
  81763. this.targetFrameRate = targetFrameRate;
  81764. this.trackerDuration = trackerDuration;
  81765. /**
  81766. * Gets the list of optimizations to apply
  81767. */
  81768. this.optimizations = new Array();
  81769. }
  81770. /**
  81771. * Add a new optimization
  81772. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  81773. * @returns the current SceneOptimizerOptions
  81774. */
  81775. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  81776. this.optimizations.push(optimization);
  81777. return this;
  81778. };
  81779. /**
  81780. * Add a new custom optimization
  81781. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  81782. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  81783. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81784. * @returns the current SceneOptimizerOptions
  81785. */
  81786. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  81787. if (priority === void 0) { priority = 0; }
  81788. var optimization = new CustomOptimization(priority);
  81789. optimization.onApply = onApply;
  81790. optimization.onGetDescription = onGetDescription;
  81791. this.optimizations.push(optimization);
  81792. return this;
  81793. };
  81794. /**
  81795. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  81796. * @param targetFrameRate defines the target frame rate (60 by default)
  81797. * @returns a SceneOptimizerOptions object
  81798. */
  81799. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  81800. var result = new SceneOptimizerOptions(targetFrameRate);
  81801. var priority = 0;
  81802. result.addOptimization(new MergeMeshesOptimization(priority));
  81803. result.addOptimization(new ShadowsOptimization(priority));
  81804. result.addOptimization(new LensFlaresOptimization(priority));
  81805. // Next priority
  81806. priority++;
  81807. result.addOptimization(new PostProcessesOptimization(priority));
  81808. result.addOptimization(new ParticlesOptimization(priority));
  81809. // Next priority
  81810. priority++;
  81811. result.addOptimization(new TextureOptimization(priority, 1024));
  81812. return result;
  81813. };
  81814. /**
  81815. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  81816. * @param targetFrameRate defines the target frame rate (60 by default)
  81817. * @returns a SceneOptimizerOptions object
  81818. */
  81819. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  81820. var result = new SceneOptimizerOptions(targetFrameRate);
  81821. var priority = 0;
  81822. result.addOptimization(new MergeMeshesOptimization(priority));
  81823. result.addOptimization(new ShadowsOptimization(priority));
  81824. result.addOptimization(new LensFlaresOptimization(priority));
  81825. // Next priority
  81826. priority++;
  81827. result.addOptimization(new PostProcessesOptimization(priority));
  81828. result.addOptimization(new ParticlesOptimization(priority));
  81829. // Next priority
  81830. priority++;
  81831. result.addOptimization(new TextureOptimization(priority, 512));
  81832. // Next priority
  81833. priority++;
  81834. result.addOptimization(new RenderTargetsOptimization(priority));
  81835. // Next priority
  81836. priority++;
  81837. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  81838. return result;
  81839. };
  81840. /**
  81841. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  81842. * @param targetFrameRate defines the target frame rate (60 by default)
  81843. * @returns a SceneOptimizerOptions object
  81844. */
  81845. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  81846. var result = new SceneOptimizerOptions(targetFrameRate);
  81847. var priority = 0;
  81848. result.addOptimization(new MergeMeshesOptimization(priority));
  81849. result.addOptimization(new ShadowsOptimization(priority));
  81850. result.addOptimization(new LensFlaresOptimization(priority));
  81851. // Next priority
  81852. priority++;
  81853. result.addOptimization(new PostProcessesOptimization(priority));
  81854. result.addOptimization(new ParticlesOptimization(priority));
  81855. // Next priority
  81856. priority++;
  81857. result.addOptimization(new TextureOptimization(priority, 256));
  81858. // Next priority
  81859. priority++;
  81860. result.addOptimization(new RenderTargetsOptimization(priority));
  81861. // Next priority
  81862. priority++;
  81863. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  81864. return result;
  81865. };
  81866. return SceneOptimizerOptions;
  81867. }());
  81868. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  81869. /**
  81870. * Class used to run optimizations in order to reach a target frame rate
  81871. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81872. */
  81873. var SceneOptimizer = /** @class */ (function () {
  81874. /**
  81875. * Creates a new SceneOptimizer
  81876. * @param scene defines the scene to work on
  81877. * @param options defines the options to use with the SceneOptimizer
  81878. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  81879. * @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)
  81880. */
  81881. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  81882. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  81883. if (improvementMode === void 0) { improvementMode = false; }
  81884. var _this = this;
  81885. this._isRunning = false;
  81886. this._currentPriorityLevel = 0;
  81887. this._targetFrameRate = 60;
  81888. this._trackerDuration = 2000;
  81889. this._currentFrameRate = 0;
  81890. this._improvementMode = false;
  81891. /**
  81892. * Defines an observable called when the optimizer reaches the target frame rate
  81893. */
  81894. this.onSuccessObservable = new BABYLON.Observable();
  81895. /**
  81896. * Defines an observable called when the optimizer enables an optimization
  81897. */
  81898. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  81899. /**
  81900. * Defines an observable called when the optimizer is not able to reach the target frame rate
  81901. */
  81902. this.onFailureObservable = new BABYLON.Observable();
  81903. if (!options) {
  81904. this._options = new SceneOptimizerOptions();
  81905. }
  81906. else {
  81907. this._options = options;
  81908. }
  81909. if (this._options.targetFrameRate) {
  81910. this._targetFrameRate = this._options.targetFrameRate;
  81911. }
  81912. if (this._options.trackerDuration) {
  81913. this._trackerDuration = this._options.trackerDuration;
  81914. }
  81915. if (autoGeneratePriorities) {
  81916. var priority = 0;
  81917. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  81918. var optim = _a[_i];
  81919. optim.priority = priority++;
  81920. }
  81921. }
  81922. this._improvementMode = improvementMode;
  81923. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81924. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  81925. _this._sceneDisposeObserver = null;
  81926. _this.dispose();
  81927. });
  81928. }
  81929. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  81930. /**
  81931. * Gets a boolean indicating if the optimizer is in improvement mode
  81932. */
  81933. get: function () {
  81934. return this._improvementMode;
  81935. },
  81936. enumerable: true,
  81937. configurable: true
  81938. });
  81939. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  81940. /**
  81941. * Gets the current priority level (0 at start)
  81942. */
  81943. get: function () {
  81944. return this._currentPriorityLevel;
  81945. },
  81946. enumerable: true,
  81947. configurable: true
  81948. });
  81949. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  81950. /**
  81951. * Gets the current frame rate checked by the SceneOptimizer
  81952. */
  81953. get: function () {
  81954. return this._currentFrameRate;
  81955. },
  81956. enumerable: true,
  81957. configurable: true
  81958. });
  81959. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  81960. /**
  81961. * Gets or sets the current target frame rate (60 by default)
  81962. */
  81963. get: function () {
  81964. return this._targetFrameRate;
  81965. },
  81966. /**
  81967. * Gets or sets the current target frame rate (60 by default)
  81968. */
  81969. set: function (value) {
  81970. this._targetFrameRate = value;
  81971. },
  81972. enumerable: true,
  81973. configurable: true
  81974. });
  81975. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  81976. /**
  81977. * Gets or sets the current interval between two checks (every 2000ms by default)
  81978. */
  81979. get: function () {
  81980. return this._trackerDuration;
  81981. },
  81982. /**
  81983. * Gets or sets the current interval between two checks (every 2000ms by default)
  81984. */
  81985. set: function (value) {
  81986. this._trackerDuration = value;
  81987. },
  81988. enumerable: true,
  81989. configurable: true
  81990. });
  81991. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  81992. /**
  81993. * Gets the list of active optimizations
  81994. */
  81995. get: function () {
  81996. return this._options.optimizations;
  81997. },
  81998. enumerable: true,
  81999. configurable: true
  82000. });
  82001. /**
  82002. * Stops the current optimizer
  82003. */
  82004. SceneOptimizer.prototype.stop = function () {
  82005. this._isRunning = false;
  82006. };
  82007. /**
  82008. * Reset the optimizer to initial step (current priority level = 0)
  82009. */
  82010. SceneOptimizer.prototype.reset = function () {
  82011. this._currentPriorityLevel = 0;
  82012. };
  82013. /**
  82014. * Start the optimizer. By default it will try to reach a specific framerate
  82015. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  82016. */
  82017. SceneOptimizer.prototype.start = function () {
  82018. var _this = this;
  82019. if (this._isRunning) {
  82020. return;
  82021. }
  82022. this._isRunning = true;
  82023. // Let's wait for the scene to be ready before running our check
  82024. this._scene.executeWhenReady(function () {
  82025. setTimeout(function () {
  82026. _this._checkCurrentState();
  82027. }, _this._trackerDuration);
  82028. });
  82029. };
  82030. SceneOptimizer.prototype._checkCurrentState = function () {
  82031. var _this = this;
  82032. if (!this._isRunning) {
  82033. return;
  82034. }
  82035. var scene = this._scene;
  82036. var options = this._options;
  82037. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  82038. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  82039. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  82040. this._isRunning = false;
  82041. this.onSuccessObservable.notifyObservers(this);
  82042. return;
  82043. }
  82044. // Apply current level of optimizations
  82045. var allDone = true;
  82046. var noOptimizationApplied = true;
  82047. for (var index = 0; index < options.optimizations.length; index++) {
  82048. var optimization = options.optimizations[index];
  82049. if (optimization.priority === this._currentPriorityLevel) {
  82050. noOptimizationApplied = false;
  82051. allDone = allDone && optimization.apply(scene, this);
  82052. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  82053. }
  82054. }
  82055. // If no optimization was applied, this is a failure :(
  82056. if (noOptimizationApplied) {
  82057. this._isRunning = false;
  82058. this.onFailureObservable.notifyObservers(this);
  82059. return;
  82060. }
  82061. // If all optimizations were done, move to next level
  82062. if (allDone) {
  82063. this._currentPriorityLevel++;
  82064. }
  82065. // Let's the system running for a specific amount of time before checking FPS
  82066. scene.executeWhenReady(function () {
  82067. setTimeout(function () {
  82068. _this._checkCurrentState();
  82069. }, _this._trackerDuration);
  82070. });
  82071. };
  82072. /**
  82073. * Release all resources
  82074. */
  82075. SceneOptimizer.prototype.dispose = function () {
  82076. this.stop();
  82077. this.onSuccessObservable.clear();
  82078. this.onFailureObservable.clear();
  82079. this.onNewOptimizationAppliedObservable.clear();
  82080. if (this._sceneDisposeObserver) {
  82081. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  82082. }
  82083. };
  82084. /**
  82085. * Helper function to create a SceneOptimizer with one single line of code
  82086. * @param scene defines the scene to work on
  82087. * @param options defines the options to use with the SceneOptimizer
  82088. * @param onSuccess defines a callback to call on success
  82089. * @param onFailure defines a callback to call on failure
  82090. * @returns the new SceneOptimizer object
  82091. */
  82092. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  82093. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  82094. if (onSuccess) {
  82095. optimizer.onSuccessObservable.add(function () {
  82096. onSuccess();
  82097. });
  82098. }
  82099. if (onFailure) {
  82100. optimizer.onFailureObservable.add(function () {
  82101. onFailure();
  82102. });
  82103. }
  82104. optimizer.start();
  82105. return optimizer;
  82106. };
  82107. return SceneOptimizer;
  82108. }());
  82109. BABYLON.SceneOptimizer = SceneOptimizer;
  82110. })(BABYLON || (BABYLON = {}));
  82111. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  82112. var BABYLON;
  82113. (function (BABYLON) {
  82114. var OutlineRenderer = /** @class */ (function () {
  82115. function OutlineRenderer(scene) {
  82116. this.zOffset = 1;
  82117. this._scene = scene;
  82118. }
  82119. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  82120. var _this = this;
  82121. if (useOverlay === void 0) { useOverlay = false; }
  82122. var scene = this._scene;
  82123. var engine = this._scene.getEngine();
  82124. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82125. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  82126. return;
  82127. }
  82128. var mesh = subMesh.getRenderingMesh();
  82129. var material = subMesh.getMaterial();
  82130. if (!material || !scene.activeCamera) {
  82131. return;
  82132. }
  82133. engine.enableEffect(this._effect);
  82134. // Logarithmic depth
  82135. if (material.useLogarithmicDepth) {
  82136. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  82137. }
  82138. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  82139. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  82140. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82141. // Bones
  82142. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82143. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82144. }
  82145. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  82146. // Alpha test
  82147. if (material && material.needAlphaTesting()) {
  82148. var alphaTexture = material.getAlphaTestTexture();
  82149. if (alphaTexture) {
  82150. this._effect.setTexture("diffuseSampler", alphaTexture);
  82151. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82152. }
  82153. }
  82154. engine.setZOffset(-this.zOffset);
  82155. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  82156. engine.setZOffset(0);
  82157. };
  82158. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  82159. var defines = [];
  82160. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82161. var mesh = subMesh.getMesh();
  82162. var material = subMesh.getMaterial();
  82163. if (material) {
  82164. // Alpha test
  82165. if (material.needAlphaTesting()) {
  82166. defines.push("#define ALPHATEST");
  82167. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82168. attribs.push(BABYLON.VertexBuffer.UVKind);
  82169. defines.push("#define UV1");
  82170. }
  82171. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82172. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82173. defines.push("#define UV2");
  82174. }
  82175. }
  82176. //Logarithmic depth
  82177. if (material.useLogarithmicDepth) {
  82178. defines.push("#define LOGARITHMICDEPTH");
  82179. }
  82180. }
  82181. // Bones
  82182. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82183. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82184. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82185. if (mesh.numBoneInfluencers > 4) {
  82186. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82187. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82188. }
  82189. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82190. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82191. }
  82192. else {
  82193. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82194. }
  82195. // Instances
  82196. if (useInstances) {
  82197. defines.push("#define INSTANCES");
  82198. attribs.push("world0");
  82199. attribs.push("world1");
  82200. attribs.push("world2");
  82201. attribs.push("world3");
  82202. }
  82203. // Get correct effect
  82204. var join = defines.join("\n");
  82205. if (this._cachedDefines !== join) {
  82206. this._cachedDefines = join;
  82207. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  82208. }
  82209. return this._effect.isReady();
  82210. };
  82211. return OutlineRenderer;
  82212. }());
  82213. BABYLON.OutlineRenderer = OutlineRenderer;
  82214. })(BABYLON || (BABYLON = {}));
  82215. //# sourceMappingURL=babylon.outlineRenderer.js.map
  82216. var BABYLON;
  82217. (function (BABYLON) {
  82218. var FaceAdjacencies = /** @class */ (function () {
  82219. function FaceAdjacencies() {
  82220. this.edges = new Array();
  82221. this.edgesConnectedCount = 0;
  82222. }
  82223. return FaceAdjacencies;
  82224. }());
  82225. var EdgesRenderer = /** @class */ (function () {
  82226. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  82227. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  82228. if (epsilon === void 0) { epsilon = 0.95; }
  82229. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  82230. this.edgesWidthScalerForOrthographic = 1000.0;
  82231. this.edgesWidthScalerForPerspective = 50.0;
  82232. this._linesPositions = new Array();
  82233. this._linesNormals = new Array();
  82234. this._linesIndices = new Array();
  82235. this._buffers = {};
  82236. this._checkVerticesInsteadOfIndices = false;
  82237. this._source = source;
  82238. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  82239. this._epsilon = epsilon;
  82240. this._prepareRessources();
  82241. this._generateEdgesLines();
  82242. }
  82243. EdgesRenderer.prototype._prepareRessources = function () {
  82244. if (this._lineShader) {
  82245. return;
  82246. }
  82247. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  82248. attributes: ["position", "normal"],
  82249. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  82250. });
  82251. this._lineShader.disableDepthWrite = true;
  82252. this._lineShader.backFaceCulling = false;
  82253. };
  82254. EdgesRenderer.prototype._rebuild = function () {
  82255. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82256. if (buffer) {
  82257. buffer._rebuild();
  82258. }
  82259. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82260. if (buffer) {
  82261. buffer._rebuild();
  82262. }
  82263. var scene = this._source.getScene();
  82264. var engine = scene.getEngine();
  82265. this._ib = engine.createIndexBuffer(this._linesIndices);
  82266. };
  82267. EdgesRenderer.prototype.dispose = function () {
  82268. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82269. if (buffer) {
  82270. buffer.dispose();
  82271. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  82272. }
  82273. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82274. if (buffer) {
  82275. buffer.dispose();
  82276. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  82277. }
  82278. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  82279. this._lineShader.dispose();
  82280. };
  82281. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  82282. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  82283. return 0;
  82284. }
  82285. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  82286. return 1;
  82287. }
  82288. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  82289. return 2;
  82290. }
  82291. return -1;
  82292. };
  82293. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  82294. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  82295. return 0;
  82296. }
  82297. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  82298. return 1;
  82299. }
  82300. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  82301. return 2;
  82302. }
  82303. return -1;
  82304. };
  82305. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  82306. var needToCreateLine;
  82307. if (edge === undefined) {
  82308. needToCreateLine = true;
  82309. }
  82310. else {
  82311. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  82312. needToCreateLine = dotProduct < this._epsilon;
  82313. }
  82314. if (needToCreateLine) {
  82315. var offset = this._linesPositions.length / 3;
  82316. var normal = p0.subtract(p1);
  82317. normal.normalize();
  82318. // Positions
  82319. this._linesPositions.push(p0.x);
  82320. this._linesPositions.push(p0.y);
  82321. this._linesPositions.push(p0.z);
  82322. this._linesPositions.push(p0.x);
  82323. this._linesPositions.push(p0.y);
  82324. this._linesPositions.push(p0.z);
  82325. this._linesPositions.push(p1.x);
  82326. this._linesPositions.push(p1.y);
  82327. this._linesPositions.push(p1.z);
  82328. this._linesPositions.push(p1.x);
  82329. this._linesPositions.push(p1.y);
  82330. this._linesPositions.push(p1.z);
  82331. // Normals
  82332. this._linesNormals.push(p1.x);
  82333. this._linesNormals.push(p1.y);
  82334. this._linesNormals.push(p1.z);
  82335. this._linesNormals.push(-1);
  82336. this._linesNormals.push(p1.x);
  82337. this._linesNormals.push(p1.y);
  82338. this._linesNormals.push(p1.z);
  82339. this._linesNormals.push(1);
  82340. this._linesNormals.push(p0.x);
  82341. this._linesNormals.push(p0.y);
  82342. this._linesNormals.push(p0.z);
  82343. this._linesNormals.push(-1);
  82344. this._linesNormals.push(p0.x);
  82345. this._linesNormals.push(p0.y);
  82346. this._linesNormals.push(p0.z);
  82347. this._linesNormals.push(1);
  82348. // Indices
  82349. this._linesIndices.push(offset);
  82350. this._linesIndices.push(offset + 1);
  82351. this._linesIndices.push(offset + 2);
  82352. this._linesIndices.push(offset);
  82353. this._linesIndices.push(offset + 2);
  82354. this._linesIndices.push(offset + 3);
  82355. }
  82356. };
  82357. EdgesRenderer.prototype._generateEdgesLines = function () {
  82358. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82359. var indices = this._source.getIndices();
  82360. if (!indices || !positions) {
  82361. return;
  82362. }
  82363. // First let's find adjacencies
  82364. var adjacencies = new Array();
  82365. var faceNormals = new Array();
  82366. var index;
  82367. var faceAdjacencies;
  82368. // Prepare faces
  82369. for (index = 0; index < indices.length; index += 3) {
  82370. faceAdjacencies = new FaceAdjacencies();
  82371. var p0Index = indices[index];
  82372. var p1Index = indices[index + 1];
  82373. var p2Index = indices[index + 2];
  82374. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82375. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82376. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82377. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82378. faceNormal.normalize();
  82379. faceNormals.push(faceNormal);
  82380. adjacencies.push(faceAdjacencies);
  82381. }
  82382. // Scan
  82383. for (index = 0; index < adjacencies.length; index++) {
  82384. faceAdjacencies = adjacencies[index];
  82385. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82386. var otherFaceAdjacencies = adjacencies[otherIndex];
  82387. if (faceAdjacencies.edgesConnectedCount === 3) {
  82388. break;
  82389. }
  82390. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82391. continue;
  82392. }
  82393. var otherP0 = indices[otherIndex * 3];
  82394. var otherP1 = indices[otherIndex * 3 + 1];
  82395. var otherP2 = indices[otherIndex * 3 + 2];
  82396. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82397. var otherEdgeIndex = 0;
  82398. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82399. continue;
  82400. }
  82401. switch (edgeIndex) {
  82402. case 0:
  82403. if (this._checkVerticesInsteadOfIndices) {
  82404. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82405. }
  82406. else {
  82407. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82408. }
  82409. break;
  82410. case 1:
  82411. if (this._checkVerticesInsteadOfIndices) {
  82412. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82413. }
  82414. else {
  82415. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82416. }
  82417. break;
  82418. case 2:
  82419. if (this._checkVerticesInsteadOfIndices) {
  82420. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82421. }
  82422. else {
  82423. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82424. }
  82425. break;
  82426. }
  82427. if (otherEdgeIndex === -1) {
  82428. continue;
  82429. }
  82430. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82431. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82432. faceAdjacencies.edgesConnectedCount++;
  82433. otherFaceAdjacencies.edgesConnectedCount++;
  82434. if (faceAdjacencies.edgesConnectedCount === 3) {
  82435. break;
  82436. }
  82437. }
  82438. }
  82439. }
  82440. // Create lines
  82441. for (index = 0; index < adjacencies.length; index++) {
  82442. // 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
  82443. var current = adjacencies[index];
  82444. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82445. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82446. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82447. }
  82448. // Merge into a single mesh
  82449. var engine = this._source.getScene().getEngine();
  82450. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82451. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82452. this._ib = engine.createIndexBuffer(this._linesIndices);
  82453. this._indicesCount = this._linesIndices.length;
  82454. };
  82455. EdgesRenderer.prototype.render = function () {
  82456. var scene = this._source.getScene();
  82457. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82458. return;
  82459. }
  82460. var engine = scene.getEngine();
  82461. this._lineShader._preBind();
  82462. // VBOs
  82463. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82464. scene.resetCachedMaterial();
  82465. this._lineShader.setColor4("color", this._source.edgesColor);
  82466. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82467. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82468. }
  82469. else {
  82470. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82471. }
  82472. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82473. this._lineShader.bind(this._source.getWorldMatrix());
  82474. // Draw order
  82475. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82476. this._lineShader.unbind();
  82477. engine.setDepthWrite(true);
  82478. };
  82479. return EdgesRenderer;
  82480. }());
  82481. BABYLON.EdgesRenderer = EdgesRenderer;
  82482. })(BABYLON || (BABYLON = {}));
  82483. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82484. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82485. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82486. s = arguments[i];
  82487. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82488. t[p] = s[p];
  82489. }
  82490. return t;
  82491. };
  82492. var BABYLON;
  82493. (function (BABYLON) {
  82494. /**
  82495. * The effect layer Helps adding post process effect blended with the main pass.
  82496. *
  82497. * This can be for instance use to generate glow or higlight effects on the scene.
  82498. *
  82499. * The effect layer class can not be used directly and is intented to inherited from to be
  82500. * customized per effects.
  82501. */
  82502. var EffectLayer = /** @class */ (function () {
  82503. /**
  82504. * Instantiates a new effect Layer and references it in the scene.
  82505. * @param name The name of the layer
  82506. * @param scene The scene to use the layer in
  82507. */
  82508. function EffectLayer(
  82509. /** The Friendly of the effect in the scene */
  82510. name, scene) {
  82511. this.name = name;
  82512. this._vertexBuffers = {};
  82513. this._maxSize = 0;
  82514. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82515. this._shouldRender = true;
  82516. this._postProcesses = [];
  82517. this._textures = [];
  82518. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82519. /**
  82520. * The clear color of the texture used to generate the glow map.
  82521. */
  82522. this.neutralColor = new BABYLON.Color4();
  82523. /**
  82524. * Specifies wether the highlight layer is enabled or not.
  82525. */
  82526. this.isEnabled = true;
  82527. /**
  82528. * An event triggered when the effect layer has been disposed.
  82529. */
  82530. this.onDisposeObservable = new BABYLON.Observable();
  82531. /**
  82532. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  82533. */
  82534. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  82535. /**
  82536. * An event triggered when the generated texture is being merged in the scene.
  82537. */
  82538. this.onBeforeComposeObservable = new BABYLON.Observable();
  82539. /**
  82540. * An event triggered when the generated texture has been merged in the scene.
  82541. */
  82542. this.onAfterComposeObservable = new BABYLON.Observable();
  82543. /**
  82544. * An event triggered when the efffect layer changes its size.
  82545. */
  82546. this.onSizeChangedObservable = new BABYLON.Observable();
  82547. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82548. this._engine = scene.getEngine();
  82549. this._maxSize = this._engine.getCaps().maxTextureSize;
  82550. this._scene.effectLayers.push(this);
  82551. // Generate Buffers
  82552. this._generateIndexBuffer();
  82553. this._genrateVertexBuffer();
  82554. }
  82555. Object.defineProperty(EffectLayer.prototype, "camera", {
  82556. /**
  82557. * Gets the camera attached to the layer.
  82558. */
  82559. get: function () {
  82560. return this._effectLayerOptions.camera;
  82561. },
  82562. enumerable: true,
  82563. configurable: true
  82564. });
  82565. /**
  82566. * Initializes the effect layer with the required options.
  82567. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  82568. */
  82569. EffectLayer.prototype._init = function (options) {
  82570. // Adapt options
  82571. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  82572. this._setMainTextureSize();
  82573. this._createMainTexture();
  82574. this._createTextureAndPostProcesses();
  82575. this._mergeEffect = this._createMergeEffect();
  82576. };
  82577. /**
  82578. * Generates the index buffer of the full screen quad blending to the main canvas.
  82579. */
  82580. EffectLayer.prototype._generateIndexBuffer = function () {
  82581. // Indices
  82582. var indices = [];
  82583. indices.push(0);
  82584. indices.push(1);
  82585. indices.push(2);
  82586. indices.push(0);
  82587. indices.push(2);
  82588. indices.push(3);
  82589. this._indexBuffer = this._engine.createIndexBuffer(indices);
  82590. };
  82591. /**
  82592. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  82593. */
  82594. EffectLayer.prototype._genrateVertexBuffer = function () {
  82595. // VBO
  82596. var vertices = [];
  82597. vertices.push(1, 1);
  82598. vertices.push(-1, 1);
  82599. vertices.push(-1, -1);
  82600. vertices.push(1, -1);
  82601. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  82602. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  82603. };
  82604. /**
  82605. * Sets the main texture desired size which is the closest power of two
  82606. * of the engine canvas size.
  82607. */
  82608. EffectLayer.prototype._setMainTextureSize = function () {
  82609. if (this._effectLayerOptions.mainTextureFixedSize) {
  82610. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  82611. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  82612. }
  82613. else {
  82614. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  82615. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  82616. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  82617. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  82618. }
  82619. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  82620. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  82621. };
  82622. /**
  82623. * Creates the main texture for the effect layer.
  82624. */
  82625. EffectLayer.prototype._createMainTexture = function () {
  82626. var _this = this;
  82627. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  82628. width: this._mainTextureDesiredSize.width,
  82629. height: this._mainTextureDesiredSize.height
  82630. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  82631. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  82632. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82633. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  82634. this._mainTexture.anisotropicFilteringLevel = 1;
  82635. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  82636. this._mainTexture.renderParticles = false;
  82637. this._mainTexture.renderList = null;
  82638. this._mainTexture.ignoreCameraViewport = true;
  82639. // Custom render function
  82640. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  82641. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  82642. var index;
  82643. var engine = _this._scene.getEngine();
  82644. if (depthOnlySubMeshes.length) {
  82645. engine.setColorWrite(false);
  82646. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  82647. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  82648. }
  82649. engine.setColorWrite(true);
  82650. }
  82651. for (index = 0; index < opaqueSubMeshes.length; index++) {
  82652. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  82653. }
  82654. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  82655. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  82656. }
  82657. for (index = 0; index < transparentSubMeshes.length; index++) {
  82658. _this._renderSubMesh(transparentSubMeshes.data[index]);
  82659. }
  82660. };
  82661. this._mainTexture.onClearObservable.add(function (engine) {
  82662. engine.clear(_this.neutralColor, true, true, true);
  82663. });
  82664. };
  82665. /**
  82666. * Checks for the readiness of the element composing the layer.
  82667. * @param subMesh the mesh to check for
  82668. * @param useInstances specify wether or not to use instances to render the mesh
  82669. * @param emissiveTexture the associated emissive texture used to generate the glow
  82670. * @return true if ready otherwise, false
  82671. */
  82672. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  82673. var material = subMesh.getMaterial();
  82674. if (!material) {
  82675. return false;
  82676. }
  82677. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  82678. return false;
  82679. }
  82680. var defines = [];
  82681. var attribs = [BABYLON.VertexBuffer.PositionKind];
  82682. var mesh = subMesh.getMesh();
  82683. var uv1 = false;
  82684. var uv2 = false;
  82685. // Alpha test
  82686. if (material && material.needAlphaTesting()) {
  82687. var alphaTexture = material.getAlphaTestTexture();
  82688. if (alphaTexture) {
  82689. defines.push("#define ALPHATEST");
  82690. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82691. alphaTexture.coordinatesIndex === 1) {
  82692. defines.push("#define DIFFUSEUV2");
  82693. uv2 = true;
  82694. }
  82695. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82696. defines.push("#define DIFFUSEUV1");
  82697. uv1 = true;
  82698. }
  82699. }
  82700. }
  82701. // Emissive
  82702. if (emissiveTexture) {
  82703. defines.push("#define EMISSIVE");
  82704. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  82705. emissiveTexture.coordinatesIndex === 1) {
  82706. defines.push("#define EMISSIVEUV2");
  82707. uv2 = true;
  82708. }
  82709. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82710. defines.push("#define EMISSIVEUV1");
  82711. uv1 = true;
  82712. }
  82713. }
  82714. if (uv1) {
  82715. attribs.push(BABYLON.VertexBuffer.UVKind);
  82716. defines.push("#define UV1");
  82717. }
  82718. if (uv2) {
  82719. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82720. defines.push("#define UV2");
  82721. }
  82722. // Bones
  82723. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82724. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82725. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82726. if (mesh.numBoneInfluencers > 4) {
  82727. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82728. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82729. }
  82730. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82731. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  82732. }
  82733. else {
  82734. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82735. }
  82736. // Instances
  82737. if (useInstances) {
  82738. defines.push("#define INSTANCES");
  82739. attribs.push("world0");
  82740. attribs.push("world1");
  82741. attribs.push("world2");
  82742. attribs.push("world3");
  82743. }
  82744. // Get correct effect
  82745. var join = defines.join("\n");
  82746. if (this._cachedDefines !== join) {
  82747. this._cachedDefines = join;
  82748. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  82749. }
  82750. return this._effectLayerMapGenerationEffect.isReady();
  82751. };
  82752. /**
  82753. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  82754. */
  82755. EffectLayer.prototype.render = function () {
  82756. var currentEffect = this._mergeEffect;
  82757. // Check
  82758. if (!currentEffect.isReady())
  82759. return;
  82760. for (var i = 0; i < this._postProcesses.length; i++) {
  82761. if (!this._postProcesses[i].isReady()) {
  82762. return;
  82763. }
  82764. }
  82765. var engine = this._scene.getEngine();
  82766. this.onBeforeComposeObservable.notifyObservers(this);
  82767. // Render
  82768. engine.enableEffect(currentEffect);
  82769. engine.setState(false);
  82770. // VBOs
  82771. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  82772. // Cache
  82773. var previousAlphaMode = engine.getAlphaMode();
  82774. // Go Blend.
  82775. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  82776. // Blends the map on the main canvas.
  82777. this._internalRender(currentEffect);
  82778. // Restore Alpha
  82779. engine.setAlphaMode(previousAlphaMode);
  82780. this.onAfterComposeObservable.notifyObservers(this);
  82781. // Handle size changes.
  82782. var size = this._mainTexture.getSize();
  82783. this._setMainTextureSize();
  82784. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  82785. // Recreate RTT and post processes on size change.
  82786. this.onSizeChangedObservable.notifyObservers(this);
  82787. this._disposeTextureAndPostProcesses();
  82788. this._createMainTexture();
  82789. this._createTextureAndPostProcesses();
  82790. }
  82791. };
  82792. /**
  82793. * Determine if a given mesh will be used in the current effect.
  82794. * @param mesh mesh to test
  82795. * @returns true if the mesh will be used
  82796. */
  82797. EffectLayer.prototype.hasMesh = function (mesh) {
  82798. return true;
  82799. };
  82800. /**
  82801. * Returns true if the layer contains information to display, otherwise false.
  82802. * @returns true if the glow layer should be rendered
  82803. */
  82804. EffectLayer.prototype.shouldRender = function () {
  82805. return this.isEnabled && this._shouldRender;
  82806. };
  82807. /**
  82808. * Returns true if the mesh should render, otherwise false.
  82809. * @param mesh The mesh to render
  82810. * @returns true if it should render otherwise false
  82811. */
  82812. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  82813. return true;
  82814. };
  82815. /**
  82816. * Returns true if the mesh should render, otherwise false.
  82817. * @param mesh The mesh to render
  82818. * @returns true if it should render otherwise false
  82819. */
  82820. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  82821. return true;
  82822. };
  82823. /**
  82824. * Renders the submesh passed in parameter to the generation map.
  82825. */
  82826. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  82827. var _this = this;
  82828. if (!this.shouldRender()) {
  82829. return;
  82830. }
  82831. var material = subMesh.getMaterial();
  82832. var mesh = subMesh.getRenderingMesh();
  82833. var scene = this._scene;
  82834. var engine = scene.getEngine();
  82835. if (!material) {
  82836. return;
  82837. }
  82838. // Do not block in blend mode.
  82839. if (material.needAlphaBlendingForMesh(mesh)) {
  82840. return;
  82841. }
  82842. // Culling
  82843. engine.setState(material.backFaceCulling);
  82844. // Managing instances
  82845. var batch = mesh._getInstancesRenderList(subMesh._id);
  82846. if (batch.mustReturn) {
  82847. return;
  82848. }
  82849. // Early Exit per mesh
  82850. if (!this._shouldRenderMesh(mesh)) {
  82851. return;
  82852. }
  82853. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82854. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  82855. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  82856. engine.enableEffect(this._effectLayerMapGenerationEffect);
  82857. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  82858. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  82859. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  82860. // Alpha test
  82861. if (material && material.needAlphaTesting()) {
  82862. var alphaTexture = material.getAlphaTestTexture();
  82863. if (alphaTexture) {
  82864. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  82865. var textureMatrix = alphaTexture.getTextureMatrix();
  82866. if (textureMatrix) {
  82867. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  82868. }
  82869. }
  82870. }
  82871. // Glow emissive only
  82872. if (this._emissiveTextureAndColor.texture) {
  82873. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  82874. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  82875. }
  82876. // Bones
  82877. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82878. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82879. }
  82880. // Draw
  82881. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  82882. }
  82883. else {
  82884. // Need to reset refresh rate of the shadowMap
  82885. this._mainTexture.resetRefreshCounter();
  82886. }
  82887. };
  82888. /**
  82889. * Rebuild the required buffers.
  82890. * @ignore Internal use only.
  82891. */
  82892. EffectLayer.prototype._rebuild = function () {
  82893. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82894. if (vb) {
  82895. vb._rebuild();
  82896. }
  82897. this._generateIndexBuffer();
  82898. };
  82899. /**
  82900. * Dispose only the render target textures and post process.
  82901. */
  82902. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  82903. this._mainTexture.dispose();
  82904. for (var i = 0; i < this._postProcesses.length; i++) {
  82905. if (this._postProcesses[i]) {
  82906. this._postProcesses[i].dispose();
  82907. }
  82908. }
  82909. this._postProcesses = [];
  82910. for (var i = 0; i < this._textures.length; i++) {
  82911. if (this._textures[i]) {
  82912. this._textures[i].dispose();
  82913. }
  82914. }
  82915. this._textures = [];
  82916. };
  82917. /**
  82918. * Dispose the highlight layer and free resources.
  82919. */
  82920. EffectLayer.prototype.dispose = function () {
  82921. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  82922. if (vertexBuffer) {
  82923. vertexBuffer.dispose();
  82924. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  82925. }
  82926. if (this._indexBuffer) {
  82927. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  82928. this._indexBuffer = null;
  82929. }
  82930. // Clean textures and post processes
  82931. this._disposeTextureAndPostProcesses();
  82932. // Remove from scene
  82933. var index = this._scene.effectLayers.indexOf(this, 0);
  82934. if (index > -1) {
  82935. this._scene.effectLayers.splice(index, 1);
  82936. }
  82937. // Callback
  82938. this.onDisposeObservable.notifyObservers(this);
  82939. this.onDisposeObservable.clear();
  82940. this.onBeforeRenderMainTextureObservable.clear();
  82941. this.onBeforeComposeObservable.clear();
  82942. this.onAfterComposeObservable.clear();
  82943. this.onSizeChangedObservable.clear();
  82944. };
  82945. return EffectLayer;
  82946. }());
  82947. BABYLON.EffectLayer = EffectLayer;
  82948. })(BABYLON || (BABYLON = {}));
  82949. //# sourceMappingURL=babylon.effectLayer.js.map
  82950. var BABYLON;
  82951. (function (BABYLON) {
  82952. /**
  82953. * Special Glow Blur post process only blurring the alpha channel
  82954. * It enforces keeping the most luminous color in the color channel.
  82955. */
  82956. var GlowBlurPostProcess = /** @class */ (function (_super) {
  82957. __extends(GlowBlurPostProcess, _super);
  82958. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  82959. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  82960. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  82961. _this.direction = direction;
  82962. _this.kernel = kernel;
  82963. _this.onApplyObservable.add(function (effect) {
  82964. effect.setFloat2("screenSize", _this.width, _this.height);
  82965. effect.setVector2("direction", _this.direction);
  82966. effect.setFloat("blurWidth", _this.kernel);
  82967. });
  82968. return _this;
  82969. }
  82970. return GlowBlurPostProcess;
  82971. }(BABYLON.PostProcess));
  82972. /**
  82973. * The highlight layer Helps adding a glow effect around a mesh.
  82974. *
  82975. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  82976. * glowy meshes to your scene.
  82977. *
  82978. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  82979. */
  82980. var HighlightLayer = /** @class */ (function (_super) {
  82981. __extends(HighlightLayer, _super);
  82982. /**
  82983. * Instantiates a new highlight Layer and references it to the scene..
  82984. * @param name The name of the layer
  82985. * @param scene The scene to use the layer in
  82986. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  82987. */
  82988. function HighlightLayer(name, scene, options) {
  82989. var _this = _super.call(this, name, scene) || this;
  82990. _this.name = name;
  82991. /**
  82992. * Specifies whether or not the inner glow is ACTIVE in the layer.
  82993. */
  82994. _this.innerGlow = true;
  82995. /**
  82996. * Specifies whether or not the outer glow is ACTIVE in the layer.
  82997. */
  82998. _this.outerGlow = true;
  82999. /**
  83000. * An event triggered when the highlight layer is being blurred.
  83001. */
  83002. _this.onBeforeBlurObservable = new BABYLON.Observable();
  83003. /**
  83004. * An event triggered when the highlight layer has been blurred.
  83005. */
  83006. _this.onAfterBlurObservable = new BABYLON.Observable();
  83007. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  83008. _this._meshes = {};
  83009. _this._excludedMeshes = {};
  83010. _this.neutralColor = HighlightLayer.NeutralColor;
  83011. // Warn on stencil
  83012. if (!_this._engine.isStencilEnable) {
  83013. 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 }");
  83014. }
  83015. // Adapt options
  83016. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83017. // Initialize the layer
  83018. _this._init({
  83019. alphaBlendingMode: _this._options.alphaBlendingMode,
  83020. camera: _this._options.camera,
  83021. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83022. mainTextureRatio: _this._options.mainTextureRatio
  83023. });
  83024. // Do not render as long as no meshes have been added
  83025. _this._shouldRender = false;
  83026. return _this;
  83027. }
  83028. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  83029. /**
  83030. * Gets the horizontal size of the blur.
  83031. */
  83032. get: function () {
  83033. return this._horizontalBlurPostprocess.kernel;
  83034. },
  83035. /**
  83036. * Specifies the horizontal size of the blur.
  83037. */
  83038. set: function (value) {
  83039. this._horizontalBlurPostprocess.kernel = value;
  83040. },
  83041. enumerable: true,
  83042. configurable: true
  83043. });
  83044. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  83045. /**
  83046. * Gets the vertical size of the blur.
  83047. */
  83048. get: function () {
  83049. return this._verticalBlurPostprocess.kernel;
  83050. },
  83051. /**
  83052. * Specifies the vertical size of the blur.
  83053. */
  83054. set: function (value) {
  83055. this._verticalBlurPostprocess.kernel = value;
  83056. },
  83057. enumerable: true,
  83058. configurable: true
  83059. });
  83060. /**
  83061. * Get the effect name of the layer.
  83062. * @return The effect name
  83063. */
  83064. HighlightLayer.prototype.getEffectName = function () {
  83065. return HighlightLayer.EffectName;
  83066. };
  83067. /**
  83068. * Create the merge effect. This is the shader use to blit the information back
  83069. * to the main canvas at the end of the scene rendering.
  83070. */
  83071. HighlightLayer.prototype._createMergeEffect = function () {
  83072. // Effect
  83073. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  83074. };
  83075. /**
  83076. * Creates the render target textures and post processes used in the highlight layer.
  83077. */
  83078. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  83079. var _this = this;
  83080. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  83081. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  83082. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83083. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83084. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  83085. width: blurTextureWidth,
  83086. height: blurTextureHeight
  83087. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83088. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83089. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83090. this._blurTexture.anisotropicFilteringLevel = 16;
  83091. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83092. this._blurTexture.renderParticles = false;
  83093. this._blurTexture.ignoreCameraViewport = true;
  83094. this._textures = [this._blurTexture];
  83095. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  83096. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83097. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  83098. effect.setTexture("textureSampler", _this._mainTexture);
  83099. });
  83100. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83101. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83102. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83103. });
  83104. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83105. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  83106. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83107. });
  83108. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83109. }
  83110. else {
  83111. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  83112. width: blurTextureWidth,
  83113. height: blurTextureHeight
  83114. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83115. this._horizontalBlurPostprocess.width = blurTextureWidth;
  83116. this._horizontalBlurPostprocess.height = blurTextureHeight;
  83117. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83118. effect.setTexture("textureSampler", _this._mainTexture);
  83119. });
  83120. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  83121. width: blurTextureWidth,
  83122. height: blurTextureHeight
  83123. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83124. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83125. }
  83126. this._mainTexture.onAfterUnbindObservable.add(function () {
  83127. _this.onBeforeBlurObservable.notifyObservers(_this);
  83128. var internalTexture = _this._blurTexture.getInternalTexture();
  83129. if (internalTexture) {
  83130. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  83131. }
  83132. _this.onAfterBlurObservable.notifyObservers(_this);
  83133. });
  83134. // Prevent autoClear.
  83135. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83136. };
  83137. /**
  83138. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83139. */
  83140. HighlightLayer.prototype.needStencil = function () {
  83141. return true;
  83142. };
  83143. /**
  83144. * Checks for the readiness of the element composing the layer.
  83145. * @param subMesh the mesh to check for
  83146. * @param useInstances specify wether or not to use instances to render the mesh
  83147. * @param emissiveTexture the associated emissive texture used to generate the glow
  83148. * @return true if ready otherwise, false
  83149. */
  83150. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  83151. var material = subMesh.getMaterial();
  83152. var mesh = subMesh.getRenderingMesh();
  83153. if (!material || !mesh || !this._meshes) {
  83154. return false;
  83155. }
  83156. var emissiveTexture = null;
  83157. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83158. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83159. emissiveTexture = material.emissiveTexture;
  83160. }
  83161. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83162. };
  83163. /**
  83164. * Implementation specific of rendering the generating effect on the main canvas.
  83165. * @param effect The effect used to render through
  83166. */
  83167. HighlightLayer.prototype._internalRender = function (effect) {
  83168. // Texture
  83169. effect.setTexture("textureSampler", this._blurTexture);
  83170. // Cache
  83171. var engine = this._engine;
  83172. var previousStencilBuffer = engine.getStencilBuffer();
  83173. var previousStencilFunction = engine.getStencilFunction();
  83174. var previousStencilMask = engine.getStencilMask();
  83175. var previousStencilOperationPass = engine.getStencilOperationPass();
  83176. var previousStencilOperationFail = engine.getStencilOperationFail();
  83177. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  83178. var previousStencilReference = engine.getStencilFunctionReference();
  83179. // Stencil operations
  83180. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  83181. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  83182. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  83183. // Draw order
  83184. engine.setStencilMask(0x00);
  83185. engine.setStencilBuffer(true);
  83186. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  83187. // 2 passes inner outer
  83188. if (this.outerGlow) {
  83189. effect.setFloat("offset", 0);
  83190. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  83191. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83192. }
  83193. if (this.innerGlow) {
  83194. effect.setFloat("offset", 1);
  83195. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  83196. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83197. }
  83198. // Restore Cache
  83199. engine.setStencilFunction(previousStencilFunction);
  83200. engine.setStencilMask(previousStencilMask);
  83201. engine.setStencilBuffer(previousStencilBuffer);
  83202. engine.setStencilOperationPass(previousStencilOperationPass);
  83203. engine.setStencilOperationFail(previousStencilOperationFail);
  83204. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  83205. engine.setStencilFunctionReference(previousStencilReference);
  83206. };
  83207. /**
  83208. * Returns true if the layer contains information to display, otherwise false.
  83209. */
  83210. HighlightLayer.prototype.shouldRender = function () {
  83211. if (_super.prototype.shouldRender.call(this)) {
  83212. return this._meshes ? true : false;
  83213. }
  83214. return false;
  83215. };
  83216. /**
  83217. * Returns true if the mesh should render, otherwise false.
  83218. * @param mesh The mesh to render
  83219. * @returns true if it should render otherwise false
  83220. */
  83221. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  83222. // Excluded Mesh
  83223. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  83224. return false;
  83225. }
  83226. ;
  83227. return true;
  83228. };
  83229. /**
  83230. * Sets the required values for both the emissive texture and and the main color.
  83231. */
  83232. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83233. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83234. if (highlightLayerMesh) {
  83235. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  83236. }
  83237. else {
  83238. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83239. }
  83240. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83241. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83242. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  83243. }
  83244. else {
  83245. this._emissiveTextureAndColor.texture = null;
  83246. }
  83247. };
  83248. /**
  83249. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  83250. * @param mesh The mesh to exclude from the highlight layer
  83251. */
  83252. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  83253. if (!this._excludedMeshes) {
  83254. return;
  83255. }
  83256. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83257. if (!meshExcluded) {
  83258. this._excludedMeshes[mesh.uniqueId] = {
  83259. mesh: mesh,
  83260. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  83261. mesh.getEngine().setStencilBuffer(false);
  83262. }),
  83263. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  83264. mesh.getEngine().setStencilBuffer(true);
  83265. }),
  83266. };
  83267. }
  83268. };
  83269. /**
  83270. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  83271. * @param mesh The mesh to highlight
  83272. */
  83273. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  83274. if (!this._excludedMeshes) {
  83275. return;
  83276. }
  83277. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83278. if (meshExcluded) {
  83279. if (meshExcluded.beforeRender) {
  83280. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  83281. }
  83282. if (meshExcluded.afterRender) {
  83283. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  83284. }
  83285. }
  83286. this._excludedMeshes[mesh.uniqueId] = null;
  83287. };
  83288. /**
  83289. * Determine if a given mesh will be highlighted by the current HighlightLayer
  83290. * @param mesh mesh to test
  83291. * @returns true if the mesh will be highlighted by the current HighlightLayer
  83292. */
  83293. HighlightLayer.prototype.hasMesh = function (mesh) {
  83294. if (!this._meshes) {
  83295. return false;
  83296. }
  83297. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  83298. };
  83299. /**
  83300. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  83301. * @param mesh The mesh to highlight
  83302. * @param color The color of the highlight
  83303. * @param glowEmissiveOnly Extract the glow from the emissive texture
  83304. */
  83305. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  83306. var _this = this;
  83307. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  83308. if (!this._meshes) {
  83309. return;
  83310. }
  83311. var meshHighlight = this._meshes[mesh.uniqueId];
  83312. if (meshHighlight) {
  83313. meshHighlight.color = color;
  83314. }
  83315. else {
  83316. this._meshes[mesh.uniqueId] = {
  83317. mesh: mesh,
  83318. color: color,
  83319. // Lambda required for capture due to Observable this context
  83320. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  83321. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  83322. _this._defaultStencilReference(mesh);
  83323. }
  83324. else {
  83325. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  83326. }
  83327. }),
  83328. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  83329. glowEmissiveOnly: glowEmissiveOnly
  83330. };
  83331. }
  83332. this._shouldRender = true;
  83333. };
  83334. /**
  83335. * Remove a mesh from the highlight layer in order to make it stop glowing.
  83336. * @param mesh The mesh to highlight
  83337. */
  83338. HighlightLayer.prototype.removeMesh = function (mesh) {
  83339. if (!this._meshes) {
  83340. return;
  83341. }
  83342. var meshHighlight = this._meshes[mesh.uniqueId];
  83343. if (meshHighlight) {
  83344. if (meshHighlight.observerHighlight) {
  83345. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83346. }
  83347. if (meshHighlight.observerDefault) {
  83348. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83349. }
  83350. delete this._meshes[mesh.uniqueId];
  83351. }
  83352. this._shouldRender = false;
  83353. for (var meshHighlightToCheck in this._meshes) {
  83354. if (this._meshes[meshHighlightToCheck]) {
  83355. this._shouldRender = true;
  83356. break;
  83357. }
  83358. }
  83359. };
  83360. /**
  83361. * Force the stencil to the normal expected value for none glowing parts
  83362. */
  83363. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83364. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83365. };
  83366. /**
  83367. * Free any resources and references associated to a mesh.
  83368. * Internal use
  83369. * @param mesh The mesh to free.
  83370. */
  83371. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83372. this.removeMesh(mesh);
  83373. this.removeExcludedMesh(mesh);
  83374. };
  83375. /**
  83376. * Dispose the highlight layer and free resources.
  83377. */
  83378. HighlightLayer.prototype.dispose = function () {
  83379. if (this._meshes) {
  83380. // Clean mesh references
  83381. for (var id in this._meshes) {
  83382. var meshHighlight = this._meshes[id];
  83383. if (meshHighlight && meshHighlight.mesh) {
  83384. if (meshHighlight.observerHighlight) {
  83385. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83386. }
  83387. if (meshHighlight.observerDefault) {
  83388. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83389. }
  83390. }
  83391. }
  83392. this._meshes = null;
  83393. }
  83394. if (this._excludedMeshes) {
  83395. for (var id in this._excludedMeshes) {
  83396. var meshHighlight = this._excludedMeshes[id];
  83397. if (meshHighlight) {
  83398. if (meshHighlight.beforeRender) {
  83399. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83400. }
  83401. if (meshHighlight.afterRender) {
  83402. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83403. }
  83404. }
  83405. }
  83406. this._excludedMeshes = null;
  83407. }
  83408. _super.prototype.dispose.call(this);
  83409. };
  83410. /**
  83411. * Effect Name of the highlight layer.
  83412. */
  83413. HighlightLayer.EffectName = "HighlightLayer";
  83414. /**
  83415. * The neutral color used during the preparation of the glow effect.
  83416. * This is black by default as the blend operation is a blend operation.
  83417. */
  83418. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83419. /**
  83420. * Stencil value used for glowing meshes.
  83421. */
  83422. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83423. /**
  83424. * Stencil value used for the other meshes in the scene.
  83425. */
  83426. HighlightLayer.NormalMeshStencilReference = 0x01;
  83427. return HighlightLayer;
  83428. }(BABYLON.EffectLayer));
  83429. BABYLON.HighlightLayer = HighlightLayer;
  83430. })(BABYLON || (BABYLON = {}));
  83431. //# sourceMappingURL=babylon.highlightLayer.js.map
  83432. var BABYLON;
  83433. (function (BABYLON) {
  83434. /**
  83435. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83436. *
  83437. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83438. * glowy meshes to your scene.
  83439. *
  83440. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83441. */
  83442. var GlowLayer = /** @class */ (function (_super) {
  83443. __extends(GlowLayer, _super);
  83444. /**
  83445. * Instantiates a new glow Layer and references it to the scene.
  83446. * @param name The name of the layer
  83447. * @param scene The scene to use the layer in
  83448. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83449. */
  83450. function GlowLayer(name, scene, options) {
  83451. var _this = _super.call(this, name, scene) || this;
  83452. _this.name = name;
  83453. _this._intensity = 1.0;
  83454. _this._includedOnlyMeshes = [];
  83455. _this._excludedMeshes = [];
  83456. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83457. // Adapt options
  83458. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83459. // Initialize the layer
  83460. _this._init({
  83461. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83462. camera: _this._options.camera,
  83463. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83464. mainTextureRatio: _this._options.mainTextureRatio
  83465. });
  83466. return _this;
  83467. }
  83468. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83469. /**
  83470. * Gets the kernel size of the blur.
  83471. */
  83472. get: function () {
  83473. return this._horizontalBlurPostprocess1.kernel;
  83474. },
  83475. /**
  83476. * Sets the kernel size of the blur.
  83477. */
  83478. set: function (value) {
  83479. this._horizontalBlurPostprocess1.kernel = value;
  83480. this._verticalBlurPostprocess1.kernel = value;
  83481. this._horizontalBlurPostprocess2.kernel = value;
  83482. this._verticalBlurPostprocess2.kernel = value;
  83483. },
  83484. enumerable: true,
  83485. configurable: true
  83486. });
  83487. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83488. /**
  83489. * Gets the glow intensity.
  83490. */
  83491. get: function () {
  83492. return this._intensity;
  83493. },
  83494. /**
  83495. * Sets the glow intensity.
  83496. */
  83497. set: function (value) {
  83498. this._intensity = value;
  83499. },
  83500. enumerable: true,
  83501. configurable: true
  83502. });
  83503. /**
  83504. * Get the effect name of the layer.
  83505. * @return The effect name
  83506. */
  83507. GlowLayer.prototype.getEffectName = function () {
  83508. return GlowLayer.EffectName;
  83509. };
  83510. /**
  83511. * Create the merge effect. This is the shader use to blit the information back
  83512. * to the main canvas at the end of the scene rendering.
  83513. */
  83514. GlowLayer.prototype._createMergeEffect = function () {
  83515. // Effect
  83516. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83517. };
  83518. /**
  83519. * Creates the render target textures and post processes used in the glow layer.
  83520. */
  83521. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83522. var _this = this;
  83523. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83524. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83525. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83526. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83527. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83528. width: blurTextureWidth,
  83529. height: blurTextureHeight
  83530. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83531. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83532. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83533. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83534. this._blurTexture1.renderParticles = false;
  83535. this._blurTexture1.ignoreCameraViewport = true;
  83536. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  83537. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  83538. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  83539. width: blurTextureWidth2,
  83540. height: blurTextureHeight2
  83541. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83542. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83543. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83544. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83545. this._blurTexture2.renderParticles = false;
  83546. this._blurTexture2.ignoreCameraViewport = true;
  83547. this._textures = [this._blurTexture1, this._blurTexture2];
  83548. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83549. width: blurTextureWidth,
  83550. height: blurTextureHeight
  83551. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83552. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  83553. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  83554. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  83555. effect.setTexture("textureSampler", _this._mainTexture);
  83556. });
  83557. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83558. width: blurTextureWidth,
  83559. height: blurTextureHeight
  83560. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83561. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  83562. width: blurTextureWidth2,
  83563. height: blurTextureHeight2
  83564. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83565. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  83566. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  83567. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  83568. effect.setTexture("textureSampler", _this._blurTexture1);
  83569. });
  83570. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  83571. width: blurTextureWidth2,
  83572. height: blurTextureHeight2
  83573. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83574. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83575. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  83576. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  83577. this._mainTexture.samples = this._options.mainTextureSamples;
  83578. this._mainTexture.onAfterUnbindObservable.add(function () {
  83579. var internalTexture = _this._blurTexture1.getInternalTexture();
  83580. if (internalTexture) {
  83581. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  83582. internalTexture = _this._blurTexture2.getInternalTexture();
  83583. if (internalTexture) {
  83584. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  83585. }
  83586. }
  83587. });
  83588. // Prevent autoClear.
  83589. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83590. };
  83591. /**
  83592. * Checks for the readiness of the element composing the layer.
  83593. * @param subMesh the mesh to check for
  83594. * @param useInstances specify wether or not to use instances to render the mesh
  83595. * @param emissiveTexture the associated emissive texture used to generate the glow
  83596. * @return true if ready otherwise, false
  83597. */
  83598. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  83599. var material = subMesh.getMaterial();
  83600. var mesh = subMesh.getRenderingMesh();
  83601. if (!material || !mesh) {
  83602. return false;
  83603. }
  83604. var emissiveTexture = material.emissiveTexture;
  83605. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83606. };
  83607. /**
  83608. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83609. */
  83610. GlowLayer.prototype.needStencil = function () {
  83611. return false;
  83612. };
  83613. /**
  83614. * Implementation specific of rendering the generating effect on the main canvas.
  83615. * @param effect The effect used to render through
  83616. */
  83617. GlowLayer.prototype._internalRender = function (effect) {
  83618. // Texture
  83619. effect.setTexture("textureSampler", this._blurTexture1);
  83620. effect.setTexture("textureSampler2", this._blurTexture2);
  83621. effect.setFloat("offset", this._intensity);
  83622. // Cache
  83623. var engine = this._engine;
  83624. var previousStencilBuffer = engine.getStencilBuffer();
  83625. // Draw order
  83626. engine.setStencilBuffer(false);
  83627. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83628. // Draw order
  83629. engine.setStencilBuffer(previousStencilBuffer);
  83630. };
  83631. /**
  83632. * Sets the required values for both the emissive texture and and the main color.
  83633. */
  83634. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83635. var textureLevel = 1.0;
  83636. if (this.customEmissiveTextureSelector) {
  83637. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  83638. }
  83639. else {
  83640. if (material) {
  83641. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83642. if (this._emissiveTextureAndColor.texture) {
  83643. textureLevel = this._emissiveTextureAndColor.texture.level;
  83644. }
  83645. }
  83646. else {
  83647. this._emissiveTextureAndColor.texture = null;
  83648. }
  83649. }
  83650. if (this.customEmissiveColorSelector) {
  83651. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  83652. }
  83653. else {
  83654. if (material.emissiveColor) {
  83655. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  83656. }
  83657. else {
  83658. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83659. }
  83660. }
  83661. };
  83662. /**
  83663. * Returns true if the mesh should render, otherwise false.
  83664. * @param mesh The mesh to render
  83665. * @returns true if it should render otherwise false
  83666. */
  83667. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  83668. return this.hasMesh(mesh);
  83669. };
  83670. /**
  83671. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  83672. * @param mesh The mesh to exclude from the glow layer
  83673. */
  83674. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  83675. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  83676. this._excludedMeshes.push(mesh.uniqueId);
  83677. }
  83678. };
  83679. /**
  83680. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  83681. * @param mesh The mesh to remove
  83682. */
  83683. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  83684. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  83685. if (index !== -1) {
  83686. this._excludedMeshes.splice(index, 1);
  83687. }
  83688. };
  83689. /**
  83690. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  83691. * @param mesh The mesh to include in the glow layer
  83692. */
  83693. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  83694. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  83695. this._includedOnlyMeshes.push(mesh.uniqueId);
  83696. }
  83697. };
  83698. /**
  83699. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  83700. * @param mesh The mesh to remove
  83701. */
  83702. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  83703. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  83704. if (index !== -1) {
  83705. this._includedOnlyMeshes.splice(index, 1);
  83706. }
  83707. };
  83708. /**
  83709. * Determine if a given mesh will be used in the glow layer
  83710. * @param mesh The mesh to test
  83711. * @returns true if the mesh will be highlighted by the current glow layer
  83712. */
  83713. GlowLayer.prototype.hasMesh = function (mesh) {
  83714. // Included Mesh
  83715. if (this._includedOnlyMeshes.length) {
  83716. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  83717. }
  83718. ;
  83719. // Excluded Mesh
  83720. if (this._excludedMeshes.length) {
  83721. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  83722. }
  83723. ;
  83724. return true;
  83725. };
  83726. /**
  83727. * Free any resources and references associated to a mesh.
  83728. * Internal use
  83729. * @param mesh The mesh to free.
  83730. */
  83731. GlowLayer.prototype._disposeMesh = function (mesh) {
  83732. this.removeIncludedOnlyMesh(mesh);
  83733. this.removeExcludedMesh(mesh);
  83734. };
  83735. /**
  83736. * Effect Name of the layer.
  83737. */
  83738. GlowLayer.EffectName = "GlowLayer";
  83739. /**
  83740. * The default blur kernel size used for the glow.
  83741. */
  83742. GlowLayer.DefaultBlurKernelSize = 32;
  83743. /**
  83744. * The default texture size ratio used for the glow.
  83745. */
  83746. GlowLayer.DefaultTextureRatio = 0.5;
  83747. return GlowLayer;
  83748. }(BABYLON.EffectLayer));
  83749. BABYLON.GlowLayer = GlowLayer;
  83750. })(BABYLON || (BABYLON = {}));
  83751. //# sourceMappingURL=babylon.glowLayer.js.map
  83752. var BABYLON;
  83753. (function (BABYLON) {
  83754. /**
  83755. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  83756. */
  83757. var AssetTaskState;
  83758. (function (AssetTaskState) {
  83759. /**
  83760. * Initialization
  83761. */
  83762. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  83763. /**
  83764. * Running
  83765. */
  83766. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  83767. /**
  83768. * Done
  83769. */
  83770. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  83771. /**
  83772. * Error
  83773. */
  83774. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  83775. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  83776. /**
  83777. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  83778. */
  83779. var AbstractAssetTask = /** @class */ (function () {
  83780. /**
  83781. * Creates a new {BABYLON.AssetsManager}
  83782. * @param name defines the name of the task
  83783. */
  83784. function AbstractAssetTask(
  83785. /**
  83786. * Task name
  83787. */ name) {
  83788. this.name = name;
  83789. this._isCompleted = false;
  83790. this._taskState = AssetTaskState.INIT;
  83791. }
  83792. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  83793. /**
  83794. * Get if the task is completed
  83795. */
  83796. get: function () {
  83797. return this._isCompleted;
  83798. },
  83799. enumerable: true,
  83800. configurable: true
  83801. });
  83802. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  83803. /**
  83804. * Gets the current state of the task
  83805. */
  83806. get: function () {
  83807. return this._taskState;
  83808. },
  83809. enumerable: true,
  83810. configurable: true
  83811. });
  83812. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  83813. /**
  83814. * Gets the current error object (if task is in error)
  83815. */
  83816. get: function () {
  83817. return this._errorObject;
  83818. },
  83819. enumerable: true,
  83820. configurable: true
  83821. });
  83822. /**
  83823. * Internal only
  83824. * @ignore
  83825. */
  83826. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  83827. if (this._errorObject) {
  83828. return;
  83829. }
  83830. this._errorObject = {
  83831. message: message,
  83832. exception: exception
  83833. };
  83834. };
  83835. /**
  83836. * Execute the current task
  83837. * @param scene defines the scene where you want your assets to be loaded
  83838. * @param onSuccess is a callback called when the task is successfully executed
  83839. * @param onError is a callback called if an error occurs
  83840. */
  83841. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  83842. var _this = this;
  83843. this._taskState = AssetTaskState.RUNNING;
  83844. this.runTask(scene, function () {
  83845. _this.onDoneCallback(onSuccess, onError);
  83846. }, function (msg, exception) {
  83847. _this.onErrorCallback(onError, msg, exception);
  83848. });
  83849. };
  83850. /**
  83851. * Execute the current task
  83852. * @param scene defines the scene where you want your assets to be loaded
  83853. * @param onSuccess is a callback called when the task is successfully executed
  83854. * @param onError is a callback called if an error occurs
  83855. */
  83856. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83857. throw new Error("runTask is not implemented");
  83858. };
  83859. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  83860. this._taskState = AssetTaskState.ERROR;
  83861. this._errorObject = {
  83862. message: message,
  83863. exception: exception
  83864. };
  83865. if (this.onError) {
  83866. this.onError(this, message, exception);
  83867. }
  83868. onError();
  83869. };
  83870. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  83871. try {
  83872. this._taskState = AssetTaskState.DONE;
  83873. this._isCompleted = true;
  83874. if (this.onSuccess) {
  83875. this.onSuccess(this);
  83876. }
  83877. onSuccess();
  83878. }
  83879. catch (e) {
  83880. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  83881. }
  83882. };
  83883. return AbstractAssetTask;
  83884. }());
  83885. BABYLON.AbstractAssetTask = AbstractAssetTask;
  83886. /**
  83887. * Class used to share progress information about assets loading
  83888. */
  83889. var AssetsProgressEvent = /** @class */ (function () {
  83890. /**
  83891. * Creates a {BABYLON.AssetsProgressEvent}
  83892. * @param remainingCount defines the number of remaining tasks to process
  83893. * @param totalCount defines the total number of tasks
  83894. * @param task defines the task that was just processed
  83895. */
  83896. function AssetsProgressEvent(remainingCount, totalCount, task) {
  83897. this.remainingCount = remainingCount;
  83898. this.totalCount = totalCount;
  83899. this.task = task;
  83900. }
  83901. return AssetsProgressEvent;
  83902. }());
  83903. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  83904. /**
  83905. * Define a task used by {BABYLON.AssetsManager} to load meshes
  83906. */
  83907. var MeshAssetTask = /** @class */ (function (_super) {
  83908. __extends(MeshAssetTask, _super);
  83909. /**
  83910. * Creates a new {BABYLON.MeshAssetTask}
  83911. * @param name defines the name of the task
  83912. * @param meshesNames defines the list of mesh's names you want to load
  83913. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  83914. * @param sceneFilename defines the filename of the scene to load from
  83915. */
  83916. function MeshAssetTask(
  83917. /**
  83918. * Defines the name of the task
  83919. */
  83920. name,
  83921. /**
  83922. * Defines the list of mesh's names you want to load
  83923. */
  83924. meshesNames,
  83925. /**
  83926. * Defines the root url to use as a base to load your meshes and associated resources
  83927. */
  83928. rootUrl,
  83929. /**
  83930. * Defines the filename of the scene to load from
  83931. */
  83932. sceneFilename) {
  83933. var _this = _super.call(this, name) || this;
  83934. _this.name = name;
  83935. _this.meshesNames = meshesNames;
  83936. _this.rootUrl = rootUrl;
  83937. _this.sceneFilename = sceneFilename;
  83938. return _this;
  83939. }
  83940. /**
  83941. * Execute the current task
  83942. * @param scene defines the scene where you want your assets to be loaded
  83943. * @param onSuccess is a callback called when the task is successfully executed
  83944. * @param onError is a callback called if an error occurs
  83945. */
  83946. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83947. var _this = this;
  83948. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  83949. _this.loadedMeshes = meshes;
  83950. _this.loadedParticleSystems = particleSystems;
  83951. _this.loadedSkeletons = skeletons;
  83952. onSuccess();
  83953. }, null, function (scene, message, exception) {
  83954. onError(message, exception);
  83955. });
  83956. };
  83957. return MeshAssetTask;
  83958. }(AbstractAssetTask));
  83959. BABYLON.MeshAssetTask = MeshAssetTask;
  83960. /**
  83961. * Define a task used by {BABYLON.AssetsManager} to load text content
  83962. */
  83963. var TextFileAssetTask = /** @class */ (function (_super) {
  83964. __extends(TextFileAssetTask, _super);
  83965. /**
  83966. * Creates a new TextFileAssetTask object
  83967. * @param name defines the name of the task
  83968. * @param url defines the location of the file to load
  83969. */
  83970. function TextFileAssetTask(
  83971. /**
  83972. * Defines the name of the task
  83973. */
  83974. name,
  83975. /**
  83976. * Defines the location of the file to load
  83977. */
  83978. url) {
  83979. var _this = _super.call(this, name) || this;
  83980. _this.name = name;
  83981. _this.url = url;
  83982. return _this;
  83983. }
  83984. /**
  83985. * Execute the current task
  83986. * @param scene defines the scene where you want your assets to be loaded
  83987. * @param onSuccess is a callback called when the task is successfully executed
  83988. * @param onError is a callback called if an error occurs
  83989. */
  83990. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  83991. var _this = this;
  83992. scene._loadFile(this.url, function (data) {
  83993. _this.text = data;
  83994. onSuccess();
  83995. }, undefined, false, false, function (request, exception) {
  83996. if (request) {
  83997. onError(request.status + " " + request.statusText, exception);
  83998. }
  83999. });
  84000. };
  84001. return TextFileAssetTask;
  84002. }(AbstractAssetTask));
  84003. BABYLON.TextFileAssetTask = TextFileAssetTask;
  84004. /**
  84005. * Define a task used by {BABYLON.AssetsManager} to load binary data
  84006. */
  84007. var BinaryFileAssetTask = /** @class */ (function (_super) {
  84008. __extends(BinaryFileAssetTask, _super);
  84009. /**
  84010. * Creates a new BinaryFileAssetTask object
  84011. * @param name defines the name of the new task
  84012. * @param url defines the location of the file to load
  84013. */
  84014. function BinaryFileAssetTask(
  84015. /**
  84016. * Defines the name of the task
  84017. */
  84018. name,
  84019. /**
  84020. * Defines the location of the file to load
  84021. */
  84022. url) {
  84023. var _this = _super.call(this, name) || this;
  84024. _this.name = name;
  84025. _this.url = url;
  84026. return _this;
  84027. }
  84028. /**
  84029. * Execute the current task
  84030. * @param scene defines the scene where you want your assets to be loaded
  84031. * @param onSuccess is a callback called when the task is successfully executed
  84032. * @param onError is a callback called if an error occurs
  84033. */
  84034. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84035. var _this = this;
  84036. scene._loadFile(this.url, function (data) {
  84037. _this.data = data;
  84038. onSuccess();
  84039. }, undefined, true, true, function (request, exception) {
  84040. if (request) {
  84041. onError(request.status + " " + request.statusText, exception);
  84042. }
  84043. });
  84044. };
  84045. return BinaryFileAssetTask;
  84046. }(AbstractAssetTask));
  84047. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  84048. /**
  84049. * Define a task used by {BABYLON.AssetsManager} to load images
  84050. */
  84051. var ImageAssetTask = /** @class */ (function (_super) {
  84052. __extends(ImageAssetTask, _super);
  84053. /**
  84054. * Creates a new ImageAssetTask
  84055. * @param name defines the name of the task
  84056. * @param url defines the location of the image to load
  84057. */
  84058. function ImageAssetTask(
  84059. /**
  84060. * Defines the name of the task
  84061. */
  84062. name,
  84063. /**
  84064. * Defines the location of the image to load
  84065. */
  84066. url) {
  84067. var _this = _super.call(this, name) || this;
  84068. _this.name = name;
  84069. _this.url = url;
  84070. return _this;
  84071. }
  84072. /**
  84073. * Execute the current task
  84074. * @param scene defines the scene where you want your assets to be loaded
  84075. * @param onSuccess is a callback called when the task is successfully executed
  84076. * @param onError is a callback called if an error occurs
  84077. */
  84078. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84079. var _this = this;
  84080. var img = new Image();
  84081. BABYLON.Tools.SetCorsBehavior(this.url, img);
  84082. img.onload = function () {
  84083. _this.image = img;
  84084. onSuccess();
  84085. };
  84086. img.onerror = function (err) {
  84087. onError("Error loading image", err);
  84088. };
  84089. img.src = this.url;
  84090. };
  84091. return ImageAssetTask;
  84092. }(AbstractAssetTask));
  84093. BABYLON.ImageAssetTask = ImageAssetTask;
  84094. /**
  84095. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  84096. */
  84097. var TextureAssetTask = /** @class */ (function (_super) {
  84098. __extends(TextureAssetTask, _super);
  84099. /**
  84100. * Creates a new TextureAssetTask object
  84101. * @param name defines the name of the task
  84102. * @param url defines the location of the file to load
  84103. * @param noMipmap defines if mipmap should not be generated (default is false)
  84104. * @param invertY defines if texture must be inverted on Y axis (default is false)
  84105. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84106. */
  84107. function TextureAssetTask(
  84108. /**
  84109. * Defines the name of the task
  84110. */
  84111. name,
  84112. /**
  84113. * Defines the location of the file to load
  84114. */
  84115. url,
  84116. /**
  84117. * Defines if mipmap should not be generated (default is false)
  84118. */
  84119. noMipmap,
  84120. /**
  84121. * Defines if texture must be inverted on Y axis (default is false)
  84122. */
  84123. invertY,
  84124. /**
  84125. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84126. */
  84127. samplingMode) {
  84128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84129. var _this = _super.call(this, name) || this;
  84130. _this.name = name;
  84131. _this.url = url;
  84132. _this.noMipmap = noMipmap;
  84133. _this.invertY = invertY;
  84134. _this.samplingMode = samplingMode;
  84135. return _this;
  84136. }
  84137. /**
  84138. * Execute the current task
  84139. * @param scene defines the scene where you want your assets to be loaded
  84140. * @param onSuccess is a callback called when the task is successfully executed
  84141. * @param onError is a callback called if an error occurs
  84142. */
  84143. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84144. var onload = function () {
  84145. onSuccess();
  84146. };
  84147. var onerror = function (message, exception) {
  84148. onError(message, exception);
  84149. };
  84150. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  84151. };
  84152. return TextureAssetTask;
  84153. }(AbstractAssetTask));
  84154. BABYLON.TextureAssetTask = TextureAssetTask;
  84155. /**
  84156. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  84157. */
  84158. var CubeTextureAssetTask = /** @class */ (function (_super) {
  84159. __extends(CubeTextureAssetTask, _super);
  84160. /**
  84161. * Creates a new CubeTextureAssetTask
  84162. * @param name defines the name of the task
  84163. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84164. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84165. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84166. * @param files defines the explicit list of files (undefined by default)
  84167. */
  84168. function CubeTextureAssetTask(
  84169. /**
  84170. * Defines the name of the task
  84171. */
  84172. name,
  84173. /**
  84174. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84175. */
  84176. url,
  84177. /**
  84178. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84179. */
  84180. extensions,
  84181. /**
  84182. * Defines if mipmaps should not be generated (default is false)
  84183. */
  84184. noMipmap,
  84185. /**
  84186. * Defines the explicit list of files (undefined by default)
  84187. */
  84188. files) {
  84189. var _this = _super.call(this, name) || this;
  84190. _this.name = name;
  84191. _this.url = url;
  84192. _this.extensions = extensions;
  84193. _this.noMipmap = noMipmap;
  84194. _this.files = files;
  84195. return _this;
  84196. }
  84197. /**
  84198. * Execute the current task
  84199. * @param scene defines the scene where you want your assets to be loaded
  84200. * @param onSuccess is a callback called when the task is successfully executed
  84201. * @param onError is a callback called if an error occurs
  84202. */
  84203. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84204. var onload = function () {
  84205. onSuccess();
  84206. };
  84207. var onerror = function (message, exception) {
  84208. onError(message, exception);
  84209. };
  84210. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  84211. };
  84212. return CubeTextureAssetTask;
  84213. }(AbstractAssetTask));
  84214. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  84215. /**
  84216. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  84217. */
  84218. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  84219. __extends(HDRCubeTextureAssetTask, _super);
  84220. /**
  84221. * Creates a new HDRCubeTextureAssetTask object
  84222. * @param name defines the name of the task
  84223. * @param url defines the location of the file to load
  84224. * @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.
  84225. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84226. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84227. * @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)
  84228. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84229. */
  84230. function HDRCubeTextureAssetTask(
  84231. /**
  84232. * Defines the name of the task
  84233. */
  84234. name,
  84235. /**
  84236. * Defines the location of the file to load
  84237. */
  84238. url,
  84239. /**
  84240. * 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.
  84241. */
  84242. size,
  84243. /**
  84244. * Defines if mipmaps should not be generated (default is false)
  84245. */
  84246. noMipmap,
  84247. /**
  84248. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84249. */
  84250. generateHarmonics,
  84251. /**
  84252. * 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)
  84253. */
  84254. useInGammaSpace,
  84255. /**
  84256. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84257. */
  84258. usePMREMGenerator) {
  84259. if (noMipmap === void 0) { noMipmap = false; }
  84260. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84261. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84262. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84263. var _this = _super.call(this, name) || this;
  84264. _this.name = name;
  84265. _this.url = url;
  84266. _this.size = size;
  84267. _this.noMipmap = noMipmap;
  84268. _this.generateHarmonics = generateHarmonics;
  84269. _this.useInGammaSpace = useInGammaSpace;
  84270. _this.usePMREMGenerator = usePMREMGenerator;
  84271. return _this;
  84272. }
  84273. /**
  84274. * Execute the current task
  84275. * @param scene defines the scene where you want your assets to be loaded
  84276. * @param onSuccess is a callback called when the task is successfully executed
  84277. * @param onError is a callback called if an error occurs
  84278. */
  84279. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84280. var onload = function () {
  84281. onSuccess();
  84282. };
  84283. var onerror = function (message, exception) {
  84284. onError(message, exception);
  84285. };
  84286. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  84287. };
  84288. return HDRCubeTextureAssetTask;
  84289. }(AbstractAssetTask));
  84290. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  84291. /**
  84292. * This class can be used to easily import assets into a scene
  84293. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  84294. */
  84295. var AssetsManager = /** @class */ (function () {
  84296. /**
  84297. * Creates a new AssetsManager
  84298. * @param scene defines the scene to work on
  84299. */
  84300. function AssetsManager(scene) {
  84301. this._isLoading = false;
  84302. this._tasks = new Array();
  84303. this._waitingTasksCount = 0;
  84304. this._totalTasksCount = 0;
  84305. /**
  84306. * Observable called when all tasks are processed
  84307. */
  84308. this.onTaskSuccessObservable = new BABYLON.Observable();
  84309. /**
  84310. * Observable called when a task had an error
  84311. */
  84312. this.onTaskErrorObservable = new BABYLON.Observable();
  84313. /**
  84314. * Observable called when a task is successful
  84315. */
  84316. this.onTasksDoneObservable = new BABYLON.Observable();
  84317. /**
  84318. * Observable called when a task is done (whatever the result is)
  84319. */
  84320. this.onProgressObservable = new BABYLON.Observable();
  84321. /**
  84322. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  84323. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  84324. */
  84325. this.useDefaultLoadingScreen = true;
  84326. this._scene = scene;
  84327. }
  84328. /**
  84329. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  84330. * @param taskName defines the name of the new task
  84331. * @param meshesNames defines the name of meshes to load
  84332. * @param rootUrl defines the root url to use to locate files
  84333. * @param sceneFilename defines the filename of the scene file
  84334. * @returns a new {BABYLON.MeshAssetTask} object
  84335. */
  84336. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  84337. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  84338. this._tasks.push(task);
  84339. return task;
  84340. };
  84341. /**
  84342. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  84343. * @param taskName defines the name of the new task
  84344. * @param url defines the url of the file to load
  84345. * @returns a new {BABYLON.TextFileAssetTask} object
  84346. */
  84347. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  84348. var task = new TextFileAssetTask(taskName, url);
  84349. this._tasks.push(task);
  84350. return task;
  84351. };
  84352. /**
  84353. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  84354. * @param taskName defines the name of the new task
  84355. * @param url defines the url of the file to load
  84356. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84357. */
  84358. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84359. var task = new BinaryFileAssetTask(taskName, url);
  84360. this._tasks.push(task);
  84361. return task;
  84362. };
  84363. /**
  84364. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84365. * @param taskName defines the name of the new task
  84366. * @param url defines the url of the file to load
  84367. * @returns a new {BABYLON.ImageAssetTask} object
  84368. */
  84369. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84370. var task = new ImageAssetTask(taskName, url);
  84371. this._tasks.push(task);
  84372. return task;
  84373. };
  84374. /**
  84375. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84376. * @param taskName defines the name of the new task
  84377. * @param url defines the url of the file to load
  84378. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84379. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84380. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84381. * @returns a new {BABYLON.TextureAssetTask} object
  84382. */
  84383. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84384. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84385. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84386. this._tasks.push(task);
  84387. return task;
  84388. };
  84389. /**
  84390. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84391. * @param taskName defines the name of the new task
  84392. * @param url defines the url of the file to load
  84393. * @param extensions defines the extension to use to load the cube map (can be null)
  84394. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84395. * @param files defines the list of files to load (can be null)
  84396. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84397. */
  84398. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84399. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84400. this._tasks.push(task);
  84401. return task;
  84402. };
  84403. /**
  84404. *
  84405. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84406. * @param taskName defines the name of the new task
  84407. * @param url defines the url of the file to load
  84408. * @param size defines the size you want for the cubemap (can be null)
  84409. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84410. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84411. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84412. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84413. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84414. */
  84415. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84416. if (noMipmap === void 0) { noMipmap = false; }
  84417. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84418. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84419. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84420. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84421. this._tasks.push(task);
  84422. return task;
  84423. };
  84424. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84425. var _this = this;
  84426. this._waitingTasksCount--;
  84427. try {
  84428. if (task.taskState === AssetTaskState.DONE) {
  84429. // Let's remove successfull tasks
  84430. BABYLON.Tools.SetImmediate(function () {
  84431. var index = _this._tasks.indexOf(task);
  84432. if (index > -1) {
  84433. _this._tasks.splice(index, 1);
  84434. }
  84435. });
  84436. }
  84437. if (this.onProgress) {
  84438. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84439. }
  84440. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84441. }
  84442. catch (e) {
  84443. BABYLON.Tools.Error("Error running progress callbacks.");
  84444. console.log(e);
  84445. }
  84446. if (this._waitingTasksCount === 0) {
  84447. try {
  84448. if (this.onFinish) {
  84449. this.onFinish(this._tasks);
  84450. }
  84451. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84452. }
  84453. catch (e) {
  84454. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84455. console.log(e);
  84456. }
  84457. this._isLoading = false;
  84458. this._scene.getEngine().hideLoadingUI();
  84459. }
  84460. };
  84461. AssetsManager.prototype._runTask = function (task) {
  84462. var _this = this;
  84463. var done = function () {
  84464. try {
  84465. if (_this.onTaskSuccess) {
  84466. _this.onTaskSuccess(task);
  84467. }
  84468. _this.onTaskSuccessObservable.notifyObservers(task);
  84469. _this._decreaseWaitingTasksCount(task);
  84470. }
  84471. catch (e) {
  84472. error("Error executing task success callbacks", e);
  84473. }
  84474. };
  84475. var error = function (message, exception) {
  84476. task._setErrorObject(message, exception);
  84477. if (_this.onTaskError) {
  84478. _this.onTaskError(task);
  84479. }
  84480. _this.onTaskErrorObservable.notifyObservers(task);
  84481. _this._decreaseWaitingTasksCount(task);
  84482. };
  84483. task.run(this._scene, done, error);
  84484. };
  84485. /**
  84486. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84487. * @return the current instance of the {BABYLON.AssetsManager}
  84488. */
  84489. AssetsManager.prototype.reset = function () {
  84490. this._isLoading = false;
  84491. this._tasks = new Array();
  84492. return this;
  84493. };
  84494. /**
  84495. * Start the loading process
  84496. * @return the current instance of the {BABYLON.AssetsManager}
  84497. */
  84498. AssetsManager.prototype.load = function () {
  84499. if (this._isLoading) {
  84500. return this;
  84501. }
  84502. this._isLoading = true;
  84503. this._waitingTasksCount = this._tasks.length;
  84504. this._totalTasksCount = this._tasks.length;
  84505. if (this._waitingTasksCount === 0) {
  84506. this._isLoading = false;
  84507. if (this.onFinish) {
  84508. this.onFinish(this._tasks);
  84509. }
  84510. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84511. return this;
  84512. }
  84513. if (this.useDefaultLoadingScreen) {
  84514. this._scene.getEngine().displayLoadingUI();
  84515. }
  84516. for (var index = 0; index < this._tasks.length; index++) {
  84517. var task = this._tasks[index];
  84518. this._runTask(task);
  84519. }
  84520. return this;
  84521. };
  84522. return AssetsManager;
  84523. }());
  84524. BABYLON.AssetsManager = AssetsManager;
  84525. })(BABYLON || (BABYLON = {}));
  84526. //# sourceMappingURL=babylon.assetsManager.js.map
  84527. var BABYLON;
  84528. (function (BABYLON) {
  84529. var serializedGeometries = [];
  84530. var serializeGeometry = function (geometry, serializationGeometries) {
  84531. if (serializedGeometries[geometry.id]) {
  84532. return;
  84533. }
  84534. if (geometry.doNotSerialize) {
  84535. return;
  84536. }
  84537. if (geometry instanceof BABYLON.BoxGeometry) {
  84538. serializationGeometries.boxes.push(geometry.serialize());
  84539. }
  84540. else if (geometry instanceof BABYLON.SphereGeometry) {
  84541. serializationGeometries.spheres.push(geometry.serialize());
  84542. }
  84543. else if (geometry instanceof BABYLON.CylinderGeometry) {
  84544. serializationGeometries.cylinders.push(geometry.serialize());
  84545. }
  84546. else if (geometry instanceof BABYLON.TorusGeometry) {
  84547. serializationGeometries.toruses.push(geometry.serialize());
  84548. }
  84549. else if (geometry instanceof BABYLON.GroundGeometry) {
  84550. serializationGeometries.grounds.push(geometry.serialize());
  84551. }
  84552. else if (geometry instanceof BABYLON.Plane) {
  84553. serializationGeometries.planes.push(geometry.serialize());
  84554. }
  84555. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  84556. serializationGeometries.torusKnots.push(geometry.serialize());
  84557. }
  84558. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  84559. throw new Error("Unknown primitive type");
  84560. }
  84561. else {
  84562. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  84563. }
  84564. serializedGeometries[geometry.id] = true;
  84565. };
  84566. var serializeMesh = function (mesh, serializationScene) {
  84567. var serializationObject = {};
  84568. // Geometry
  84569. var geometry = mesh._geometry;
  84570. if (geometry) {
  84571. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  84572. // 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
  84573. serializeGeometry(geometry, serializationScene.geometries);
  84574. }
  84575. }
  84576. // Custom
  84577. if (mesh.serialize) {
  84578. mesh.serialize(serializationObject);
  84579. }
  84580. return serializationObject;
  84581. };
  84582. var finalizeSingleMesh = function (mesh, serializationObject) {
  84583. //only works if the mesh is already loaded
  84584. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84585. //serialize material
  84586. if (mesh.material) {
  84587. if (mesh.material instanceof BABYLON.StandardMaterial) {
  84588. serializationObject.materials = serializationObject.materials || [];
  84589. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84590. serializationObject.materials.push(mesh.material.serialize());
  84591. }
  84592. }
  84593. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  84594. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  84595. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  84596. serializationObject.multiMaterials.push(mesh.material.serialize());
  84597. }
  84598. }
  84599. }
  84600. //serialize geometry
  84601. var geometry = mesh._geometry;
  84602. if (geometry) {
  84603. if (!serializationObject.geometries) {
  84604. serializationObject.geometries = {};
  84605. serializationObject.geometries.boxes = [];
  84606. serializationObject.geometries.spheres = [];
  84607. serializationObject.geometries.cylinders = [];
  84608. serializationObject.geometries.toruses = [];
  84609. serializationObject.geometries.grounds = [];
  84610. serializationObject.geometries.planes = [];
  84611. serializationObject.geometries.torusKnots = [];
  84612. serializationObject.geometries.vertexData = [];
  84613. }
  84614. serializeGeometry(geometry, serializationObject.geometries);
  84615. }
  84616. // Skeletons
  84617. if (mesh.skeleton) {
  84618. serializationObject.skeletons = serializationObject.skeletons || [];
  84619. serializationObject.skeletons.push(mesh.skeleton.serialize());
  84620. }
  84621. //serialize the actual mesh
  84622. serializationObject.meshes = serializationObject.meshes || [];
  84623. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84624. }
  84625. };
  84626. var SceneSerializer = /** @class */ (function () {
  84627. function SceneSerializer() {
  84628. }
  84629. SceneSerializer.ClearCache = function () {
  84630. serializedGeometries = [];
  84631. };
  84632. SceneSerializer.Serialize = function (scene) {
  84633. var serializationObject = {};
  84634. SceneSerializer.ClearCache();
  84635. // Scene
  84636. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  84637. serializationObject.autoClear = scene.autoClear;
  84638. serializationObject.clearColor = scene.clearColor.asArray();
  84639. serializationObject.ambientColor = scene.ambientColor.asArray();
  84640. serializationObject.gravity = scene.gravity.asArray();
  84641. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  84642. serializationObject.workerCollisions = scene.workerCollisions;
  84643. // Fog
  84644. if (scene.fogMode && scene.fogMode !== 0) {
  84645. serializationObject.fogMode = scene.fogMode;
  84646. serializationObject.fogColor = scene.fogColor.asArray();
  84647. serializationObject.fogStart = scene.fogStart;
  84648. serializationObject.fogEnd = scene.fogEnd;
  84649. serializationObject.fogDensity = scene.fogDensity;
  84650. }
  84651. //Physics
  84652. if (scene.isPhysicsEnabled()) {
  84653. var physicEngine = scene.getPhysicsEngine();
  84654. if (physicEngine) {
  84655. serializationObject.physicsEnabled = true;
  84656. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  84657. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  84658. }
  84659. }
  84660. // Metadata
  84661. if (scene.metadata) {
  84662. serializationObject.metadata = scene.metadata;
  84663. }
  84664. // Morph targets
  84665. serializationObject.morphTargetManagers = [];
  84666. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  84667. var abstractMesh = _a[_i];
  84668. var manager = abstractMesh.morphTargetManager;
  84669. if (manager) {
  84670. serializationObject.morphTargetManagers.push(manager.serialize());
  84671. }
  84672. }
  84673. // Lights
  84674. serializationObject.lights = [];
  84675. var index;
  84676. var light;
  84677. for (index = 0; index < scene.lights.length; index++) {
  84678. light = scene.lights[index];
  84679. if (!light.doNotSerialize) {
  84680. serializationObject.lights.push(light.serialize());
  84681. }
  84682. }
  84683. // Cameras
  84684. serializationObject.cameras = [];
  84685. for (index = 0; index < scene.cameras.length; index++) {
  84686. var camera = scene.cameras[index];
  84687. if (!camera.doNotSerialize) {
  84688. serializationObject.cameras.push(camera.serialize());
  84689. }
  84690. }
  84691. if (scene.activeCamera) {
  84692. serializationObject.activeCameraID = scene.activeCamera.id;
  84693. }
  84694. // Animations
  84695. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  84696. // Materials
  84697. serializationObject.materials = [];
  84698. serializationObject.multiMaterials = [];
  84699. var material;
  84700. for (index = 0; index < scene.materials.length; index++) {
  84701. material = scene.materials[index];
  84702. if (!material.doNotSerialize) {
  84703. serializationObject.materials.push(material.serialize());
  84704. }
  84705. }
  84706. // MultiMaterials
  84707. serializationObject.multiMaterials = [];
  84708. for (index = 0; index < scene.multiMaterials.length; index++) {
  84709. var multiMaterial = scene.multiMaterials[index];
  84710. serializationObject.multiMaterials.push(multiMaterial.serialize());
  84711. }
  84712. // Environment texture
  84713. if (scene.environmentTexture) {
  84714. serializationObject.environmentTexture = scene.environmentTexture.name;
  84715. }
  84716. // Skeletons
  84717. serializationObject.skeletons = [];
  84718. for (index = 0; index < scene.skeletons.length; index++) {
  84719. var skeleton = scene.skeletons[index];
  84720. if (!skeleton.doNotSerialize) {
  84721. serializationObject.skeletons.push(skeleton.serialize());
  84722. }
  84723. }
  84724. // Transform nodes
  84725. serializationObject.transformNodes = [];
  84726. for (index = 0; index < scene.transformNodes.length; index++) {
  84727. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  84728. }
  84729. // Geometries
  84730. serializationObject.geometries = {};
  84731. serializationObject.geometries.boxes = [];
  84732. serializationObject.geometries.spheres = [];
  84733. serializationObject.geometries.cylinders = [];
  84734. serializationObject.geometries.toruses = [];
  84735. serializationObject.geometries.grounds = [];
  84736. serializationObject.geometries.planes = [];
  84737. serializationObject.geometries.torusKnots = [];
  84738. serializationObject.geometries.vertexData = [];
  84739. serializedGeometries = [];
  84740. var geometries = scene.getGeometries();
  84741. for (index = 0; index < geometries.length; index++) {
  84742. var geometry = geometries[index];
  84743. if (geometry.isReady()) {
  84744. serializeGeometry(geometry, serializationObject.geometries);
  84745. }
  84746. }
  84747. // Meshes
  84748. serializationObject.meshes = [];
  84749. for (index = 0; index < scene.meshes.length; index++) {
  84750. var abstractMesh = scene.meshes[index];
  84751. if (abstractMesh instanceof BABYLON.Mesh) {
  84752. var mesh = abstractMesh;
  84753. if (!mesh.doNotSerialize) {
  84754. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  84755. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  84756. }
  84757. }
  84758. }
  84759. }
  84760. // Particles Systems
  84761. serializationObject.particleSystems = [];
  84762. for (index = 0; index < scene.particleSystems.length; index++) {
  84763. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  84764. }
  84765. // Lens flares
  84766. serializationObject.lensFlareSystems = [];
  84767. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  84768. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  84769. }
  84770. // Shadows
  84771. serializationObject.shadowGenerators = [];
  84772. for (index = 0; index < scene.lights.length; index++) {
  84773. light = scene.lights[index];
  84774. var shadowGenerator = light.getShadowGenerator();
  84775. if (shadowGenerator) {
  84776. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  84777. }
  84778. }
  84779. // Action Manager
  84780. if (scene.actionManager) {
  84781. serializationObject.actions = scene.actionManager.serialize("scene");
  84782. }
  84783. // Audio
  84784. serializationObject.sounds = [];
  84785. for (index = 0; index < scene.soundTracks.length; index++) {
  84786. var soundtrack = scene.soundTracks[index];
  84787. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  84788. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  84789. }
  84790. }
  84791. return serializationObject;
  84792. };
  84793. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  84794. if (withParents === void 0) { withParents = false; }
  84795. if (withChildren === void 0) { withChildren = false; }
  84796. var serializationObject = {};
  84797. SceneSerializer.ClearCache();
  84798. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  84799. if (withParents || withChildren) {
  84800. //deliberate for loop! not for each, appended should be processed as well.
  84801. for (var i = 0; i < toSerialize.length; ++i) {
  84802. if (withChildren) {
  84803. toSerialize[i].getDescendants().forEach(function (node) {
  84804. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  84805. toSerialize.push(node);
  84806. }
  84807. });
  84808. }
  84809. //make sure the array doesn't contain the object already
  84810. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  84811. toSerialize.push(toSerialize[i].parent);
  84812. }
  84813. }
  84814. }
  84815. toSerialize.forEach(function (mesh) {
  84816. finalizeSingleMesh(mesh, serializationObject);
  84817. });
  84818. return serializationObject;
  84819. };
  84820. return SceneSerializer;
  84821. }());
  84822. BABYLON.SceneSerializer = SceneSerializer;
  84823. })(BABYLON || (BABYLON = {}));
  84824. //# sourceMappingURL=babylon.sceneSerializer.js.map
  84825. var BABYLON;
  84826. (function (BABYLON) {
  84827. var ReflectionProbe = /** @class */ (function () {
  84828. function ReflectionProbe(name, size, scene, generateMipMaps) {
  84829. if (generateMipMaps === void 0) { generateMipMaps = true; }
  84830. var _this = this;
  84831. this.name = name;
  84832. this._viewMatrix = BABYLON.Matrix.Identity();
  84833. this._target = BABYLON.Vector3.Zero();
  84834. this._add = BABYLON.Vector3.Zero();
  84835. this.invertYAxis = false;
  84836. this.position = BABYLON.Vector3.Zero();
  84837. this._scene = scene;
  84838. this._scene.reflectionProbes.push(this);
  84839. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  84840. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  84841. switch (faceIndex) {
  84842. case 0:
  84843. _this._add.copyFromFloats(1, 0, 0);
  84844. break;
  84845. case 1:
  84846. _this._add.copyFromFloats(-1, 0, 0);
  84847. break;
  84848. case 2:
  84849. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  84850. break;
  84851. case 3:
  84852. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  84853. break;
  84854. case 4:
  84855. _this._add.copyFromFloats(0, 0, 1);
  84856. break;
  84857. case 5:
  84858. _this._add.copyFromFloats(0, 0, -1);
  84859. break;
  84860. }
  84861. if (_this._attachedMesh) {
  84862. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  84863. }
  84864. _this.position.addToRef(_this._add, _this._target);
  84865. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  84866. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  84867. scene._forcedViewPosition = _this.position;
  84868. });
  84869. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  84870. scene._forcedViewPosition = null;
  84871. scene.updateTransformMatrix(true);
  84872. });
  84873. if (scene.activeCamera) {
  84874. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  84875. }
  84876. }
  84877. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  84878. get: function () {
  84879. return this._renderTargetTexture.samples;
  84880. },
  84881. set: function (value) {
  84882. this._renderTargetTexture.samples = value;
  84883. },
  84884. enumerable: true,
  84885. configurable: true
  84886. });
  84887. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  84888. get: function () {
  84889. return this._renderTargetTexture.refreshRate;
  84890. },
  84891. set: function (value) {
  84892. this._renderTargetTexture.refreshRate = value;
  84893. },
  84894. enumerable: true,
  84895. configurable: true
  84896. });
  84897. ReflectionProbe.prototype.getScene = function () {
  84898. return this._scene;
  84899. };
  84900. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  84901. get: function () {
  84902. return this._renderTargetTexture;
  84903. },
  84904. enumerable: true,
  84905. configurable: true
  84906. });
  84907. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  84908. get: function () {
  84909. return this._renderTargetTexture.renderList;
  84910. },
  84911. enumerable: true,
  84912. configurable: true
  84913. });
  84914. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  84915. this._attachedMesh = mesh;
  84916. };
  84917. /**
  84918. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  84919. *
  84920. * @param renderingGroupId The rendering group id corresponding to its index
  84921. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  84922. */
  84923. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  84924. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  84925. };
  84926. ReflectionProbe.prototype.dispose = function () {
  84927. var index = this._scene.reflectionProbes.indexOf(this);
  84928. if (index !== -1) {
  84929. // Remove from the scene if found
  84930. this._scene.reflectionProbes.splice(index, 1);
  84931. }
  84932. if (this._renderTargetTexture) {
  84933. this._renderTargetTexture.dispose();
  84934. this._renderTargetTexture = null;
  84935. }
  84936. };
  84937. return ReflectionProbe;
  84938. }());
  84939. BABYLON.ReflectionProbe = ReflectionProbe;
  84940. })(BABYLON || (BABYLON = {}));
  84941. //# sourceMappingURL=babylon.reflectionProbe.js.map
  84942. var BABYLON;
  84943. (function (BABYLON) {
  84944. var Layer = /** @class */ (function () {
  84945. function Layer(name, imgUrl, scene, isBackground, color) {
  84946. this.name = name;
  84947. this.scale = new BABYLON.Vector2(1, 1);
  84948. this.offset = new BABYLON.Vector2(0, 0);
  84949. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  84950. this.layerMask = 0x0FFFFFFF;
  84951. this._vertexBuffers = {};
  84952. // Events
  84953. /**
  84954. * An event triggered when the layer is disposed.
  84955. * @type {BABYLON.Observable}
  84956. */
  84957. this.onDisposeObservable = new BABYLON.Observable();
  84958. /**
  84959. * An event triggered before rendering the scene
  84960. * @type {BABYLON.Observable}
  84961. */
  84962. this.onBeforeRenderObservable = new BABYLON.Observable();
  84963. /**
  84964. * An event triggered after rendering the scene
  84965. * @type {BABYLON.Observable}
  84966. */
  84967. this.onAfterRenderObservable = new BABYLON.Observable();
  84968. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  84969. this.isBackground = isBackground === undefined ? true : isBackground;
  84970. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  84971. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  84972. this._scene.layers.push(this);
  84973. var engine = this._scene.getEngine();
  84974. // VBO
  84975. var vertices = [];
  84976. vertices.push(1, 1);
  84977. vertices.push(-1, 1);
  84978. vertices.push(-1, -1);
  84979. vertices.push(1, -1);
  84980. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  84981. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  84982. this._createIndexBuffer();
  84983. // Effects
  84984. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  84985. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  84986. }
  84987. Object.defineProperty(Layer.prototype, "onDispose", {
  84988. set: function (callback) {
  84989. if (this._onDisposeObserver) {
  84990. this.onDisposeObservable.remove(this._onDisposeObserver);
  84991. }
  84992. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  84993. },
  84994. enumerable: true,
  84995. configurable: true
  84996. });
  84997. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  84998. set: function (callback) {
  84999. if (this._onBeforeRenderObserver) {
  85000. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  85001. }
  85002. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  85003. },
  85004. enumerable: true,
  85005. configurable: true
  85006. });
  85007. Object.defineProperty(Layer.prototype, "onAfterRender", {
  85008. set: function (callback) {
  85009. if (this._onAfterRenderObserver) {
  85010. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  85011. }
  85012. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  85013. },
  85014. enumerable: true,
  85015. configurable: true
  85016. });
  85017. Layer.prototype._createIndexBuffer = function () {
  85018. var engine = this._scene.getEngine();
  85019. // Indices
  85020. var indices = [];
  85021. indices.push(0);
  85022. indices.push(1);
  85023. indices.push(2);
  85024. indices.push(0);
  85025. indices.push(2);
  85026. indices.push(3);
  85027. this._indexBuffer = engine.createIndexBuffer(indices);
  85028. };
  85029. Layer.prototype._rebuild = function () {
  85030. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85031. if (vb) {
  85032. vb._rebuild();
  85033. }
  85034. this._createIndexBuffer();
  85035. };
  85036. Layer.prototype.render = function () {
  85037. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  85038. // Check
  85039. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  85040. return;
  85041. var engine = this._scene.getEngine();
  85042. this.onBeforeRenderObservable.notifyObservers(this);
  85043. // Render
  85044. engine.enableEffect(currentEffect);
  85045. engine.setState(false);
  85046. // Texture
  85047. currentEffect.setTexture("textureSampler", this.texture);
  85048. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  85049. // Color
  85050. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  85051. // Scale / offset
  85052. currentEffect.setVector2("offset", this.offset);
  85053. currentEffect.setVector2("scale", this.scale);
  85054. // VBOs
  85055. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85056. // Draw order
  85057. if (!this.alphaTest) {
  85058. engine.setAlphaMode(this.alphaBlendingMode);
  85059. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85060. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85061. }
  85062. else {
  85063. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85064. }
  85065. this.onAfterRenderObservable.notifyObservers(this);
  85066. };
  85067. Layer.prototype.dispose = function () {
  85068. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85069. if (vertexBuffer) {
  85070. vertexBuffer.dispose();
  85071. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85072. }
  85073. if (this._indexBuffer) {
  85074. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85075. this._indexBuffer = null;
  85076. }
  85077. if (this.texture) {
  85078. this.texture.dispose();
  85079. this.texture = null;
  85080. }
  85081. // Remove from scene
  85082. var index = this._scene.layers.indexOf(this);
  85083. this._scene.layers.splice(index, 1);
  85084. // Callback
  85085. this.onDisposeObservable.notifyObservers(this);
  85086. this.onDisposeObservable.clear();
  85087. this.onAfterRenderObservable.clear();
  85088. this.onBeforeRenderObservable.clear();
  85089. };
  85090. return Layer;
  85091. }());
  85092. BABYLON.Layer = Layer;
  85093. })(BABYLON || (BABYLON = {}));
  85094. //# sourceMappingURL=babylon.layer.js.map
  85095. var BABYLON;
  85096. (function (BABYLON) {
  85097. var TextureTools = /** @class */ (function () {
  85098. function TextureTools() {
  85099. }
  85100. /**
  85101. * Uses the GPU to create a copy texture rescaled at a given size
  85102. * @param texture Texture to copy from
  85103. * @param width Desired width
  85104. * @param height Desired height
  85105. * @return Generated texture
  85106. */
  85107. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  85108. if (useBilinearMode === void 0) { useBilinearMode = true; }
  85109. var scene = texture.getScene();
  85110. var engine = scene.getEngine();
  85111. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  85112. rtt.wrapU = texture.wrapU;
  85113. rtt.wrapV = texture.wrapV;
  85114. rtt.uOffset = texture.uOffset;
  85115. rtt.vOffset = texture.vOffset;
  85116. rtt.uScale = texture.uScale;
  85117. rtt.vScale = texture.vScale;
  85118. rtt.uAng = texture.uAng;
  85119. rtt.vAng = texture.vAng;
  85120. rtt.wAng = texture.wAng;
  85121. rtt.coordinatesIndex = texture.coordinatesIndex;
  85122. rtt.level = texture.level;
  85123. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  85124. rtt._texture.isReady = false;
  85125. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85126. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85127. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85128. passPostProcess.getEffect().executeWhenCompiled(function () {
  85129. passPostProcess.onApply = function (effect) {
  85130. effect.setTexture("textureSampler", texture);
  85131. };
  85132. var internalTexture = rtt.getInternalTexture();
  85133. if (internalTexture) {
  85134. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  85135. engine.unBindFramebuffer(internalTexture);
  85136. rtt.disposeFramebufferObjects();
  85137. passPostProcess.dispose();
  85138. internalTexture.isReady = true;
  85139. }
  85140. });
  85141. return rtt;
  85142. };
  85143. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  85144. if (!scene._environmentBRDFTexture) {
  85145. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85146. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85147. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85148. scene._environmentBRDFTexture = texture;
  85149. }
  85150. return scene._environmentBRDFTexture;
  85151. };
  85152. 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=";
  85153. return TextureTools;
  85154. }());
  85155. BABYLON.TextureTools = TextureTools;
  85156. })(BABYLON || (BABYLON = {}));
  85157. //# sourceMappingURL=babylon.textureTools.js.map
  85158. var BABYLON;
  85159. (function (BABYLON) {
  85160. var FramingBehavior = /** @class */ (function () {
  85161. function FramingBehavior() {
  85162. this._mode = FramingBehavior.FitFrustumSidesMode;
  85163. this._radiusScale = 1.0;
  85164. this._positionScale = 0.5;
  85165. this._defaultElevation = 0.3;
  85166. this._elevationReturnTime = 1500;
  85167. this._elevationReturnWaitTime = 1000;
  85168. this._zoomStopsAnimation = false;
  85169. this._framingTime = 1500;
  85170. this._isPointerDown = false;
  85171. this._lastInteractionTime = -Infinity;
  85172. // Framing control
  85173. this._animatables = new Array();
  85174. this._betaIsAnimating = false;
  85175. }
  85176. Object.defineProperty(FramingBehavior.prototype, "name", {
  85177. get: function () {
  85178. return "Framing";
  85179. },
  85180. enumerable: true,
  85181. configurable: true
  85182. });
  85183. Object.defineProperty(FramingBehavior.prototype, "mode", {
  85184. /**
  85185. * Gets current mode used by the behavior.
  85186. */
  85187. get: function () {
  85188. return this._mode;
  85189. },
  85190. /**
  85191. * Sets the current mode used by the behavior
  85192. */
  85193. set: function (mode) {
  85194. this._mode = mode;
  85195. },
  85196. enumerable: true,
  85197. configurable: true
  85198. });
  85199. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  85200. /**
  85201. * Gets the scale applied to the radius
  85202. */
  85203. get: function () {
  85204. return this._radiusScale;
  85205. },
  85206. /**
  85207. * Sets the scale applied to the radius (1 by default)
  85208. */
  85209. set: function (radius) {
  85210. this._radiusScale = radius;
  85211. },
  85212. enumerable: true,
  85213. configurable: true
  85214. });
  85215. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  85216. /**
  85217. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85218. */
  85219. get: function () {
  85220. return this._positionScale;
  85221. },
  85222. /**
  85223. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85224. */
  85225. set: function (scale) {
  85226. this._positionScale = scale;
  85227. },
  85228. enumerable: true,
  85229. configurable: true
  85230. });
  85231. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  85232. /**
  85233. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85234. * behaviour is triggered, in radians.
  85235. */
  85236. get: function () {
  85237. return this._defaultElevation;
  85238. },
  85239. /**
  85240. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85241. * behaviour is triggered, in radians.
  85242. */
  85243. set: function (elevation) {
  85244. this._defaultElevation = elevation;
  85245. },
  85246. enumerable: true,
  85247. configurable: true
  85248. });
  85249. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  85250. /**
  85251. * Gets the time (in milliseconds) taken to return to the default beta position.
  85252. * Negative value indicates camera should not return to default.
  85253. */
  85254. get: function () {
  85255. return this._elevationReturnTime;
  85256. },
  85257. /**
  85258. * Sets the time (in milliseconds) taken to return to the default beta position.
  85259. * Negative value indicates camera should not return to default.
  85260. */
  85261. set: function (speed) {
  85262. this._elevationReturnTime = speed;
  85263. },
  85264. enumerable: true,
  85265. configurable: true
  85266. });
  85267. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  85268. /**
  85269. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85270. */
  85271. get: function () {
  85272. return this._elevationReturnWaitTime;
  85273. },
  85274. /**
  85275. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85276. */
  85277. set: function (time) {
  85278. this._elevationReturnWaitTime = time;
  85279. },
  85280. enumerable: true,
  85281. configurable: true
  85282. });
  85283. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  85284. /**
  85285. * Gets the flag that indicates if user zooming should stop animation.
  85286. */
  85287. get: function () {
  85288. return this._zoomStopsAnimation;
  85289. },
  85290. /**
  85291. * Sets the flag that indicates if user zooming should stop animation.
  85292. */
  85293. set: function (flag) {
  85294. this._zoomStopsAnimation = flag;
  85295. },
  85296. enumerable: true,
  85297. configurable: true
  85298. });
  85299. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  85300. /**
  85301. * Gets the transition time when framing the mesh, in milliseconds
  85302. */
  85303. get: function () {
  85304. return this._framingTime;
  85305. },
  85306. /**
  85307. * Sets the transition time when framing the mesh, in milliseconds
  85308. */
  85309. set: function (time) {
  85310. this._framingTime = time;
  85311. },
  85312. enumerable: true,
  85313. configurable: true
  85314. });
  85315. FramingBehavior.prototype.init = function () {
  85316. // Do notihng
  85317. };
  85318. FramingBehavior.prototype.attach = function (camera) {
  85319. var _this = this;
  85320. this._attachedCamera = camera;
  85321. var scene = this._attachedCamera.getScene();
  85322. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  85323. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85324. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85325. _this._isPointerDown = true;
  85326. return;
  85327. }
  85328. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85329. _this._isPointerDown = false;
  85330. }
  85331. });
  85332. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85333. if (mesh) {
  85334. _this.zoomOnMesh(mesh);
  85335. }
  85336. });
  85337. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85338. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85339. _this._applyUserInteraction();
  85340. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  85341. // back to the default position after a given timeout
  85342. _this._maintainCameraAboveGround();
  85343. });
  85344. };
  85345. FramingBehavior.prototype.detach = function () {
  85346. if (!this._attachedCamera) {
  85347. return;
  85348. }
  85349. var scene = this._attachedCamera.getScene();
  85350. if (this._onPrePointerObservableObserver) {
  85351. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85352. }
  85353. if (this._onAfterCheckInputsObserver) {
  85354. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85355. }
  85356. if (this._onMeshTargetChangedObserver) {
  85357. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85358. }
  85359. this._attachedCamera = null;
  85360. };
  85361. /**
  85362. * Targets the given mesh and updates zoom level accordingly.
  85363. * @param mesh The mesh to target.
  85364. * @param radius Optional. If a cached radius position already exists, overrides default.
  85365. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85366. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85367. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85368. */
  85369. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85370. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85371. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85372. mesh.computeWorldMatrix(true);
  85373. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85374. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85375. };
  85376. /**
  85377. * Targets the given mesh with its children and updates zoom level accordingly.
  85378. * @param mesh The mesh to target.
  85379. * @param radius Optional. If a cached radius position already exists, overrides default.
  85380. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85381. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85382. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85383. */
  85384. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85385. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85386. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85387. mesh.computeWorldMatrix(true);
  85388. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85389. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85390. };
  85391. /**
  85392. * Targets the given meshes with their children and updates zoom level accordingly.
  85393. * @param meshes The mesh to target.
  85394. * @param radius Optional. If a cached radius position already exists, overrides default.
  85395. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85396. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85397. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85398. */
  85399. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85400. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85401. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85402. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85403. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85404. for (var i = 0; i < meshes.length; i++) {
  85405. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85406. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85407. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85408. }
  85409. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85410. };
  85411. /**
  85412. * Targets the given mesh and updates zoom level accordingly.
  85413. * @param mesh The mesh to target.
  85414. * @param radius Optional. If a cached radius position already exists, overrides default.
  85415. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85416. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85417. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85418. */
  85419. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85420. var _this = this;
  85421. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85422. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85423. var zoomTarget;
  85424. if (!this._attachedCamera) {
  85425. return;
  85426. }
  85427. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85428. var bottom = minimumWorld.y;
  85429. var top = maximumWorld.y;
  85430. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85431. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85432. if (focusOnOriginXZ) {
  85433. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85434. }
  85435. else {
  85436. var centerWorld = minimumWorld.add(radiusWorld);
  85437. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85438. }
  85439. if (!this._vectorTransition) {
  85440. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85441. }
  85442. this._betaIsAnimating = true;
  85443. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85444. if (animatable) {
  85445. this._animatables.push(animatable);
  85446. }
  85447. // sets the radius and lower radius bounds
  85448. // Small delta ensures camera is not always at lower zoom limit.
  85449. var radius = 0;
  85450. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85451. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85452. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85453. radius = position;
  85454. }
  85455. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85456. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85457. if (this._attachedCamera.lowerRadiusLimit === null) {
  85458. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85459. }
  85460. }
  85461. // Set sensibilities
  85462. var extend = maximumWorld.subtract(minimumWorld).length();
  85463. this._attachedCamera.panningSensibility = 5000 / extend;
  85464. this._attachedCamera.wheelPrecision = 100 / radius;
  85465. // transition to new radius
  85466. if (!this._radiusTransition) {
  85467. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85468. }
  85469. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85470. if (onAnimationEnd) {
  85471. onAnimationEnd();
  85472. }
  85473. if (_this._attachedCamera) {
  85474. _this._attachedCamera.storeState();
  85475. }
  85476. });
  85477. if (animatable) {
  85478. this._animatables.push(animatable);
  85479. }
  85480. };
  85481. /**
  85482. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85483. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85484. * frustum width.
  85485. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85486. * to fully enclose the mesh in the viewing frustum.
  85487. */
  85488. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85489. var size = maximumWorld.subtract(minimumWorld);
  85490. var boxVectorGlobalDiagonal = size.length();
  85491. var frustumSlope = this._getFrustumSlope();
  85492. // Formula for setting distance
  85493. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85494. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85495. // Horizon distance
  85496. var radius = radiusWithoutFraming * this._radiusScale;
  85497. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85498. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85499. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85500. var camera = this._attachedCamera;
  85501. if (!camera) {
  85502. return 0;
  85503. }
  85504. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85505. // Don't exceed the requested limit
  85506. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85507. }
  85508. // Don't exceed the upper radius limit
  85509. if (camera.upperRadiusLimit) {
  85510. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85511. }
  85512. return distance;
  85513. };
  85514. /**
  85515. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85516. * is automatically returned to its default position (expected to be above ground plane).
  85517. */
  85518. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85519. var _this = this;
  85520. if (this._elevationReturnTime < 0) {
  85521. return;
  85522. }
  85523. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85524. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85525. var limitBeta = Math.PI * 0.5;
  85526. // Bring the camera back up if below the ground plane
  85527. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85528. this._betaIsAnimating = true;
  85529. //Transition to new position
  85530. this.stopAllAnimations();
  85531. if (!this._betaTransition) {
  85532. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85533. }
  85534. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  85535. _this._clearAnimationLocks();
  85536. _this.stopAllAnimations();
  85537. });
  85538. if (animatabe) {
  85539. this._animatables.push(animatabe);
  85540. }
  85541. }
  85542. };
  85543. /**
  85544. * Returns the frustum slope based on the canvas ratio and camera FOV
  85545. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  85546. */
  85547. FramingBehavior.prototype._getFrustumSlope = function () {
  85548. // Calculate the viewport ratio
  85549. // Aspect Ratio is Height/Width.
  85550. var camera = this._attachedCamera;
  85551. if (!camera) {
  85552. return BABYLON.Vector2.Zero();
  85553. }
  85554. var engine = camera.getScene().getEngine();
  85555. var aspectRatio = engine.getAspectRatio(camera);
  85556. // Camera FOV is the vertical field of view (top-bottom) in radians.
  85557. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  85558. var frustumSlopeY = Math.tan(camera.fov / 2);
  85559. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  85560. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  85561. // along the forward vector.
  85562. var frustumSlopeX = frustumSlopeY * aspectRatio;
  85563. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  85564. };
  85565. /**
  85566. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  85567. */
  85568. FramingBehavior.prototype._clearAnimationLocks = function () {
  85569. this._betaIsAnimating = false;
  85570. };
  85571. /**
  85572. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85573. */
  85574. FramingBehavior.prototype._applyUserInteraction = function () {
  85575. if (this.isUserIsMoving) {
  85576. this._lastInteractionTime = BABYLON.Tools.Now;
  85577. this.stopAllAnimations();
  85578. this._clearAnimationLocks();
  85579. }
  85580. };
  85581. /**
  85582. * Stops and removes all animations that have been applied to the camera
  85583. */
  85584. FramingBehavior.prototype.stopAllAnimations = function () {
  85585. if (this._attachedCamera) {
  85586. this._attachedCamera.animations = [];
  85587. }
  85588. while (this._animatables.length) {
  85589. if (this._animatables[0]) {
  85590. this._animatables[0].onAnimationEnd = null;
  85591. this._animatables[0].stop();
  85592. }
  85593. this._animatables.shift();
  85594. }
  85595. };
  85596. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  85597. /**
  85598. * Gets a value indicating if the user is moving the camera
  85599. */
  85600. get: function () {
  85601. if (!this._attachedCamera) {
  85602. return false;
  85603. }
  85604. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85605. this._attachedCamera.inertialBetaOffset !== 0 ||
  85606. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85607. this._attachedCamera.inertialPanningX !== 0 ||
  85608. this._attachedCamera.inertialPanningY !== 0 ||
  85609. this._isPointerDown;
  85610. },
  85611. enumerable: true,
  85612. configurable: true
  85613. });
  85614. /**
  85615. * The easing function used by animations
  85616. */
  85617. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  85618. /**
  85619. * The easing mode used by animations
  85620. */
  85621. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  85622. // Statics
  85623. /**
  85624. * The camera can move all the way towards the mesh.
  85625. */
  85626. FramingBehavior.IgnoreBoundsSizeMode = 0;
  85627. /**
  85628. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  85629. */
  85630. FramingBehavior.FitFrustumSidesMode = 1;
  85631. return FramingBehavior;
  85632. }());
  85633. BABYLON.FramingBehavior = FramingBehavior;
  85634. })(BABYLON || (BABYLON = {}));
  85635. //# sourceMappingURL=babylon.framingBehavior.js.map
  85636. var BABYLON;
  85637. (function (BABYLON) {
  85638. /**
  85639. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  85640. */
  85641. var BouncingBehavior = /** @class */ (function () {
  85642. function BouncingBehavior() {
  85643. /**
  85644. * The duration of the animation, in milliseconds
  85645. */
  85646. this.transitionDuration = 450;
  85647. /**
  85648. * Length of the distance animated by the transition when lower radius is reached
  85649. */
  85650. this.lowerRadiusTransitionRange = 2;
  85651. /**
  85652. * Length of the distance animated by the transition when upper radius is reached
  85653. */
  85654. this.upperRadiusTransitionRange = -2;
  85655. this._autoTransitionRange = false;
  85656. // Animations
  85657. this._radiusIsAnimating = false;
  85658. this._radiusBounceTransition = null;
  85659. this._animatables = new Array();
  85660. }
  85661. Object.defineProperty(BouncingBehavior.prototype, "name", {
  85662. get: function () {
  85663. return "Bouncing";
  85664. },
  85665. enumerable: true,
  85666. configurable: true
  85667. });
  85668. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  85669. /**
  85670. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85671. */
  85672. get: function () {
  85673. return this._autoTransitionRange;
  85674. },
  85675. /**
  85676. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  85677. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  85678. */
  85679. set: function (value) {
  85680. var _this = this;
  85681. if (this._autoTransitionRange === value) {
  85682. return;
  85683. }
  85684. this._autoTransitionRange = value;
  85685. var camera = this._attachedCamera;
  85686. if (!camera) {
  85687. return;
  85688. }
  85689. if (value) {
  85690. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85691. if (!mesh) {
  85692. return;
  85693. }
  85694. mesh.computeWorldMatrix(true);
  85695. var diagonal = mesh.getBoundingInfo().diagonalLength;
  85696. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  85697. _this.upperRadiusTransitionRange = diagonal * 0.05;
  85698. });
  85699. }
  85700. else if (this._onMeshTargetChangedObserver) {
  85701. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85702. }
  85703. },
  85704. enumerable: true,
  85705. configurable: true
  85706. });
  85707. BouncingBehavior.prototype.init = function () {
  85708. // Do notihng
  85709. };
  85710. BouncingBehavior.prototype.attach = function (camera) {
  85711. var _this = this;
  85712. this._attachedCamera = camera;
  85713. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85714. if (!_this._attachedCamera) {
  85715. return;
  85716. }
  85717. // Add the bounce animation to the lower radius limit
  85718. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  85719. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  85720. }
  85721. // Add the bounce animation to the upper radius limit
  85722. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  85723. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  85724. }
  85725. });
  85726. };
  85727. BouncingBehavior.prototype.detach = function () {
  85728. if (!this._attachedCamera) {
  85729. return;
  85730. }
  85731. if (this._onAfterCheckInputsObserver) {
  85732. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85733. }
  85734. if (this._onMeshTargetChangedObserver) {
  85735. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85736. }
  85737. this._attachedCamera = null;
  85738. };
  85739. /**
  85740. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  85741. * @param radiusLimit The limit to check against.
  85742. * @return Bool to indicate if at limit.
  85743. */
  85744. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  85745. if (!this._attachedCamera) {
  85746. return false;
  85747. }
  85748. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  85749. return true;
  85750. }
  85751. return false;
  85752. };
  85753. /**
  85754. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  85755. * @param radiusDelta The delta by which to animate to. Can be negative.
  85756. */
  85757. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  85758. var _this = this;
  85759. if (!this._attachedCamera) {
  85760. return;
  85761. }
  85762. if (!this._radiusBounceTransition) {
  85763. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  85764. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  85765. }
  85766. // Prevent zoom until bounce has completed
  85767. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  85768. this._attachedCamera.wheelPrecision = Infinity;
  85769. this._attachedCamera.inertialRadiusOffset = 0;
  85770. // Animate to the radius limit
  85771. this.stopAllAnimations();
  85772. this._radiusIsAnimating = true;
  85773. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  85774. if (animatable) {
  85775. this._animatables.push(animatable);
  85776. }
  85777. };
  85778. /**
  85779. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  85780. */
  85781. BouncingBehavior.prototype._clearAnimationLocks = function () {
  85782. this._radiusIsAnimating = false;
  85783. if (this._attachedCamera) {
  85784. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  85785. }
  85786. };
  85787. /**
  85788. * Stops and removes all animations that have been applied to the camera
  85789. */
  85790. BouncingBehavior.prototype.stopAllAnimations = function () {
  85791. if (this._attachedCamera) {
  85792. this._attachedCamera.animations = [];
  85793. }
  85794. while (this._animatables.length) {
  85795. this._animatables[0].onAnimationEnd = null;
  85796. this._animatables[0].stop();
  85797. this._animatables.shift();
  85798. }
  85799. };
  85800. /**
  85801. * The easing function used by animations
  85802. */
  85803. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  85804. /**
  85805. * The easing mode used by animations
  85806. */
  85807. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  85808. return BouncingBehavior;
  85809. }());
  85810. BABYLON.BouncingBehavior = BouncingBehavior;
  85811. })(BABYLON || (BABYLON = {}));
  85812. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  85813. var BABYLON;
  85814. (function (BABYLON) {
  85815. var AutoRotationBehavior = /** @class */ (function () {
  85816. function AutoRotationBehavior() {
  85817. this._zoomStopsAnimation = false;
  85818. this._idleRotationSpeed = 0.05;
  85819. this._idleRotationWaitTime = 2000;
  85820. this._idleRotationSpinupTime = 2000;
  85821. this._isPointerDown = false;
  85822. this._lastFrameTime = null;
  85823. this._lastInteractionTime = -Infinity;
  85824. this._cameraRotationSpeed = 0;
  85825. this._lastFrameRadius = 0;
  85826. }
  85827. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  85828. get: function () {
  85829. return "AutoRotation";
  85830. },
  85831. enumerable: true,
  85832. configurable: true
  85833. });
  85834. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  85835. /**
  85836. * Gets the flag that indicates if user zooming should stop animation.
  85837. */
  85838. get: function () {
  85839. return this._zoomStopsAnimation;
  85840. },
  85841. /**
  85842. * Sets the flag that indicates if user zooming should stop animation.
  85843. */
  85844. set: function (flag) {
  85845. this._zoomStopsAnimation = flag;
  85846. },
  85847. enumerable: true,
  85848. configurable: true
  85849. });
  85850. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  85851. /**
  85852. * Gets the default speed at which the camera rotates around the model.
  85853. */
  85854. get: function () {
  85855. return this._idleRotationSpeed;
  85856. },
  85857. /**
  85858. * Sets the default speed at which the camera rotates around the model.
  85859. */
  85860. set: function (speed) {
  85861. this._idleRotationSpeed = speed;
  85862. },
  85863. enumerable: true,
  85864. configurable: true
  85865. });
  85866. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  85867. /**
  85868. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  85869. */
  85870. get: function () {
  85871. return this._idleRotationWaitTime;
  85872. },
  85873. /**
  85874. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  85875. */
  85876. set: function (time) {
  85877. this._idleRotationWaitTime = time;
  85878. },
  85879. enumerable: true,
  85880. configurable: true
  85881. });
  85882. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  85883. /**
  85884. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85885. */
  85886. get: function () {
  85887. return this._idleRotationSpinupTime;
  85888. },
  85889. /**
  85890. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  85891. */
  85892. set: function (time) {
  85893. this._idleRotationSpinupTime = time;
  85894. },
  85895. enumerable: true,
  85896. configurable: true
  85897. });
  85898. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  85899. /**
  85900. * Gets a value indicating if the camera is currently rotating because of this behavior
  85901. */
  85902. get: function () {
  85903. return Math.abs(this._cameraRotationSpeed) > 0;
  85904. },
  85905. enumerable: true,
  85906. configurable: true
  85907. });
  85908. AutoRotationBehavior.prototype.init = function () {
  85909. // Do notihng
  85910. };
  85911. AutoRotationBehavior.prototype.attach = function (camera) {
  85912. var _this = this;
  85913. this._attachedCamera = camera;
  85914. var scene = this._attachedCamera.getScene();
  85915. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85916. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85917. _this._isPointerDown = true;
  85918. return;
  85919. }
  85920. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85921. _this._isPointerDown = false;
  85922. }
  85923. });
  85924. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85925. var now = BABYLON.Tools.Now;
  85926. var dt = 0;
  85927. if (_this._lastFrameTime != null) {
  85928. dt = now - _this._lastFrameTime;
  85929. }
  85930. _this._lastFrameTime = now;
  85931. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85932. _this._applyUserInteraction();
  85933. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  85934. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  85935. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  85936. // Step camera rotation by rotation speed
  85937. if (_this._attachedCamera) {
  85938. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  85939. }
  85940. });
  85941. };
  85942. AutoRotationBehavior.prototype.detach = function () {
  85943. if (!this._attachedCamera) {
  85944. return;
  85945. }
  85946. var scene = this._attachedCamera.getScene();
  85947. if (this._onPrePointerObservableObserver) {
  85948. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85949. }
  85950. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85951. this._attachedCamera = null;
  85952. };
  85953. /**
  85954. * Returns true if user is scrolling.
  85955. * @return true if user is scrolling.
  85956. */
  85957. AutoRotationBehavior.prototype._userIsZooming = function () {
  85958. if (!this._attachedCamera) {
  85959. return false;
  85960. }
  85961. return this._attachedCamera.inertialRadiusOffset !== 0;
  85962. };
  85963. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  85964. if (!this._attachedCamera) {
  85965. return false;
  85966. }
  85967. var zoomHasHitLimit = false;
  85968. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  85969. zoomHasHitLimit = true;
  85970. }
  85971. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  85972. this._lastFrameRadius = this._attachedCamera.radius;
  85973. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  85974. };
  85975. /**
  85976. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  85977. */
  85978. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  85979. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  85980. this._lastInteractionTime = BABYLON.Tools.Now;
  85981. }
  85982. };
  85983. // Tools
  85984. AutoRotationBehavior.prototype._userIsMoving = function () {
  85985. if (!this._attachedCamera) {
  85986. return false;
  85987. }
  85988. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  85989. this._attachedCamera.inertialBetaOffset !== 0 ||
  85990. this._attachedCamera.inertialRadiusOffset !== 0 ||
  85991. this._attachedCamera.inertialPanningX !== 0 ||
  85992. this._attachedCamera.inertialPanningY !== 0 ||
  85993. this._isPointerDown;
  85994. };
  85995. return AutoRotationBehavior;
  85996. }());
  85997. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  85998. })(BABYLON || (BABYLON = {}));
  85999. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  86000. var BABYLON;
  86001. (function (BABYLON) {
  86002. /**
  86003. * This class can be used to get instrumentation data from a Babylon engine
  86004. */
  86005. var EngineInstrumentation = /** @class */ (function () {
  86006. function EngineInstrumentation(engine) {
  86007. this.engine = engine;
  86008. this._captureGPUFrameTime = false;
  86009. this._gpuFrameTime = new BABYLON.PerfCounter();
  86010. this._captureShaderCompilationTime = false;
  86011. this._shaderCompilationTime = new BABYLON.PerfCounter();
  86012. // Observers
  86013. this._onBeginFrameObserver = null;
  86014. this._onEndFrameObserver = null;
  86015. this._onBeforeShaderCompilationObserver = null;
  86016. this._onAfterShaderCompilationObserver = null;
  86017. }
  86018. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  86019. // Properties
  86020. /**
  86021. * Gets the perf counter used for GPU frame time
  86022. */
  86023. get: function () {
  86024. return this._gpuFrameTime;
  86025. },
  86026. enumerable: true,
  86027. configurable: true
  86028. });
  86029. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  86030. /**
  86031. * Gets the GPU frame time capture status
  86032. */
  86033. get: function () {
  86034. return this._captureGPUFrameTime;
  86035. },
  86036. /**
  86037. * Enable or disable the GPU frame time capture
  86038. */
  86039. set: function (value) {
  86040. var _this = this;
  86041. if (value === this._captureGPUFrameTime) {
  86042. return;
  86043. }
  86044. this._captureGPUFrameTime = value;
  86045. if (value) {
  86046. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  86047. if (!_this._gpuFrameTimeToken) {
  86048. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  86049. }
  86050. });
  86051. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  86052. if (!_this._gpuFrameTimeToken) {
  86053. return;
  86054. }
  86055. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  86056. if (time > -1) {
  86057. _this._gpuFrameTimeToken = null;
  86058. _this._gpuFrameTime.fetchNewFrame();
  86059. _this._gpuFrameTime.addCount(time, true);
  86060. }
  86061. });
  86062. }
  86063. else {
  86064. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86065. this._onBeginFrameObserver = null;
  86066. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86067. this._onEndFrameObserver = null;
  86068. }
  86069. },
  86070. enumerable: true,
  86071. configurable: true
  86072. });
  86073. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  86074. /**
  86075. * Gets the perf counter used for shader compilation time
  86076. */
  86077. get: function () {
  86078. return this._shaderCompilationTime;
  86079. },
  86080. enumerable: true,
  86081. configurable: true
  86082. });
  86083. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  86084. /**
  86085. * Gets the shader compilation time capture status
  86086. */
  86087. get: function () {
  86088. return this._captureShaderCompilationTime;
  86089. },
  86090. /**
  86091. * Enable or disable the shader compilation time capture
  86092. */
  86093. set: function (value) {
  86094. var _this = this;
  86095. if (value === this._captureShaderCompilationTime) {
  86096. return;
  86097. }
  86098. this._captureShaderCompilationTime = value;
  86099. if (value) {
  86100. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  86101. _this._shaderCompilationTime.fetchNewFrame();
  86102. _this._shaderCompilationTime.beginMonitoring();
  86103. });
  86104. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  86105. _this._shaderCompilationTime.endMonitoring();
  86106. });
  86107. }
  86108. else {
  86109. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86110. this._onBeforeShaderCompilationObserver = null;
  86111. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86112. this._onAfterShaderCompilationObserver = null;
  86113. }
  86114. },
  86115. enumerable: true,
  86116. configurable: true
  86117. });
  86118. EngineInstrumentation.prototype.dispose = function () {
  86119. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86120. this._onBeginFrameObserver = null;
  86121. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86122. this._onEndFrameObserver = null;
  86123. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86124. this._onBeforeShaderCompilationObserver = null;
  86125. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86126. this._onAfterShaderCompilationObserver = null;
  86127. this.engine = null;
  86128. };
  86129. return EngineInstrumentation;
  86130. }());
  86131. BABYLON.EngineInstrumentation = EngineInstrumentation;
  86132. })(BABYLON || (BABYLON = {}));
  86133. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  86134. var BABYLON;
  86135. (function (BABYLON) {
  86136. /**
  86137. * This class can be used to get instrumentation data from a Babylon engine
  86138. */
  86139. var SceneInstrumentation = /** @class */ (function () {
  86140. function SceneInstrumentation(scene) {
  86141. var _this = this;
  86142. this.scene = scene;
  86143. this._captureActiveMeshesEvaluationTime = false;
  86144. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  86145. this._captureRenderTargetsRenderTime = false;
  86146. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  86147. this._captureFrameTime = false;
  86148. this._frameTime = new BABYLON.PerfCounter();
  86149. this._captureRenderTime = false;
  86150. this._renderTime = new BABYLON.PerfCounter();
  86151. this._captureInterFrameTime = false;
  86152. this._interFrameTime = new BABYLON.PerfCounter();
  86153. this._captureParticlesRenderTime = false;
  86154. this._particlesRenderTime = new BABYLON.PerfCounter();
  86155. this._captureSpritesRenderTime = false;
  86156. this._spritesRenderTime = new BABYLON.PerfCounter();
  86157. this._capturePhysicsTime = false;
  86158. this._physicsTime = new BABYLON.PerfCounter();
  86159. this._captureAnimationsTime = false;
  86160. this._animationsTime = new BABYLON.PerfCounter();
  86161. // Observers
  86162. this._onBeforeActiveMeshesEvaluationObserver = null;
  86163. this._onAfterActiveMeshesEvaluationObserver = null;
  86164. this._onBeforeRenderTargetsRenderObserver = null;
  86165. this._onAfterRenderTargetsRenderObserver = null;
  86166. this._onAfterRenderObserver = null;
  86167. this._onBeforeDrawPhaseObserver = null;
  86168. this._onAfterDrawPhaseObserver = null;
  86169. this._onBeforeAnimationsObserver = null;
  86170. this._onBeforeParticlesRenderingObserver = null;
  86171. this._onAfterParticlesRenderingObserver = null;
  86172. this._onBeforeSpritesRenderingObserver = null;
  86173. this._onAfterSpritesRenderingObserver = null;
  86174. this._onBeforePhysicsObserver = null;
  86175. this._onAfterPhysicsObserver = null;
  86176. this._onAfterAnimationsObserver = null;
  86177. // Before render
  86178. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  86179. if (_this._captureActiveMeshesEvaluationTime) {
  86180. _this._activeMeshesEvaluationTime.fetchNewFrame();
  86181. }
  86182. if (_this._captureRenderTargetsRenderTime) {
  86183. _this._renderTargetsRenderTime.fetchNewFrame();
  86184. }
  86185. if (_this._captureFrameTime) {
  86186. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  86187. _this._frameTime.beginMonitoring();
  86188. }
  86189. if (_this._captureInterFrameTime) {
  86190. _this._interFrameTime.endMonitoring();
  86191. }
  86192. if (_this._captureParticlesRenderTime) {
  86193. _this._particlesRenderTime.fetchNewFrame();
  86194. }
  86195. if (_this._captureSpritesRenderTime) {
  86196. _this._spritesRenderTime.fetchNewFrame();
  86197. }
  86198. if (_this._captureAnimationsTime) {
  86199. _this._animationsTime.beginMonitoring();
  86200. }
  86201. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  86202. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  86203. });
  86204. // After render
  86205. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  86206. if (_this._captureFrameTime) {
  86207. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  86208. _this._frameTime.endMonitoring();
  86209. }
  86210. if (_this._captureRenderTime) {
  86211. _this._renderTime.endMonitoring(false);
  86212. }
  86213. if (_this._captureInterFrameTime) {
  86214. _this._interFrameTime.beginMonitoring();
  86215. }
  86216. });
  86217. }
  86218. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  86219. // Properties
  86220. /**
  86221. * Gets the perf counter used for active meshes evaluation time
  86222. */
  86223. get: function () {
  86224. return this._activeMeshesEvaluationTime;
  86225. },
  86226. enumerable: true,
  86227. configurable: true
  86228. });
  86229. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  86230. /**
  86231. * Gets the active meshes evaluation time capture status
  86232. */
  86233. get: function () {
  86234. return this._captureActiveMeshesEvaluationTime;
  86235. },
  86236. /**
  86237. * Enable or disable the active meshes evaluation time capture
  86238. */
  86239. set: function (value) {
  86240. var _this = this;
  86241. if (value === this._captureActiveMeshesEvaluationTime) {
  86242. return;
  86243. }
  86244. this._captureActiveMeshesEvaluationTime = value;
  86245. if (value) {
  86246. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  86247. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  86248. _this._activeMeshesEvaluationTime.beginMonitoring();
  86249. });
  86250. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  86251. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  86252. _this._activeMeshesEvaluationTime.endMonitoring();
  86253. });
  86254. }
  86255. else {
  86256. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86257. this._onBeforeActiveMeshesEvaluationObserver = null;
  86258. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86259. this._onAfterActiveMeshesEvaluationObserver = null;
  86260. }
  86261. },
  86262. enumerable: true,
  86263. configurable: true
  86264. });
  86265. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  86266. /**
  86267. * Gets the perf counter used for render targets render time
  86268. */
  86269. get: function () {
  86270. return this._renderTargetsRenderTime;
  86271. },
  86272. enumerable: true,
  86273. configurable: true
  86274. });
  86275. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  86276. /**
  86277. * Gets the render targets render time capture status
  86278. */
  86279. get: function () {
  86280. return this._captureRenderTargetsRenderTime;
  86281. },
  86282. /**
  86283. * Enable or disable the render targets render time capture
  86284. */
  86285. set: function (value) {
  86286. var _this = this;
  86287. if (value === this._captureRenderTargetsRenderTime) {
  86288. return;
  86289. }
  86290. this._captureRenderTargetsRenderTime = value;
  86291. if (value) {
  86292. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  86293. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  86294. _this._renderTargetsRenderTime.beginMonitoring();
  86295. });
  86296. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  86297. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  86298. _this._renderTargetsRenderTime.endMonitoring(false);
  86299. });
  86300. }
  86301. else {
  86302. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86303. this._onBeforeRenderTargetsRenderObserver = null;
  86304. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86305. this._onAfterRenderTargetsRenderObserver = null;
  86306. }
  86307. },
  86308. enumerable: true,
  86309. configurable: true
  86310. });
  86311. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  86312. /**
  86313. * Gets the perf counter used for particles render time
  86314. */
  86315. get: function () {
  86316. return this._particlesRenderTime;
  86317. },
  86318. enumerable: true,
  86319. configurable: true
  86320. });
  86321. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  86322. /**
  86323. * Gets the particles render time capture status
  86324. */
  86325. get: function () {
  86326. return this._captureParticlesRenderTime;
  86327. },
  86328. /**
  86329. * Enable or disable the particles render time capture
  86330. */
  86331. set: function (value) {
  86332. var _this = this;
  86333. if (value === this._captureParticlesRenderTime) {
  86334. return;
  86335. }
  86336. this._captureParticlesRenderTime = value;
  86337. if (value) {
  86338. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  86339. BABYLON.Tools.StartPerformanceCounter("Particles");
  86340. _this._particlesRenderTime.beginMonitoring();
  86341. });
  86342. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  86343. BABYLON.Tools.EndPerformanceCounter("Particles");
  86344. _this._particlesRenderTime.endMonitoring(false);
  86345. });
  86346. }
  86347. else {
  86348. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86349. this._onBeforeParticlesRenderingObserver = null;
  86350. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86351. this._onAfterParticlesRenderingObserver = null;
  86352. }
  86353. },
  86354. enumerable: true,
  86355. configurable: true
  86356. });
  86357. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  86358. /**
  86359. * Gets the perf counter used for sprites render time
  86360. */
  86361. get: function () {
  86362. return this._spritesRenderTime;
  86363. },
  86364. enumerable: true,
  86365. configurable: true
  86366. });
  86367. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  86368. /**
  86369. * Gets the sprites render time capture status
  86370. */
  86371. get: function () {
  86372. return this._captureSpritesRenderTime;
  86373. },
  86374. /**
  86375. * Enable or disable the sprites render time capture
  86376. */
  86377. set: function (value) {
  86378. var _this = this;
  86379. if (value === this._captureSpritesRenderTime) {
  86380. return;
  86381. }
  86382. this._captureSpritesRenderTime = value;
  86383. if (value) {
  86384. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  86385. BABYLON.Tools.StartPerformanceCounter("Sprites");
  86386. _this._spritesRenderTime.beginMonitoring();
  86387. });
  86388. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  86389. BABYLON.Tools.EndPerformanceCounter("Sprites");
  86390. _this._spritesRenderTime.endMonitoring(false);
  86391. });
  86392. }
  86393. else {
  86394. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86395. this._onBeforeSpritesRenderingObserver = null;
  86396. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86397. this._onAfterSpritesRenderingObserver = null;
  86398. }
  86399. },
  86400. enumerable: true,
  86401. configurable: true
  86402. });
  86403. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  86404. /**
  86405. * Gets the perf counter used for physics time
  86406. */
  86407. get: function () {
  86408. return this._physicsTime;
  86409. },
  86410. enumerable: true,
  86411. configurable: true
  86412. });
  86413. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  86414. /**
  86415. * Gets the physics time capture status
  86416. */
  86417. get: function () {
  86418. return this._capturePhysicsTime;
  86419. },
  86420. /**
  86421. * Enable or disable the physics time capture
  86422. */
  86423. set: function (value) {
  86424. var _this = this;
  86425. if (value === this._capturePhysicsTime) {
  86426. return;
  86427. }
  86428. this._capturePhysicsTime = value;
  86429. if (value) {
  86430. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  86431. BABYLON.Tools.StartPerformanceCounter("Physics");
  86432. _this._physicsTime.beginMonitoring();
  86433. });
  86434. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  86435. BABYLON.Tools.EndPerformanceCounter("Physics");
  86436. _this._physicsTime.endMonitoring();
  86437. });
  86438. }
  86439. else {
  86440. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86441. this._onBeforePhysicsObserver = null;
  86442. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86443. this._onAfterPhysicsObserver = null;
  86444. }
  86445. },
  86446. enumerable: true,
  86447. configurable: true
  86448. });
  86449. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  86450. /**
  86451. * Gets the perf counter used for animations time
  86452. */
  86453. get: function () {
  86454. return this._animationsTime;
  86455. },
  86456. enumerable: true,
  86457. configurable: true
  86458. });
  86459. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  86460. /**
  86461. * Gets the animations time capture status
  86462. */
  86463. get: function () {
  86464. return this._captureAnimationsTime;
  86465. },
  86466. /**
  86467. * Enable or disable the animations time capture
  86468. */
  86469. set: function (value) {
  86470. var _this = this;
  86471. if (value === this._captureAnimationsTime) {
  86472. return;
  86473. }
  86474. this._captureAnimationsTime = value;
  86475. if (value) {
  86476. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  86477. _this._animationsTime.endMonitoring();
  86478. });
  86479. }
  86480. else {
  86481. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86482. this._onAfterAnimationsObserver = null;
  86483. }
  86484. },
  86485. enumerable: true,
  86486. configurable: true
  86487. });
  86488. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  86489. /**
  86490. * Gets the perf counter used for frame time capture
  86491. */
  86492. get: function () {
  86493. return this._frameTime;
  86494. },
  86495. enumerable: true,
  86496. configurable: true
  86497. });
  86498. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  86499. /**
  86500. * Gets the frame time capture status
  86501. */
  86502. get: function () {
  86503. return this._captureFrameTime;
  86504. },
  86505. /**
  86506. * Enable or disable the frame time capture
  86507. */
  86508. set: function (value) {
  86509. this._captureFrameTime = value;
  86510. },
  86511. enumerable: true,
  86512. configurable: true
  86513. });
  86514. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  86515. /**
  86516. * Gets the perf counter used for inter-frames time capture
  86517. */
  86518. get: function () {
  86519. return this._interFrameTime;
  86520. },
  86521. enumerable: true,
  86522. configurable: true
  86523. });
  86524. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  86525. /**
  86526. * Gets the inter-frames time capture status
  86527. */
  86528. get: function () {
  86529. return this._captureInterFrameTime;
  86530. },
  86531. /**
  86532. * Enable or disable the inter-frames time capture
  86533. */
  86534. set: function (value) {
  86535. this._captureInterFrameTime = value;
  86536. },
  86537. enumerable: true,
  86538. configurable: true
  86539. });
  86540. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  86541. /**
  86542. * Gets the perf counter used for render time capture
  86543. */
  86544. get: function () {
  86545. return this._renderTime;
  86546. },
  86547. enumerable: true,
  86548. configurable: true
  86549. });
  86550. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  86551. /**
  86552. * Gets the render time capture status
  86553. */
  86554. get: function () {
  86555. return this._captureRenderTime;
  86556. },
  86557. /**
  86558. * Enable or disable the render time capture
  86559. */
  86560. set: function (value) {
  86561. var _this = this;
  86562. if (value === this._captureRenderTime) {
  86563. return;
  86564. }
  86565. this._captureRenderTime = value;
  86566. if (value) {
  86567. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  86568. _this._renderTime.beginMonitoring();
  86569. BABYLON.Tools.StartPerformanceCounter("Main render");
  86570. });
  86571. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  86572. _this._renderTime.endMonitoring(false);
  86573. BABYLON.Tools.EndPerformanceCounter("Main render");
  86574. });
  86575. }
  86576. else {
  86577. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86578. this._onBeforeDrawPhaseObserver = null;
  86579. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86580. this._onAfterDrawPhaseObserver = null;
  86581. }
  86582. },
  86583. enumerable: true,
  86584. configurable: true
  86585. });
  86586. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  86587. /**
  86588. * Gets the perf counter used for draw calls
  86589. */
  86590. get: function () {
  86591. return this.scene.getEngine()._drawCalls;
  86592. },
  86593. enumerable: true,
  86594. configurable: true
  86595. });
  86596. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  86597. /**
  86598. * Gets the perf counter used for texture collisions
  86599. */
  86600. get: function () {
  86601. return this.scene.getEngine()._textureCollisions;
  86602. },
  86603. enumerable: true,
  86604. configurable: true
  86605. });
  86606. SceneInstrumentation.prototype.dispose = function () {
  86607. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86608. this._onAfterRenderObserver = null;
  86609. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  86610. this._onBeforeActiveMeshesEvaluationObserver = null;
  86611. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  86612. this._onAfterActiveMeshesEvaluationObserver = null;
  86613. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  86614. this._onBeforeRenderTargetsRenderObserver = null;
  86615. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  86616. this._onAfterRenderTargetsRenderObserver = null;
  86617. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  86618. this._onBeforeAnimationsObserver = null;
  86619. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  86620. this._onBeforeParticlesRenderingObserver = null;
  86621. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  86622. this._onAfterParticlesRenderingObserver = null;
  86623. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  86624. this._onBeforeSpritesRenderingObserver = null;
  86625. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  86626. this._onAfterSpritesRenderingObserver = null;
  86627. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  86628. this._onBeforeDrawPhaseObserver = null;
  86629. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  86630. this._onAfterDrawPhaseObserver = null;
  86631. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  86632. this._onBeforePhysicsObserver = null;
  86633. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  86634. this._onAfterPhysicsObserver = null;
  86635. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  86636. this._onAfterAnimationsObserver = null;
  86637. this.scene = null;
  86638. };
  86639. return SceneInstrumentation;
  86640. }());
  86641. BABYLON.SceneInstrumentation = SceneInstrumentation;
  86642. })(BABYLON || (BABYLON = {}));
  86643. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  86644. var BABYLON;
  86645. (function (BABYLON) {
  86646. var _TimeToken = /** @class */ (function () {
  86647. function _TimeToken() {
  86648. this._timeElapsedQueryEnded = false;
  86649. }
  86650. return _TimeToken;
  86651. }());
  86652. BABYLON._TimeToken = _TimeToken;
  86653. })(BABYLON || (BABYLON = {}));
  86654. //# sourceMappingURL=babylon.timeToken.js.map
  86655. var BABYLON;
  86656. (function (BABYLON) {
  86657. /**
  86658. * Background material defines definition.
  86659. * @ignore Mainly internal Use
  86660. */
  86661. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  86662. __extends(BackgroundMaterialDefines, _super);
  86663. /**
  86664. * Constructor of the defines.
  86665. */
  86666. function BackgroundMaterialDefines() {
  86667. var _this = _super.call(this) || this;
  86668. /**
  86669. * True if the diffuse texture is in use.
  86670. */
  86671. _this.DIFFUSE = false;
  86672. /**
  86673. * The direct UV channel to use.
  86674. */
  86675. _this.DIFFUSEDIRECTUV = 0;
  86676. /**
  86677. * True if the diffuse texture is in gamma space.
  86678. */
  86679. _this.GAMMADIFFUSE = false;
  86680. /**
  86681. * True if the diffuse texture has opacity in the alpha channel.
  86682. */
  86683. _this.DIFFUSEHASALPHA = false;
  86684. /**
  86685. * True if you want the material to fade to transparent at grazing angle.
  86686. */
  86687. _this.OPACITYFRESNEL = false;
  86688. /**
  86689. * True if an extra blur needs to be added in the reflection.
  86690. */
  86691. _this.REFLECTIONBLUR = false;
  86692. /**
  86693. * True if you want the material to fade to reflection at grazing angle.
  86694. */
  86695. _this.REFLECTIONFRESNEL = false;
  86696. /**
  86697. * True if you want the material to falloff as far as you move away from the scene center.
  86698. */
  86699. _this.REFLECTIONFALLOFF = false;
  86700. /**
  86701. * False if the current Webgl implementation does not support the texture lod extension.
  86702. */
  86703. _this.TEXTURELODSUPPORT = false;
  86704. /**
  86705. * True to ensure the data are premultiplied.
  86706. */
  86707. _this.PREMULTIPLYALPHA = false;
  86708. /**
  86709. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  86710. */
  86711. _this.USERGBCOLOR = false;
  86712. /**
  86713. * True to add noise in order to reduce the banding effect.
  86714. */
  86715. _this.NOISE = false;
  86716. // Image Processing Configuration.
  86717. _this.IMAGEPROCESSING = false;
  86718. _this.VIGNETTE = false;
  86719. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  86720. _this.VIGNETTEBLENDMODEOPAQUE = false;
  86721. _this.TONEMAPPING = false;
  86722. _this.CONTRAST = false;
  86723. _this.COLORCURVES = false;
  86724. _this.COLORGRADING = false;
  86725. _this.COLORGRADING3D = false;
  86726. _this.SAMPLER3DGREENDEPTH = false;
  86727. _this.SAMPLER3DBGRMAP = false;
  86728. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  86729. _this.EXPOSURE = false;
  86730. // Reflection.
  86731. _this.REFLECTION = false;
  86732. _this.REFLECTIONMAP_3D = false;
  86733. _this.REFLECTIONMAP_SPHERICAL = false;
  86734. _this.REFLECTIONMAP_PLANAR = false;
  86735. _this.REFLECTIONMAP_CUBIC = false;
  86736. _this.REFLECTIONMAP_PROJECTION = false;
  86737. _this.REFLECTIONMAP_SKYBOX = false;
  86738. _this.REFLECTIONMAP_EXPLICIT = false;
  86739. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  86740. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  86741. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  86742. _this.INVERTCUBICMAP = false;
  86743. _this.REFLECTIONMAP_OPPOSITEZ = false;
  86744. _this.LODINREFLECTIONALPHA = false;
  86745. _this.GAMMAREFLECTION = false;
  86746. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  86747. // Default BJS.
  86748. _this.MAINUV1 = false;
  86749. _this.MAINUV2 = false;
  86750. _this.UV1 = false;
  86751. _this.UV2 = false;
  86752. _this.CLIPPLANE = false;
  86753. _this.POINTSIZE = false;
  86754. _this.FOG = false;
  86755. _this.NORMAL = false;
  86756. _this.NUM_BONE_INFLUENCERS = 0;
  86757. _this.BonesPerMesh = 0;
  86758. _this.INSTANCES = false;
  86759. _this.SHADOWFLOAT = false;
  86760. _this.rebuild();
  86761. return _this;
  86762. }
  86763. return BackgroundMaterialDefines;
  86764. }(BABYLON.MaterialDefines));
  86765. /**
  86766. * Background material used to create an efficient environement around your scene.
  86767. */
  86768. var BackgroundMaterial = /** @class */ (function (_super) {
  86769. __extends(BackgroundMaterial, _super);
  86770. /**
  86771. * Instantiates a Background Material in the given scene
  86772. * @param name The friendly name of the material
  86773. * @param scene The scene to add the material to
  86774. */
  86775. function BackgroundMaterial(name, scene) {
  86776. var _this = _super.call(this, name, scene) || this;
  86777. /**
  86778. * Key light Color (multiply against the R channel of the environement texture)
  86779. */
  86780. _this.primaryColor = BABYLON.Color3.White();
  86781. /**
  86782. * Key light Level (allowing HDR output of the background)
  86783. */
  86784. _this.primaryLevel = 1;
  86785. /**
  86786. * Secondary light Color (multiply against the G channel of the environement texture)
  86787. */
  86788. _this.secondaryColor = BABYLON.Color3.Gray();
  86789. /**
  86790. * Secondary light Level (allowing HDR output of the background)
  86791. */
  86792. _this.secondaryLevel = 1;
  86793. /**
  86794. * Tertiary light Color (multiply against the B channel of the environement texture)
  86795. */
  86796. _this.tertiaryColor = BABYLON.Color3.Black();
  86797. /**
  86798. * Tertiary light Level (allowing HDR output of the background)
  86799. */
  86800. _this.tertiaryLevel = 1;
  86801. /**
  86802. * Reflection Texture used in the material.
  86803. * Should be author in a specific way for the best result (refer to the documentation).
  86804. */
  86805. _this.reflectionTexture = null;
  86806. /**
  86807. * Reflection Texture level of blur.
  86808. *
  86809. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  86810. * texture twice.
  86811. */
  86812. _this.reflectionBlur = 0;
  86813. /**
  86814. * Diffuse Texture used in the material.
  86815. * Should be author in a specific way for the best result (refer to the documentation).
  86816. */
  86817. _this.diffuseTexture = null;
  86818. _this._shadowLights = null;
  86819. /**
  86820. * Specify the list of lights casting shadow on the material.
  86821. * All scene shadow lights will be included if null.
  86822. */
  86823. _this.shadowLights = null;
  86824. /**
  86825. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  86826. * soft lighting on the background.
  86827. */
  86828. _this.shadowBlurScale = 1;
  86829. /**
  86830. * Helps adjusting the shadow to a softer level if required.
  86831. * 0 means black shadows and 1 means no shadows.
  86832. */
  86833. _this.shadowLevel = 0;
  86834. /**
  86835. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  86836. * It is usually zero but might be interesting to modify according to your setup.
  86837. */
  86838. _this.sceneCenter = BABYLON.Vector3.Zero();
  86839. /**
  86840. * This helps specifying that the material is falling off to the sky box at grazing angle.
  86841. * This helps ensuring a nice transition when the camera goes under the ground.
  86842. */
  86843. _this.opacityFresnel = true;
  86844. /**
  86845. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  86846. * This helps adding a mirror texture on the ground.
  86847. */
  86848. _this.reflectionFresnel = false;
  86849. /**
  86850. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  86851. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  86852. */
  86853. _this.reflectionFalloffDistance = 0.0;
  86854. /**
  86855. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  86856. */
  86857. _this.reflectionAmount = 1.0;
  86858. /**
  86859. * This specifies the weight of the reflection at grazing angle.
  86860. */
  86861. _this.reflectionReflectance0 = 0.05;
  86862. /**
  86863. * This specifies the weight of the reflection at a perpendicular point of view.
  86864. */
  86865. _this.reflectionReflectance90 = 0.5;
  86866. /**
  86867. * Helps to directly use the maps channels instead of their level.
  86868. */
  86869. _this.useRGBColor = true;
  86870. /**
  86871. * This helps reducing the banding effect that could occur on the background.
  86872. */
  86873. _this.enableNoise = false;
  86874. _this._fovMultiplier = 1.0;
  86875. /**
  86876. * Enable the FOV adjustment feature controlled by fovMultiplier.
  86877. * @type {boolean}
  86878. */
  86879. _this.useEquirectangularFOV = false;
  86880. _this._maxSimultaneousLights = 4;
  86881. /**
  86882. * Number of Simultaneous lights allowed on the material.
  86883. */
  86884. _this.maxSimultaneousLights = 4;
  86885. /**
  86886. * Keep track of the image processing observer to allow dispose and replace.
  86887. */
  86888. _this._imageProcessingObserver = null;
  86889. // Temp values kept as cache in the material.
  86890. _this._renderTargets = new BABYLON.SmartArray(16);
  86891. _this._reflectionControls = BABYLON.Vector4.Zero();
  86892. // Setup the default processing configuration to the scene.
  86893. _this._attachImageProcessingConfiguration(null);
  86894. _this.getRenderTargetTextures = function () {
  86895. _this._renderTargets.reset();
  86896. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  86897. _this._renderTargets.push(_this._diffuseTexture);
  86898. }
  86899. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  86900. _this._renderTargets.push(_this._reflectionTexture);
  86901. }
  86902. return _this._renderTargets;
  86903. };
  86904. return _this;
  86905. }
  86906. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  86907. /**
  86908. * Sets the reflection reflectance fresnel values according to the default standard
  86909. * empirically know to work well :-)
  86910. */
  86911. set: function (value) {
  86912. var reflectionWeight = value;
  86913. if (reflectionWeight < 0.5) {
  86914. reflectionWeight = reflectionWeight * 2.0;
  86915. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  86916. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  86917. }
  86918. else {
  86919. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  86920. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  86921. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  86922. }
  86923. },
  86924. enumerable: true,
  86925. configurable: true
  86926. });
  86927. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  86928. /**
  86929. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  86930. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  86931. * Recommended to be keep at 1.0 except for special cases.
  86932. */
  86933. get: function () {
  86934. return this._fovMultiplier;
  86935. },
  86936. set: function (value) {
  86937. if (isNaN(value)) {
  86938. value = 1.0;
  86939. }
  86940. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  86941. },
  86942. enumerable: true,
  86943. configurable: true
  86944. });
  86945. /**
  86946. * Attaches a new image processing configuration to the PBR Material.
  86947. * @param configuration (if null the scene configuration will be use)
  86948. */
  86949. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  86950. var _this = this;
  86951. if (configuration === this._imageProcessingConfiguration) {
  86952. return;
  86953. }
  86954. // Detaches observer.
  86955. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  86956. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  86957. }
  86958. // Pick the scene configuration if needed.
  86959. if (!configuration) {
  86960. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  86961. }
  86962. else {
  86963. this._imageProcessingConfiguration = configuration;
  86964. }
  86965. // Attaches observer.
  86966. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  86967. _this._markAllSubMeshesAsImageProcessingDirty();
  86968. });
  86969. };
  86970. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  86971. /**
  86972. * Gets the image processing configuration used either in this material.
  86973. */
  86974. get: function () {
  86975. return this._imageProcessingConfiguration;
  86976. },
  86977. /**
  86978. * Sets the Default image processing configuration used either in the this material.
  86979. *
  86980. * If sets to null, the scene one is in use.
  86981. */
  86982. set: function (value) {
  86983. this._attachImageProcessingConfiguration(value);
  86984. // Ensure the effect will be rebuilt.
  86985. this._markAllSubMeshesAsTexturesDirty();
  86986. },
  86987. enumerable: true,
  86988. configurable: true
  86989. });
  86990. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  86991. /**
  86992. * Gets wether the color curves effect is enabled.
  86993. */
  86994. get: function () {
  86995. return this.imageProcessingConfiguration.colorCurvesEnabled;
  86996. },
  86997. /**
  86998. * Sets wether the color curves effect is enabled.
  86999. */
  87000. set: function (value) {
  87001. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  87002. },
  87003. enumerable: true,
  87004. configurable: true
  87005. });
  87006. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  87007. /**
  87008. * Gets wether the color grading effect is enabled.
  87009. */
  87010. get: function () {
  87011. return this.imageProcessingConfiguration.colorGradingEnabled;
  87012. },
  87013. /**
  87014. * Gets wether the color grading effect is enabled.
  87015. */
  87016. set: function (value) {
  87017. this.imageProcessingConfiguration.colorGradingEnabled = value;
  87018. },
  87019. enumerable: true,
  87020. configurable: true
  87021. });
  87022. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  87023. /**
  87024. * Gets wether tonemapping is enabled or not.
  87025. */
  87026. get: function () {
  87027. return this._imageProcessingConfiguration.toneMappingEnabled;
  87028. },
  87029. /**
  87030. * Sets wether tonemapping is enabled or not
  87031. */
  87032. set: function (value) {
  87033. this._imageProcessingConfiguration.toneMappingEnabled = value;
  87034. },
  87035. enumerable: true,
  87036. configurable: true
  87037. });
  87038. ;
  87039. ;
  87040. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  87041. /**
  87042. * The camera exposure used on this material.
  87043. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87044. * This corresponds to a photographic exposure.
  87045. */
  87046. get: function () {
  87047. return this._imageProcessingConfiguration.exposure;
  87048. },
  87049. /**
  87050. * The camera exposure used on this material.
  87051. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87052. * This corresponds to a photographic exposure.
  87053. */
  87054. set: function (value) {
  87055. this._imageProcessingConfiguration.exposure = value;
  87056. },
  87057. enumerable: true,
  87058. configurable: true
  87059. });
  87060. ;
  87061. ;
  87062. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  87063. /**
  87064. * Gets The camera contrast used on this material.
  87065. */
  87066. get: function () {
  87067. return this._imageProcessingConfiguration.contrast;
  87068. },
  87069. /**
  87070. * Sets The camera contrast used on this material.
  87071. */
  87072. set: function (value) {
  87073. this._imageProcessingConfiguration.contrast = value;
  87074. },
  87075. enumerable: true,
  87076. configurable: true
  87077. });
  87078. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  87079. /**
  87080. * Gets the Color Grading 2D Lookup Texture.
  87081. */
  87082. get: function () {
  87083. return this._imageProcessingConfiguration.colorGradingTexture;
  87084. },
  87085. /**
  87086. * Sets the Color Grading 2D Lookup Texture.
  87087. */
  87088. set: function (value) {
  87089. this.imageProcessingConfiguration.colorGradingTexture = value;
  87090. },
  87091. enumerable: true,
  87092. configurable: true
  87093. });
  87094. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  87095. /**
  87096. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87097. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87098. * 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;
  87099. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87100. */
  87101. get: function () {
  87102. return this.imageProcessingConfiguration.colorCurves;
  87103. },
  87104. /**
  87105. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87106. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87107. * 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;
  87108. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87109. */
  87110. set: function (value) {
  87111. this.imageProcessingConfiguration.colorCurves = value;
  87112. },
  87113. enumerable: true,
  87114. configurable: true
  87115. });
  87116. /**
  87117. * The entire material has been created in order to prevent overdraw.
  87118. * @returns false
  87119. */
  87120. BackgroundMaterial.prototype.needAlphaTesting = function () {
  87121. return true;
  87122. };
  87123. /**
  87124. * The entire material has been created in order to prevent overdraw.
  87125. * @returns true if blending is enable
  87126. */
  87127. BackgroundMaterial.prototype.needAlphaBlending = function () {
  87128. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  87129. };
  87130. /**
  87131. * Checks wether the material is ready to be rendered for a given mesh.
  87132. * @param mesh The mesh to render
  87133. * @param subMesh The submesh to check against
  87134. * @param useInstances Specify wether or not the material is used with instances
  87135. * @returns true if all the dependencies are ready (Textures, Effects...)
  87136. */
  87137. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87138. var _this = this;
  87139. if (useInstances === void 0) { useInstances = false; }
  87140. if (subMesh.effect && this.isFrozen) {
  87141. if (this._wasPreviouslyReady) {
  87142. return true;
  87143. }
  87144. }
  87145. if (!subMesh._materialDefines) {
  87146. subMesh._materialDefines = new BackgroundMaterialDefines();
  87147. }
  87148. var scene = this.getScene();
  87149. var defines = subMesh._materialDefines;
  87150. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87151. if (defines._renderId === scene.getRenderId()) {
  87152. return true;
  87153. }
  87154. }
  87155. var engine = scene.getEngine();
  87156. // Lights
  87157. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  87158. defines._needNormals = true;
  87159. // Textures
  87160. if (defines._areTexturesDirty) {
  87161. defines._needUVs = false;
  87162. if (scene.texturesEnabled) {
  87163. if (scene.getEngine().getCaps().textureLOD) {
  87164. defines.TEXTURELODSUPPORT = true;
  87165. }
  87166. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87167. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  87168. return false;
  87169. }
  87170. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  87171. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  87172. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  87173. defines.OPACITYFRESNEL = this._opacityFresnel;
  87174. }
  87175. else {
  87176. defines.DIFFUSE = false;
  87177. defines.DIFFUSEHASALPHA = false;
  87178. defines.GAMMADIFFUSE = false;
  87179. defines.OPACITYFRESNEL = false;
  87180. }
  87181. var reflectionTexture = this._reflectionTexture;
  87182. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87183. if (!reflectionTexture.isReadyOrNotBlocking()) {
  87184. return false;
  87185. }
  87186. defines.REFLECTION = true;
  87187. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  87188. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  87189. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  87190. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  87191. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  87192. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  87193. defines.INVERTCUBICMAP = true;
  87194. }
  87195. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  87196. switch (reflectionTexture.coordinatesMode) {
  87197. case BABYLON.Texture.CUBIC_MODE:
  87198. case BABYLON.Texture.INVCUBIC_MODE:
  87199. defines.REFLECTIONMAP_CUBIC = true;
  87200. break;
  87201. case BABYLON.Texture.EXPLICIT_MODE:
  87202. defines.REFLECTIONMAP_EXPLICIT = true;
  87203. break;
  87204. case BABYLON.Texture.PLANAR_MODE:
  87205. defines.REFLECTIONMAP_PLANAR = true;
  87206. break;
  87207. case BABYLON.Texture.PROJECTION_MODE:
  87208. defines.REFLECTIONMAP_PROJECTION = true;
  87209. break;
  87210. case BABYLON.Texture.SKYBOX_MODE:
  87211. defines.REFLECTIONMAP_SKYBOX = true;
  87212. break;
  87213. case BABYLON.Texture.SPHERICAL_MODE:
  87214. defines.REFLECTIONMAP_SPHERICAL = true;
  87215. break;
  87216. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  87217. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  87218. break;
  87219. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  87220. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  87221. break;
  87222. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  87223. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  87224. break;
  87225. }
  87226. if (this.reflectionFresnel) {
  87227. defines.REFLECTIONFRESNEL = true;
  87228. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  87229. this._reflectionControls.x = this.reflectionAmount;
  87230. this._reflectionControls.y = this.reflectionReflectance0;
  87231. this._reflectionControls.z = this.reflectionReflectance90;
  87232. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  87233. }
  87234. else {
  87235. defines.REFLECTIONFRESNEL = false;
  87236. defines.REFLECTIONFALLOFF = false;
  87237. }
  87238. }
  87239. else {
  87240. defines.REFLECTION = false;
  87241. defines.REFLECTIONFALLOFF = false;
  87242. defines.REFLECTIONBLUR = false;
  87243. defines.REFLECTIONMAP_3D = false;
  87244. defines.REFLECTIONMAP_SPHERICAL = false;
  87245. defines.REFLECTIONMAP_PLANAR = false;
  87246. defines.REFLECTIONMAP_CUBIC = false;
  87247. defines.REFLECTIONMAP_PROJECTION = false;
  87248. defines.REFLECTIONMAP_SKYBOX = false;
  87249. defines.REFLECTIONMAP_EXPLICIT = false;
  87250. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87251. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87252. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87253. defines.INVERTCUBICMAP = false;
  87254. defines.REFLECTIONMAP_OPPOSITEZ = false;
  87255. defines.LODINREFLECTIONALPHA = false;
  87256. defines.GAMMAREFLECTION = false;
  87257. }
  87258. }
  87259. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  87260. defines.USERGBCOLOR = this._useRGBColor;
  87261. defines.NOISE = this._enableNoise;
  87262. }
  87263. if (defines._areImageProcessingDirty) {
  87264. if (!this._imageProcessingConfiguration.isReady()) {
  87265. return false;
  87266. }
  87267. this._imageProcessingConfiguration.prepareDefines(defines);
  87268. }
  87269. // Misc.
  87270. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  87271. // Values that need to be evaluated on every frame
  87272. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  87273. // Attribs
  87274. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  87275. if (mesh) {
  87276. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  87277. mesh.createNormals(true);
  87278. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  87279. }
  87280. }
  87281. }
  87282. // Get correct effect
  87283. if (defines.isDirty) {
  87284. defines.markAsProcessed();
  87285. scene.resetCachedMaterial();
  87286. // Fallbacks
  87287. var fallbacks = new BABYLON.EffectFallbacks();
  87288. if (defines.FOG) {
  87289. fallbacks.addFallback(0, "FOG");
  87290. }
  87291. if (defines.POINTSIZE) {
  87292. fallbacks.addFallback(1, "POINTSIZE");
  87293. }
  87294. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  87295. if (defines.NUM_BONE_INFLUENCERS > 0) {
  87296. fallbacks.addCPUSkinningFallback(0, mesh);
  87297. }
  87298. //Attributes
  87299. var attribs = [BABYLON.VertexBuffer.PositionKind];
  87300. if (defines.NORMAL) {
  87301. attribs.push(BABYLON.VertexBuffer.NormalKind);
  87302. }
  87303. if (defines.UV1) {
  87304. attribs.push(BABYLON.VertexBuffer.UVKind);
  87305. }
  87306. if (defines.UV2) {
  87307. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  87308. }
  87309. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  87310. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  87311. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  87312. "vFogInfos", "vFogColor", "pointSize",
  87313. "vClipPlane", "mBones",
  87314. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  87315. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  87316. "shadowLevel", "alpha",
  87317. "vBackgroundCenter", "vReflectionControl",
  87318. "vDiffuseInfos", "diffuseMatrix",
  87319. ];
  87320. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  87321. var uniformBuffers = ["Material", "Scene"];
  87322. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  87323. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  87324. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  87325. uniformsNames: uniforms,
  87326. uniformBuffersNames: uniformBuffers,
  87327. samplers: samplers,
  87328. defines: defines,
  87329. maxSimultaneousLights: this._maxSimultaneousLights
  87330. });
  87331. var onCompiled = function (effect) {
  87332. if (_this.onCompiled) {
  87333. _this.onCompiled(effect);
  87334. }
  87335. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  87336. };
  87337. var join = defines.toString();
  87338. subMesh.setEffect(scene.getEngine().createEffect("background", {
  87339. attributes: attribs,
  87340. uniformsNames: uniforms,
  87341. uniformBuffersNames: uniformBuffers,
  87342. samplers: samplers,
  87343. defines: join,
  87344. fallbacks: fallbacks,
  87345. onCompiled: onCompiled,
  87346. onError: this.onError,
  87347. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  87348. }, engine), defines);
  87349. this.buildUniformLayout();
  87350. }
  87351. if (!subMesh.effect || !subMesh.effect.isReady()) {
  87352. return false;
  87353. }
  87354. defines._renderId = scene.getRenderId();
  87355. this._wasPreviouslyReady = true;
  87356. return true;
  87357. };
  87358. /**
  87359. * Build the uniform buffer used in the material.
  87360. */
  87361. BackgroundMaterial.prototype.buildUniformLayout = function () {
  87362. // Order is important !
  87363. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  87364. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  87365. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  87366. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  87367. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  87368. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  87369. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  87370. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  87371. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  87372. this._uniformBuffer.addUniform("pointSize", 1);
  87373. this._uniformBuffer.addUniform("shadowLevel", 1);
  87374. this._uniformBuffer.addUniform("alpha", 1);
  87375. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  87376. this._uniformBuffer.addUniform("vReflectionControl", 4);
  87377. this._uniformBuffer.create();
  87378. };
  87379. /**
  87380. * Unbind the material.
  87381. */
  87382. BackgroundMaterial.prototype.unbind = function () {
  87383. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  87384. this._uniformBuffer.setTexture("diffuseSampler", null);
  87385. }
  87386. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  87387. this._uniformBuffer.setTexture("reflectionSampler", null);
  87388. }
  87389. _super.prototype.unbind.call(this);
  87390. };
  87391. /**
  87392. * Bind only the world matrix to the material.
  87393. * @param world The world matrix to bind.
  87394. */
  87395. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  87396. this._activeEffect.setMatrix("world", world);
  87397. };
  87398. /**
  87399. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  87400. * @param world The world matrix to bind.
  87401. * @param subMesh The submesh to bind for.
  87402. */
  87403. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  87404. var scene = this.getScene();
  87405. var defines = subMesh._materialDefines;
  87406. if (!defines) {
  87407. return;
  87408. }
  87409. var effect = subMesh.effect;
  87410. if (!effect) {
  87411. return;
  87412. }
  87413. this._activeEffect = effect;
  87414. // Matrices
  87415. this.bindOnlyWorldMatrix(world);
  87416. // Bones
  87417. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  87418. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  87419. if (mustRebind) {
  87420. this._uniformBuffer.bindToEffect(effect, "Material");
  87421. this.bindViewProjection(effect);
  87422. var reflectionTexture = this._reflectionTexture;
  87423. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  87424. // Texture uniforms
  87425. if (scene.texturesEnabled) {
  87426. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87427. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  87428. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  87429. }
  87430. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87431. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  87432. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  87433. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  87434. }
  87435. }
  87436. if (this.shadowLevel > 0) {
  87437. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  87438. }
  87439. this._uniformBuffer.updateFloat("alpha", this.alpha);
  87440. // Point size
  87441. if (this.pointsCloud) {
  87442. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  87443. }
  87444. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  87445. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  87446. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  87447. }
  87448. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  87449. // Textures
  87450. if (scene.texturesEnabled) {
  87451. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87452. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  87453. }
  87454. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87455. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  87456. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87457. }
  87458. else if (!defines.REFLECTIONBLUR) {
  87459. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  87460. }
  87461. else {
  87462. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  87463. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  87464. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  87465. }
  87466. if (defines.REFLECTIONFRESNEL) {
  87467. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  87468. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  87469. }
  87470. }
  87471. }
  87472. // Clip plane
  87473. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  87474. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  87475. }
  87476. if (mustRebind || !this.isFrozen) {
  87477. if (scene.lightsEnabled) {
  87478. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  87479. }
  87480. // View
  87481. this.bindView(effect);
  87482. // Fog
  87483. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  87484. // image processing
  87485. this._imageProcessingConfiguration.bind(this._activeEffect);
  87486. }
  87487. this._uniformBuffer.update();
  87488. this._afterBind(mesh);
  87489. };
  87490. /**
  87491. * Dispose the material.
  87492. * @param forceDisposeEffect Force disposal of the associated effect.
  87493. * @param forceDisposeTextures Force disposal of the associated textures.
  87494. */
  87495. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  87496. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  87497. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  87498. if (forceDisposeTextures) {
  87499. if (this.diffuseTexture) {
  87500. this.diffuseTexture.dispose();
  87501. }
  87502. if (this.reflectionTexture) {
  87503. this.reflectionTexture.dispose();
  87504. }
  87505. }
  87506. this._renderTargets.dispose();
  87507. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87508. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87509. }
  87510. _super.prototype.dispose.call(this, forceDisposeEffect);
  87511. };
  87512. /**
  87513. * Clones the material.
  87514. * @param name The cloned name.
  87515. * @returns The cloned material.
  87516. */
  87517. BackgroundMaterial.prototype.clone = function (name) {
  87518. var _this = this;
  87519. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  87520. };
  87521. /**
  87522. * Serializes the current material to its JSON representation.
  87523. * @returns The JSON representation.
  87524. */
  87525. BackgroundMaterial.prototype.serialize = function () {
  87526. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87527. serializationObject.customType = "BABYLON.BackgroundMaterial";
  87528. return serializationObject;
  87529. };
  87530. /**
  87531. * Gets the class name of the material
  87532. * @returns "BackgroundMaterial"
  87533. */
  87534. BackgroundMaterial.prototype.getClassName = function () {
  87535. return "BackgroundMaterial";
  87536. };
  87537. /**
  87538. * Parse a JSON input to create back a background material.
  87539. * @param source The JSON data to parse
  87540. * @param scene The scene to create the parsed material in
  87541. * @param rootUrl The root url of the assets the material depends upon
  87542. * @returns the instantiated BackgroundMaterial.
  87543. */
  87544. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  87545. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  87546. };
  87547. /**
  87548. * Standard reflectance value at parallel view angle.
  87549. */
  87550. BackgroundMaterial.StandardReflectance0 = 0.05;
  87551. /**
  87552. * Standard reflectance value at grazing angle.
  87553. */
  87554. BackgroundMaterial.StandardReflectance90 = 0.5;
  87555. __decorate([
  87556. BABYLON.serializeAsColor3()
  87557. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  87558. __decorate([
  87559. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87560. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  87561. __decorate([
  87562. BABYLON.serialize()
  87563. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  87564. __decorate([
  87565. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87566. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  87567. __decorate([
  87568. BABYLON.serializeAsColor3()
  87569. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  87570. __decorate([
  87571. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87572. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  87573. __decorate([
  87574. BABYLON.serialize()
  87575. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  87576. __decorate([
  87577. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87578. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  87579. __decorate([
  87580. BABYLON.serializeAsColor3()
  87581. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  87582. __decorate([
  87583. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87584. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  87585. __decorate([
  87586. BABYLON.serialize()
  87587. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  87588. __decorate([
  87589. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  87590. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  87591. __decorate([
  87592. BABYLON.serializeAsTexture()
  87593. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  87594. __decorate([
  87595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87596. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  87597. __decorate([
  87598. BABYLON.serialize()
  87599. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  87600. __decorate([
  87601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87602. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  87603. __decorate([
  87604. BABYLON.serializeAsTexture()
  87605. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  87606. __decorate([
  87607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87608. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  87609. __decorate([
  87610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87611. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  87612. __decorate([
  87613. BABYLON.serialize()
  87614. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  87615. __decorate([
  87616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87617. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  87618. __decorate([
  87619. BABYLON.serialize()
  87620. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  87621. __decorate([
  87622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87623. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  87624. __decorate([
  87625. BABYLON.serializeAsVector3()
  87626. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  87627. __decorate([
  87628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87629. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  87630. __decorate([
  87631. BABYLON.serialize()
  87632. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  87633. __decorate([
  87634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87635. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  87636. __decorate([
  87637. BABYLON.serialize()
  87638. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  87639. __decorate([
  87640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87641. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  87642. __decorate([
  87643. BABYLON.serialize()
  87644. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  87645. __decorate([
  87646. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87647. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  87648. __decorate([
  87649. BABYLON.serialize()
  87650. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  87651. __decorate([
  87652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87653. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  87654. __decorate([
  87655. BABYLON.serialize()
  87656. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  87657. __decorate([
  87658. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87659. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  87660. __decorate([
  87661. BABYLON.serialize()
  87662. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  87663. __decorate([
  87664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87665. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  87666. __decorate([
  87667. BABYLON.serialize()
  87668. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  87669. __decorate([
  87670. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87671. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  87672. __decorate([
  87673. BABYLON.serialize()
  87674. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  87675. __decorate([
  87676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87677. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  87678. __decorate([
  87679. BABYLON.serialize()
  87680. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  87681. __decorate([
  87682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  87683. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  87684. __decorate([
  87685. BABYLON.serializeAsImageProcessingConfiguration()
  87686. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  87687. return BackgroundMaterial;
  87688. }(BABYLON.PushMaterial));
  87689. BABYLON.BackgroundMaterial = BackgroundMaterial;
  87690. })(BABYLON || (BABYLON = {}));
  87691. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  87692. var __assign = (this && this.__assign) || Object.assign || function(t) {
  87693. for (var s, i = 1, n = arguments.length; i < n; i++) {
  87694. s = arguments[i];
  87695. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  87696. t[p] = s[p];
  87697. }
  87698. return t;
  87699. };
  87700. var BABYLON;
  87701. (function (BABYLON) {
  87702. /**
  87703. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  87704. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  87705. * It also helps with the default setup of your imageProcessing configuration.
  87706. */
  87707. var EnvironmentHelper = /** @class */ (function () {
  87708. /**
  87709. * constructor
  87710. * @param options
  87711. * @param scene The scene to add the material to
  87712. */
  87713. function EnvironmentHelper(options, scene) {
  87714. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  87715. this._scene = scene;
  87716. this._setupBackground();
  87717. this._setupImageProcessing();
  87718. }
  87719. /**
  87720. * Creates the default options for the helper.
  87721. */
  87722. EnvironmentHelper._getDefaultOptions = function () {
  87723. return {
  87724. createGround: true,
  87725. groundSize: 15,
  87726. groundTexture: this._groundTextureCDNUrl,
  87727. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87728. groundOpacity: 0.9,
  87729. enableGroundShadow: true,
  87730. groundShadowLevel: 0.5,
  87731. enableGroundMirror: false,
  87732. groundMirrorSizeRatio: 0.3,
  87733. groundMirrorBlurKernel: 64,
  87734. groundMirrorAmount: 1,
  87735. groundMirrorFresnelWeight: 1,
  87736. groundMirrorFallOffDistance: 0,
  87737. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  87738. groundYBias: 0.00001,
  87739. createSkybox: true,
  87740. skyboxSize: 20,
  87741. skyboxTexture: this._skyboxTextureCDNUrl,
  87742. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  87743. backgroundYRotation: 0,
  87744. sizeAuto: true,
  87745. rootPosition: BABYLON.Vector3.Zero(),
  87746. setupImageProcessing: true,
  87747. environmentTexture: this._environmentTextureCDNUrl,
  87748. cameraExposure: 0.8,
  87749. cameraContrast: 1.2,
  87750. toneMappingEnabled: true,
  87751. };
  87752. };
  87753. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  87754. /**
  87755. * Gets the root mesh created by the helper.
  87756. */
  87757. get: function () {
  87758. return this._rootMesh;
  87759. },
  87760. enumerable: true,
  87761. configurable: true
  87762. });
  87763. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  87764. /**
  87765. * Gets the skybox created by the helper.
  87766. */
  87767. get: function () {
  87768. return this._skybox;
  87769. },
  87770. enumerable: true,
  87771. configurable: true
  87772. });
  87773. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  87774. /**
  87775. * Gets the skybox texture created by the helper.
  87776. */
  87777. get: function () {
  87778. return this._skyboxTexture;
  87779. },
  87780. enumerable: true,
  87781. configurable: true
  87782. });
  87783. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  87784. /**
  87785. * Gets the skybox material created by the helper.
  87786. */
  87787. get: function () {
  87788. return this._skyboxMaterial;
  87789. },
  87790. enumerable: true,
  87791. configurable: true
  87792. });
  87793. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  87794. /**
  87795. * Gets the ground mesh created by the helper.
  87796. */
  87797. get: function () {
  87798. return this._ground;
  87799. },
  87800. enumerable: true,
  87801. configurable: true
  87802. });
  87803. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  87804. /**
  87805. * Gets the ground texture created by the helper.
  87806. */
  87807. get: function () {
  87808. return this._groundTexture;
  87809. },
  87810. enumerable: true,
  87811. configurable: true
  87812. });
  87813. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  87814. /**
  87815. * Gets the ground mirror created by the helper.
  87816. */
  87817. get: function () {
  87818. return this._groundMirror;
  87819. },
  87820. enumerable: true,
  87821. configurable: true
  87822. });
  87823. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  87824. /**
  87825. * Gets the ground mirror render list to helps pushing the meshes
  87826. * you wish in the ground reflection.
  87827. */
  87828. get: function () {
  87829. if (this._groundMirror) {
  87830. return this._groundMirror.renderList;
  87831. }
  87832. return null;
  87833. },
  87834. enumerable: true,
  87835. configurable: true
  87836. });
  87837. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  87838. /**
  87839. * Gets the ground material created by the helper.
  87840. */
  87841. get: function () {
  87842. return this._groundMaterial;
  87843. },
  87844. enumerable: true,
  87845. configurable: true
  87846. });
  87847. /**
  87848. * Updates the background according to the new options
  87849. * @param options
  87850. */
  87851. EnvironmentHelper.prototype.updateOptions = function (options) {
  87852. var newOptions = __assign({}, this._options, options);
  87853. if (this._ground && !newOptions.createGround) {
  87854. this._ground.dispose();
  87855. this._ground = null;
  87856. }
  87857. if (this._groundMaterial && !newOptions.createGround) {
  87858. this._groundMaterial.dispose();
  87859. this._groundMaterial = null;
  87860. }
  87861. if (this._groundTexture) {
  87862. if (this._options.groundTexture != newOptions.groundTexture) {
  87863. this._groundTexture.dispose();
  87864. this._groundTexture = null;
  87865. }
  87866. }
  87867. if (this._skybox && !newOptions.createSkybox) {
  87868. this._skybox.dispose();
  87869. this._skybox = null;
  87870. }
  87871. if (this._skyboxMaterial && !newOptions.createSkybox) {
  87872. this._skyboxMaterial.dispose();
  87873. this._skyboxMaterial = null;
  87874. }
  87875. if (this._skyboxTexture) {
  87876. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  87877. this._skyboxTexture.dispose();
  87878. this._skyboxTexture = null;
  87879. }
  87880. }
  87881. if (this._groundMirror && !newOptions.enableGroundMirror) {
  87882. this._groundMirror.dispose();
  87883. this._groundMirror = null;
  87884. }
  87885. if (this._scene.environmentTexture) {
  87886. if (this._options.environmentTexture != newOptions.environmentTexture) {
  87887. this._scene.environmentTexture.dispose();
  87888. }
  87889. }
  87890. this._options = newOptions;
  87891. this._setupBackground();
  87892. this._setupImageProcessing();
  87893. };
  87894. /**
  87895. * Sets the primary color of all the available elements.
  87896. * @param color
  87897. */
  87898. EnvironmentHelper.prototype.setMainColor = function (color) {
  87899. if (this.groundMaterial) {
  87900. this.groundMaterial.primaryColor = color;
  87901. }
  87902. if (this.skyboxMaterial) {
  87903. this.skyboxMaterial.primaryColor = color;
  87904. }
  87905. if (this.groundMirror) {
  87906. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  87907. }
  87908. };
  87909. /**
  87910. * Setup the image processing according to the specified options.
  87911. */
  87912. EnvironmentHelper.prototype._setupImageProcessing = function () {
  87913. if (this._options.setupImageProcessing) {
  87914. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  87915. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  87916. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  87917. this._setupEnvironmentTexture();
  87918. }
  87919. };
  87920. /**
  87921. * Setup the environment texture according to the specified options.
  87922. */
  87923. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  87924. if (this._scene.environmentTexture) {
  87925. return;
  87926. }
  87927. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  87928. this._scene.environmentTexture = this._options.environmentTexture;
  87929. return;
  87930. }
  87931. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  87932. this._scene.environmentTexture = environmentTexture;
  87933. };
  87934. /**
  87935. * Setup the background according to the specified options.
  87936. */
  87937. EnvironmentHelper.prototype._setupBackground = function () {
  87938. if (!this._rootMesh) {
  87939. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  87940. }
  87941. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  87942. var sceneSize = this._getSceneSize();
  87943. if (this._options.createGround) {
  87944. this._setupGround(sceneSize);
  87945. this._setupGroundMaterial();
  87946. this._setupGroundDiffuseTexture();
  87947. if (this._options.enableGroundMirror) {
  87948. this._setupGroundMirrorTexture(sceneSize);
  87949. }
  87950. this._setupMirrorInGroundMaterial();
  87951. }
  87952. if (this._options.createSkybox) {
  87953. this._setupSkybox(sceneSize);
  87954. this._setupSkyboxMaterial();
  87955. this._setupSkyboxReflectionTexture();
  87956. }
  87957. this._rootMesh.position.x = sceneSize.rootPosition.x;
  87958. this._rootMesh.position.z = sceneSize.rootPosition.z;
  87959. this._rootMesh.position.y = sceneSize.rootPosition.y;
  87960. };
  87961. /**
  87962. * Get the scene sizes according to the setup.
  87963. */
  87964. EnvironmentHelper.prototype._getSceneSize = function () {
  87965. var groundSize = this._options.groundSize;
  87966. var skyboxSize = this._options.skyboxSize;
  87967. var rootPosition = this._options.rootPosition;
  87968. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  87969. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87970. }
  87971. var sceneExtends = this._scene.getWorldExtends();
  87972. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  87973. if (this._options.sizeAuto) {
  87974. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  87975. this._scene.activeCamera.upperRadiusLimit) {
  87976. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  87977. skyboxSize = groundSize;
  87978. }
  87979. var sceneDiagonalLenght = sceneDiagonal.length();
  87980. if (sceneDiagonalLenght > groundSize) {
  87981. groundSize = sceneDiagonalLenght * 2;
  87982. skyboxSize = groundSize;
  87983. }
  87984. // 10 % bigger.
  87985. groundSize *= 1.1;
  87986. skyboxSize *= 1.5;
  87987. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  87988. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  87989. }
  87990. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  87991. };
  87992. /**
  87993. * Setup the ground according to the specified options.
  87994. */
  87995. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  87996. var _this = this;
  87997. if (!this._ground) {
  87998. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  87999. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  88000. this._ground.parent = this._rootMesh;
  88001. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  88002. }
  88003. this._ground.receiveShadows = this._options.enableGroundShadow;
  88004. };
  88005. /**
  88006. * Setup the ground material according to the specified options.
  88007. */
  88008. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  88009. if (!this._groundMaterial) {
  88010. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  88011. }
  88012. this._groundMaterial.alpha = this._options.groundOpacity;
  88013. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  88014. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  88015. this._groundMaterial.primaryLevel = 1;
  88016. this._groundMaterial.primaryColor = this._options.groundColor;
  88017. this._groundMaterial.secondaryLevel = 0;
  88018. this._groundMaterial.tertiaryLevel = 0;
  88019. this._groundMaterial.useRGBColor = false;
  88020. this._groundMaterial.enableNoise = true;
  88021. if (this._ground) {
  88022. this._ground.material = this._groundMaterial;
  88023. }
  88024. };
  88025. /**
  88026. * Setup the ground diffuse texture according to the specified options.
  88027. */
  88028. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  88029. if (!this._groundMaterial) {
  88030. return;
  88031. }
  88032. if (this._groundTexture) {
  88033. return;
  88034. }
  88035. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  88036. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  88037. return;
  88038. }
  88039. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  88040. diffuseTexture.gammaSpace = false;
  88041. diffuseTexture.hasAlpha = true;
  88042. this._groundMaterial.diffuseTexture = diffuseTexture;
  88043. };
  88044. /**
  88045. * Setup the ground mirror texture according to the specified options.
  88046. */
  88047. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  88048. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88049. if (!this._groundMirror) {
  88050. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  88051. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  88052. this._groundMirror.anisotropicFilteringLevel = 1;
  88053. this._groundMirror.wrapU = wrapping;
  88054. this._groundMirror.wrapV = wrapping;
  88055. this._groundMirror.gammaSpace = false;
  88056. if (this._groundMirror.renderList) {
  88057. for (var i = 0; i < this._scene.meshes.length; i++) {
  88058. var mesh = this._scene.meshes[i];
  88059. if (mesh !== this._ground &&
  88060. mesh !== this._skybox &&
  88061. mesh !== this._rootMesh) {
  88062. this._groundMirror.renderList.push(mesh);
  88063. }
  88064. }
  88065. }
  88066. }
  88067. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  88068. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  88069. };
  88070. /**
  88071. * Setup the ground to receive the mirror texture.
  88072. */
  88073. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  88074. if (this._groundMaterial) {
  88075. this._groundMaterial.reflectionTexture = this._groundMirror;
  88076. this._groundMaterial.reflectionFresnel = true;
  88077. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  88078. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  88079. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  88080. }
  88081. };
  88082. /**
  88083. * Setup the skybox according to the specified options.
  88084. */
  88085. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  88086. var _this = this;
  88087. if (!this._skybox) {
  88088. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  88089. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  88090. }
  88091. this._skybox.parent = this._rootMesh;
  88092. };
  88093. /**
  88094. * Setup the skybox material according to the specified options.
  88095. */
  88096. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  88097. if (!this._skybox) {
  88098. return;
  88099. }
  88100. if (!this._skyboxMaterial) {
  88101. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  88102. }
  88103. this._skyboxMaterial.useRGBColor = false;
  88104. this._skyboxMaterial.primaryLevel = 1;
  88105. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  88106. this._skyboxMaterial.secondaryLevel = 0;
  88107. this._skyboxMaterial.tertiaryLevel = 0;
  88108. this._skyboxMaterial.enableNoise = true;
  88109. this._skybox.material = this._skyboxMaterial;
  88110. };
  88111. /**
  88112. * Setup the skybox reflection texture according to the specified options.
  88113. */
  88114. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  88115. if (!this._skyboxMaterial) {
  88116. return;
  88117. }
  88118. if (this._skyboxTexture) {
  88119. return;
  88120. }
  88121. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  88122. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88123. return;
  88124. }
  88125. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  88126. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  88127. this._skyboxTexture.gammaSpace = false;
  88128. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88129. };
  88130. /**
  88131. * Dispose all the elements created by the Helper.
  88132. */
  88133. EnvironmentHelper.prototype.dispose = function () {
  88134. if (this._groundMaterial) {
  88135. this._groundMaterial.dispose(true, true);
  88136. }
  88137. if (this._skyboxMaterial) {
  88138. this._skyboxMaterial.dispose(true, true);
  88139. }
  88140. this._rootMesh.dispose(false);
  88141. };
  88142. /**
  88143. * Default ground texture URL.
  88144. */
  88145. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  88146. /**
  88147. * Default skybox texture URL.
  88148. */
  88149. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  88150. /**
  88151. * Default environment texture URL.
  88152. */
  88153. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  88154. return EnvironmentHelper;
  88155. }());
  88156. BABYLON.EnvironmentHelper = EnvironmentHelper;
  88157. })(BABYLON || (BABYLON = {}));
  88158. //# sourceMappingURL=babylon.environmentHelper.js.map
  88159. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=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 screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  88160. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#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}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  88161. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88162. var BABYLON;
  88163. (function (BABYLON) {
  88164. var GridMaterialDefines = /** @class */ (function (_super) {
  88165. __extends(GridMaterialDefines, _super);
  88166. function GridMaterialDefines() {
  88167. var _this = _super.call(this) || this;
  88168. _this.TRANSPARENT = false;
  88169. _this.FOG = false;
  88170. _this.PREMULTIPLYALPHA = false;
  88171. _this.rebuild();
  88172. return _this;
  88173. }
  88174. return GridMaterialDefines;
  88175. }(BABYLON.MaterialDefines));
  88176. /**
  88177. * The grid materials allows you to wrap any shape with a grid.
  88178. * Colors are customizable.
  88179. */
  88180. var GridMaterial = /** @class */ (function (_super) {
  88181. __extends(GridMaterial, _super);
  88182. /**
  88183. * constructor
  88184. * @param name The name given to the material in order to identify it afterwards.
  88185. * @param scene The scene the material is used in.
  88186. */
  88187. function GridMaterial(name, scene) {
  88188. var _this = _super.call(this, name, scene) || this;
  88189. /**
  88190. * Main color of the grid (e.g. between lines)
  88191. */
  88192. _this.mainColor = BABYLON.Color3.Black();
  88193. /**
  88194. * Color of the grid lines.
  88195. */
  88196. _this.lineColor = BABYLON.Color3.Teal();
  88197. /**
  88198. * The scale of the grid compared to unit.
  88199. */
  88200. _this.gridRatio = 1.0;
  88201. /**
  88202. * Allows setting an offset for the grid lines.
  88203. */
  88204. _this.gridOffset = BABYLON.Vector3.Zero();
  88205. /**
  88206. * The frequency of thicker lines.
  88207. */
  88208. _this.majorUnitFrequency = 10;
  88209. /**
  88210. * The visibility of minor units in the grid.
  88211. */
  88212. _this.minorUnitVisibility = 0.33;
  88213. /**
  88214. * The grid opacity outside of the lines.
  88215. */
  88216. _this.opacity = 1.0;
  88217. /**
  88218. * Determine RBG output is premultiplied by alpha value.
  88219. */
  88220. _this.preMultiplyAlpha = false;
  88221. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  88222. return _this;
  88223. }
  88224. /**
  88225. * Returns wehter or not the grid requires alpha blending.
  88226. */
  88227. GridMaterial.prototype.needAlphaBlending = function () {
  88228. return this.opacity < 1.0;
  88229. };
  88230. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  88231. return this.needAlphaBlending();
  88232. };
  88233. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88234. if (this.isFrozen) {
  88235. if (this._wasPreviouslyReady && subMesh.effect) {
  88236. return true;
  88237. }
  88238. }
  88239. if (!subMesh._materialDefines) {
  88240. subMesh._materialDefines = new GridMaterialDefines();
  88241. }
  88242. var defines = subMesh._materialDefines;
  88243. var scene = this.getScene();
  88244. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88245. if (this._renderId === scene.getRenderId()) {
  88246. return true;
  88247. }
  88248. }
  88249. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  88250. defines.TRANSPARENT = !defines.TRANSPARENT;
  88251. defines.markAsUnprocessed();
  88252. }
  88253. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  88254. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  88255. defines.markAsUnprocessed();
  88256. }
  88257. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, false, defines);
  88258. // Get correct effect
  88259. if (defines.isDirty) {
  88260. defines.markAsProcessed();
  88261. scene.resetCachedMaterial();
  88262. // Attributes
  88263. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  88264. // Defines
  88265. var join = defines.toString();
  88266. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  88267. }
  88268. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88269. return false;
  88270. }
  88271. this._renderId = scene.getRenderId();
  88272. this._wasPreviouslyReady = true;
  88273. return true;
  88274. };
  88275. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88276. var scene = this.getScene();
  88277. var defines = subMesh._materialDefines;
  88278. if (!defines) {
  88279. return;
  88280. }
  88281. var effect = subMesh.effect;
  88282. if (!effect) {
  88283. return;
  88284. }
  88285. this._activeEffect = effect;
  88286. // Matrices
  88287. this.bindOnlyWorldMatrix(world);
  88288. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  88289. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  88290. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  88291. // Uniforms
  88292. if (this._mustRebind(scene, effect)) {
  88293. this._activeEffect.setColor3("mainColor", this.mainColor);
  88294. this._activeEffect.setColor3("lineColor", this.lineColor);
  88295. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  88296. this._gridControl.x = this.gridRatio;
  88297. this._gridControl.y = Math.round(this.majorUnitFrequency);
  88298. this._gridControl.z = this.minorUnitVisibility;
  88299. this._gridControl.w = this.opacity;
  88300. this._activeEffect.setVector4("gridControl", this._gridControl);
  88301. }
  88302. // Fog
  88303. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88304. this._afterBind(mesh, this._activeEffect);
  88305. };
  88306. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  88307. _super.prototype.dispose.call(this, forceDisposeEffect);
  88308. };
  88309. GridMaterial.prototype.clone = function (name) {
  88310. var _this = this;
  88311. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  88312. };
  88313. GridMaterial.prototype.serialize = function () {
  88314. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88315. serializationObject.customType = "BABYLON.GridMaterial";
  88316. return serializationObject;
  88317. };
  88318. GridMaterial.prototype.getClassName = function () {
  88319. return "GridMaterial";
  88320. };
  88321. GridMaterial.Parse = function (source, scene, rootUrl) {
  88322. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  88323. };
  88324. __decorate([
  88325. BABYLON.serializeAsColor3()
  88326. ], GridMaterial.prototype, "mainColor", void 0);
  88327. __decorate([
  88328. BABYLON.serializeAsColor3()
  88329. ], GridMaterial.prototype, "lineColor", void 0);
  88330. __decorate([
  88331. BABYLON.serialize()
  88332. ], GridMaterial.prototype, "gridRatio", void 0);
  88333. __decorate([
  88334. BABYLON.serializeAsColor3()
  88335. ], GridMaterial.prototype, "gridOffset", void 0);
  88336. __decorate([
  88337. BABYLON.serialize()
  88338. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  88339. __decorate([
  88340. BABYLON.serialize()
  88341. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  88342. __decorate([
  88343. BABYLON.serialize()
  88344. ], GridMaterial.prototype, "opacity", void 0);
  88345. __decorate([
  88346. BABYLON.serialize()
  88347. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  88348. return GridMaterial;
  88349. }(BABYLON.PushMaterial));
  88350. BABYLON.GridMaterial = GridMaterial;
  88351. })(BABYLON || (BABYLON = {}));
  88352. //# sourceMappingURL=babylon.gridmaterial.js.map
  88353. 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}";
  88354. 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}";
  88355. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  88356. var BABYLON;
  88357. (function (BABYLON) {
  88358. var GLTFLoaderCoordinateSystemMode;
  88359. (function (GLTFLoaderCoordinateSystemMode) {
  88360. /**
  88361. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  88362. */
  88363. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  88364. /**
  88365. * Sets the useRightHandedSystem flag on the scene.
  88366. */
  88367. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  88368. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  88369. var GLTFLoaderAnimationStartMode;
  88370. (function (GLTFLoaderAnimationStartMode) {
  88371. /**
  88372. * No animation will start.
  88373. */
  88374. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  88375. /**
  88376. * The first animation will start.
  88377. */
  88378. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  88379. /**
  88380. * All animations will start.
  88381. */
  88382. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  88383. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  88384. var GLTFLoaderState;
  88385. (function (GLTFLoaderState) {
  88386. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  88387. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  88388. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  88389. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  88390. var GLTFFileLoader = /** @class */ (function () {
  88391. function GLTFFileLoader() {
  88392. // #region Common options
  88393. /**
  88394. * Raised when the asset has been parsed.
  88395. * The data.json property stores the glTF JSON.
  88396. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  88397. */
  88398. this.onParsedObservable = new BABYLON.Observable();
  88399. // #endregion
  88400. // #region V2 options
  88401. /**
  88402. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  88403. */
  88404. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  88405. /**
  88406. * The animation start mode (NONE, FIRST, ALL).
  88407. */
  88408. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  88409. /**
  88410. * Set to true to compile materials before raising the success callback.
  88411. */
  88412. this.compileMaterials = false;
  88413. /**
  88414. * Set to true to also compile materials with clip planes.
  88415. */
  88416. this.useClipPlane = false;
  88417. /**
  88418. * Set to true to compile shadow generators before raising the success callback.
  88419. */
  88420. this.compileShadowGenerators = false;
  88421. /**
  88422. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  88423. */
  88424. this.onMeshLoadedObservable = new BABYLON.Observable();
  88425. /**
  88426. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  88427. */
  88428. this.onTextureLoadedObservable = new BABYLON.Observable();
  88429. /**
  88430. * Raised when the loader creates a material after parsing the glTF properties of the material.
  88431. */
  88432. this.onMaterialLoadedObservable = new BABYLON.Observable();
  88433. /**
  88434. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  88435. * For assets with LODs, raised when all of the LODs are complete.
  88436. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  88437. */
  88438. this.onCompleteObservable = new BABYLON.Observable();
  88439. /**
  88440. * Raised when the loader is disposed.
  88441. */
  88442. this.onDisposeObservable = new BABYLON.Observable();
  88443. /**
  88444. * Raised after a loader extension is created.
  88445. * Set additional options for a loader extension in this event.
  88446. */
  88447. this.onExtensionLoadedObservable = new BABYLON.Observable();
  88448. // #endregion
  88449. this._loader = null;
  88450. this.name = "gltf";
  88451. this.extensions = {
  88452. ".gltf": { isBinary: false },
  88453. ".glb": { isBinary: true }
  88454. };
  88455. }
  88456. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  88457. set: function (callback) {
  88458. if (this._onParsedObserver) {
  88459. this.onParsedObservable.remove(this._onParsedObserver);
  88460. }
  88461. this._onParsedObserver = this.onParsedObservable.add(callback);
  88462. },
  88463. enumerable: true,
  88464. configurable: true
  88465. });
  88466. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  88467. set: function (callback) {
  88468. if (this._onMeshLoadedObserver) {
  88469. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  88470. }
  88471. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  88472. },
  88473. enumerable: true,
  88474. configurable: true
  88475. });
  88476. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  88477. set: function (callback) {
  88478. if (this._onTextureLoadedObserver) {
  88479. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  88480. }
  88481. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  88482. },
  88483. enumerable: true,
  88484. configurable: true
  88485. });
  88486. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  88487. set: function (callback) {
  88488. if (this._onMaterialLoadedObserver) {
  88489. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  88490. }
  88491. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  88492. },
  88493. enumerable: true,
  88494. configurable: true
  88495. });
  88496. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  88497. set: function (callback) {
  88498. if (this._onCompleteObserver) {
  88499. this.onCompleteObservable.remove(this._onCompleteObserver);
  88500. }
  88501. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  88502. },
  88503. enumerable: true,
  88504. configurable: true
  88505. });
  88506. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  88507. set: function (callback) {
  88508. if (this._onDisposeObserver) {
  88509. this.onDisposeObservable.remove(this._onDisposeObserver);
  88510. }
  88511. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88512. },
  88513. enumerable: true,
  88514. configurable: true
  88515. });
  88516. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  88517. set: function (callback) {
  88518. if (this._onExtensionLoadedObserver) {
  88519. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  88520. }
  88521. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  88522. },
  88523. enumerable: true,
  88524. configurable: true
  88525. });
  88526. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  88527. /**
  88528. * The loader state or null if not active.
  88529. */
  88530. get: function () {
  88531. return this._loader ? this._loader.state : null;
  88532. },
  88533. enumerable: true,
  88534. configurable: true
  88535. });
  88536. /**
  88537. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  88538. */
  88539. GLTFFileLoader.prototype.dispose = function () {
  88540. if (this._loader) {
  88541. this._loader.dispose();
  88542. this._loader = null;
  88543. }
  88544. this.onMeshLoadedObservable.clear();
  88545. this.onTextureLoadedObservable.clear();
  88546. this.onMaterialLoadedObservable.clear();
  88547. this.onDisposeObservable.notifyObservers(this);
  88548. this.onDisposeObservable.clear();
  88549. };
  88550. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  88551. var _this = this;
  88552. return Promise.resolve().then(function () {
  88553. var loaderData = _this._parse(data);
  88554. _this._loader = _this._getLoader(loaderData);
  88555. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  88556. });
  88557. };
  88558. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  88559. var _this = this;
  88560. return Promise.resolve().then(function () {
  88561. var loaderData = _this._parse(data);
  88562. _this._loader = _this._getLoader(loaderData);
  88563. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  88564. });
  88565. };
  88566. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  88567. var _this = this;
  88568. return Promise.resolve().then(function () {
  88569. var loaderData = _this._parse(data);
  88570. _this._loader = _this._getLoader(loaderData);
  88571. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  88572. var container = new BABYLON.AssetContainer(scene);
  88573. Array.prototype.push.apply(container.meshes, result.meshes);
  88574. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  88575. Array.prototype.push.apply(container.skeletons, result.skeletons);
  88576. container.removeAllFromScene();
  88577. return container;
  88578. });
  88579. });
  88580. };
  88581. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  88582. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  88583. };
  88584. GLTFFileLoader.prototype.createPlugin = function () {
  88585. return new GLTFFileLoader();
  88586. };
  88587. GLTFFileLoader.prototype._parse = function (data) {
  88588. var parsedData;
  88589. if (data instanceof ArrayBuffer) {
  88590. parsedData = GLTFFileLoader._parseBinary(data);
  88591. }
  88592. else {
  88593. parsedData = {
  88594. json: JSON.parse(data),
  88595. bin: null
  88596. };
  88597. }
  88598. this.onParsedObservable.notifyObservers(parsedData);
  88599. this.onParsedObservable.clear();
  88600. return parsedData;
  88601. };
  88602. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  88603. var _this = this;
  88604. var loaderVersion = { major: 2, minor: 0 };
  88605. var asset = loaderData.json.asset || {};
  88606. var version = GLTFFileLoader._parseVersion(asset.version);
  88607. if (!version) {
  88608. throw new Error("Invalid version: " + asset.version);
  88609. }
  88610. if (asset.minVersion !== undefined) {
  88611. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  88612. if (!minVersion) {
  88613. throw new Error("Invalid minimum version: " + asset.minVersion);
  88614. }
  88615. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  88616. throw new Error("Incompatible minimum version: " + asset.minVersion);
  88617. }
  88618. }
  88619. var createLoaders = {
  88620. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  88621. 2: GLTFFileLoader.CreateGLTFLoaderV2
  88622. };
  88623. var createLoader = createLoaders[version.major];
  88624. if (!createLoader) {
  88625. throw new Error("Unsupported version: " + asset.version);
  88626. }
  88627. var loader = createLoader();
  88628. loader.coordinateSystemMode = this.coordinateSystemMode;
  88629. loader.animationStartMode = this.animationStartMode;
  88630. loader.compileMaterials = this.compileMaterials;
  88631. loader.useClipPlane = this.useClipPlane;
  88632. loader.compileShadowGenerators = this.compileShadowGenerators;
  88633. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  88634. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  88635. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  88636. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  88637. loader.onCompleteObservable.add(function () {
  88638. _this.onMeshLoadedObservable.clear();
  88639. _this.onTextureLoadedObservable.clear();
  88640. _this.onMaterialLoadedObservable.clear();
  88641. _this.onCompleteObservable.notifyObservers(_this);
  88642. _this.onCompleteObservable.clear();
  88643. });
  88644. return loader;
  88645. };
  88646. GLTFFileLoader._parseBinary = function (data) {
  88647. var Binary = {
  88648. Magic: 0x46546C67
  88649. };
  88650. var binaryReader = new BinaryReader(data);
  88651. var magic = binaryReader.readUint32();
  88652. if (magic !== Binary.Magic) {
  88653. throw new Error("Unexpected magic: " + magic);
  88654. }
  88655. var version = binaryReader.readUint32();
  88656. switch (version) {
  88657. case 1: return GLTFFileLoader._parseV1(binaryReader);
  88658. case 2: return GLTFFileLoader._parseV2(binaryReader);
  88659. }
  88660. throw new Error("Unsupported version: " + version);
  88661. };
  88662. GLTFFileLoader._parseV1 = function (binaryReader) {
  88663. var ContentFormat = {
  88664. JSON: 0
  88665. };
  88666. var length = binaryReader.readUint32();
  88667. if (length != binaryReader.getLength()) {
  88668. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88669. }
  88670. var contentLength = binaryReader.readUint32();
  88671. var contentFormat = binaryReader.readUint32();
  88672. var content;
  88673. switch (contentFormat) {
  88674. case ContentFormat.JSON: {
  88675. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  88676. break;
  88677. }
  88678. default: {
  88679. throw new Error("Unexpected content format: " + contentFormat);
  88680. }
  88681. }
  88682. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  88683. var body = binaryReader.readUint8Array(bytesRemaining);
  88684. return {
  88685. json: content,
  88686. bin: body
  88687. };
  88688. };
  88689. GLTFFileLoader._parseV2 = function (binaryReader) {
  88690. var ChunkFormat = {
  88691. JSON: 0x4E4F534A,
  88692. BIN: 0x004E4942
  88693. };
  88694. var length = binaryReader.readUint32();
  88695. if (length !== binaryReader.getLength()) {
  88696. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  88697. }
  88698. // JSON chunk
  88699. var chunkLength = binaryReader.readUint32();
  88700. var chunkFormat = binaryReader.readUint32();
  88701. if (chunkFormat !== ChunkFormat.JSON) {
  88702. throw new Error("First chunk format is not JSON");
  88703. }
  88704. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  88705. // Look for BIN chunk
  88706. var bin = null;
  88707. while (binaryReader.getPosition() < binaryReader.getLength()) {
  88708. var chunkLength_1 = binaryReader.readUint32();
  88709. var chunkFormat_1 = binaryReader.readUint32();
  88710. switch (chunkFormat_1) {
  88711. case ChunkFormat.JSON: {
  88712. throw new Error("Unexpected JSON chunk");
  88713. }
  88714. case ChunkFormat.BIN: {
  88715. bin = binaryReader.readUint8Array(chunkLength_1);
  88716. break;
  88717. }
  88718. default: {
  88719. // ignore unrecognized chunkFormat
  88720. binaryReader.skipBytes(chunkLength_1);
  88721. break;
  88722. }
  88723. }
  88724. }
  88725. return {
  88726. json: json,
  88727. bin: bin
  88728. };
  88729. };
  88730. GLTFFileLoader._parseVersion = function (version) {
  88731. if (version === "1.0" || version === "1.0.1") {
  88732. return {
  88733. major: 1,
  88734. minor: 0
  88735. };
  88736. }
  88737. var match = (version + "").match(/^(\d+)\.(\d+)/);
  88738. if (!match) {
  88739. return null;
  88740. }
  88741. return {
  88742. major: parseInt(match[1]),
  88743. minor: parseInt(match[2])
  88744. };
  88745. };
  88746. GLTFFileLoader._compareVersion = function (a, b) {
  88747. if (a.major > b.major)
  88748. return 1;
  88749. if (a.major < b.major)
  88750. return -1;
  88751. if (a.minor > b.minor)
  88752. return 1;
  88753. if (a.minor < b.minor)
  88754. return -1;
  88755. return 0;
  88756. };
  88757. GLTFFileLoader._decodeBufferToText = function (buffer) {
  88758. var result = "";
  88759. var length = buffer.byteLength;
  88760. for (var i = 0; i < length; i++) {
  88761. result += String.fromCharCode(buffer[i]);
  88762. }
  88763. return result;
  88764. };
  88765. // #endregion
  88766. // #region V1 options
  88767. GLTFFileLoader.IncrementalLoading = true;
  88768. GLTFFileLoader.HomogeneousCoordinates = false;
  88769. return GLTFFileLoader;
  88770. }());
  88771. BABYLON.GLTFFileLoader = GLTFFileLoader;
  88772. var BinaryReader = /** @class */ (function () {
  88773. function BinaryReader(arrayBuffer) {
  88774. this._arrayBuffer = arrayBuffer;
  88775. this._dataView = new DataView(arrayBuffer);
  88776. this._byteOffset = 0;
  88777. }
  88778. BinaryReader.prototype.getPosition = function () {
  88779. return this._byteOffset;
  88780. };
  88781. BinaryReader.prototype.getLength = function () {
  88782. return this._arrayBuffer.byteLength;
  88783. };
  88784. BinaryReader.prototype.readUint32 = function () {
  88785. var value = this._dataView.getUint32(this._byteOffset, true);
  88786. this._byteOffset += 4;
  88787. return value;
  88788. };
  88789. BinaryReader.prototype.readUint8Array = function (length) {
  88790. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  88791. this._byteOffset += length;
  88792. return value;
  88793. };
  88794. BinaryReader.prototype.skipBytes = function (length) {
  88795. this._byteOffset += length;
  88796. };
  88797. return BinaryReader;
  88798. }());
  88799. if (BABYLON.SceneLoader) {
  88800. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  88801. }
  88802. })(BABYLON || (BABYLON = {}));
  88803. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  88804. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88805. var BABYLON;
  88806. (function (BABYLON) {
  88807. var GLTF1;
  88808. (function (GLTF1) {
  88809. /**
  88810. * Enums
  88811. */
  88812. var EComponentType;
  88813. (function (EComponentType) {
  88814. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  88815. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88816. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  88817. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88818. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  88819. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  88820. var EShaderType;
  88821. (function (EShaderType) {
  88822. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  88823. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  88824. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  88825. var EParameterType;
  88826. (function (EParameterType) {
  88827. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  88828. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  88829. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  88830. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  88831. EParameterType[EParameterType["INT"] = 5124] = "INT";
  88832. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  88833. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  88834. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  88835. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  88836. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  88837. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  88838. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  88839. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  88840. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  88841. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  88842. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  88843. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  88844. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  88845. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  88846. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  88847. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  88848. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  88849. var ETextureWrapMode;
  88850. (function (ETextureWrapMode) {
  88851. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  88852. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  88853. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  88854. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  88855. var ETextureFilterType;
  88856. (function (ETextureFilterType) {
  88857. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  88858. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  88859. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  88860. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  88861. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  88862. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  88863. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  88864. var ETextureFormat;
  88865. (function (ETextureFormat) {
  88866. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  88867. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  88868. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  88869. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  88870. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  88871. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  88872. var ECullingType;
  88873. (function (ECullingType) {
  88874. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  88875. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  88876. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  88877. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  88878. var EBlendingFunction;
  88879. (function (EBlendingFunction) {
  88880. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  88881. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  88882. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  88883. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  88884. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  88885. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  88886. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  88887. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  88888. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  88889. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  88890. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  88891. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  88892. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88893. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  88894. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  88895. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  88896. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  88897. })(BABYLON || (BABYLON = {}));
  88898. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  88899. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  88900. var BABYLON;
  88901. (function (BABYLON) {
  88902. var GLTF1;
  88903. (function (GLTF1) {
  88904. /**
  88905. * Tokenizer. Used for shaders compatibility
  88906. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  88907. */
  88908. var ETokenType;
  88909. (function (ETokenType) {
  88910. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  88911. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  88912. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  88913. })(ETokenType || (ETokenType = {}));
  88914. var Tokenizer = /** @class */ (function () {
  88915. function Tokenizer(toParse) {
  88916. this._pos = 0;
  88917. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  88918. this._toParse = toParse;
  88919. this._maxPos = toParse.length;
  88920. }
  88921. Tokenizer.prototype.getNextToken = function () {
  88922. if (this.isEnd())
  88923. return ETokenType.END_OF_INPUT;
  88924. this.currentString = this.read();
  88925. this.currentToken = ETokenType.UNKNOWN;
  88926. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  88927. this.currentToken = ETokenType.IDENTIFIER;
  88928. this.currentIdentifier = this.currentString;
  88929. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  88930. this.currentIdentifier += this.currentString;
  88931. this.forward();
  88932. }
  88933. }
  88934. return this.currentToken;
  88935. };
  88936. Tokenizer.prototype.peek = function () {
  88937. return this._toParse[this._pos];
  88938. };
  88939. Tokenizer.prototype.read = function () {
  88940. return this._toParse[this._pos++];
  88941. };
  88942. Tokenizer.prototype.forward = function () {
  88943. this._pos++;
  88944. };
  88945. Tokenizer.prototype.isEnd = function () {
  88946. return this._pos >= this._maxPos;
  88947. };
  88948. return Tokenizer;
  88949. }());
  88950. /**
  88951. * Values
  88952. */
  88953. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  88954. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  88955. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  88956. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  88957. /**
  88958. * Parse
  88959. */
  88960. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  88961. for (var buf in parsedBuffers) {
  88962. var parsedBuffer = parsedBuffers[buf];
  88963. gltfRuntime.buffers[buf] = parsedBuffer;
  88964. gltfRuntime.buffersCount++;
  88965. }
  88966. };
  88967. var parseShaders = function (parsedShaders, gltfRuntime) {
  88968. for (var sha in parsedShaders) {
  88969. var parsedShader = parsedShaders[sha];
  88970. gltfRuntime.shaders[sha] = parsedShader;
  88971. gltfRuntime.shaderscount++;
  88972. }
  88973. };
  88974. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  88975. for (var object in parsedObjects) {
  88976. var parsedObject = parsedObjects[object];
  88977. gltfRuntime[runtimeProperty][object] = parsedObject;
  88978. }
  88979. };
  88980. /**
  88981. * Utils
  88982. */
  88983. var normalizeUVs = function (buffer) {
  88984. if (!buffer) {
  88985. return;
  88986. }
  88987. for (var i = 0; i < buffer.length / 2; i++) {
  88988. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  88989. }
  88990. };
  88991. var getAttribute = function (attributeParameter) {
  88992. if (attributeParameter.semantic === "NORMAL") {
  88993. return "normal";
  88994. }
  88995. else if (attributeParameter.semantic === "POSITION") {
  88996. return "position";
  88997. }
  88998. else if (attributeParameter.semantic === "JOINT") {
  88999. return "matricesIndices";
  89000. }
  89001. else if (attributeParameter.semantic === "WEIGHT") {
  89002. return "matricesWeights";
  89003. }
  89004. else if (attributeParameter.semantic === "COLOR") {
  89005. return "color";
  89006. }
  89007. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  89008. var channel = Number(attributeParameter.semantic.split("_")[1]);
  89009. return "uv" + (channel === 0 ? "" : channel + 1);
  89010. }
  89011. return null;
  89012. };
  89013. /**
  89014. * Loads and creates animations
  89015. */
  89016. var loadAnimations = function (gltfRuntime) {
  89017. for (var anim in gltfRuntime.animations) {
  89018. var animation = gltfRuntime.animations[anim];
  89019. if (!animation.channels || !animation.samplers) {
  89020. continue;
  89021. }
  89022. var lastAnimation = null;
  89023. for (var i = 0; i < animation.channels.length; i++) {
  89024. // Get parameters and load buffers
  89025. var channel = animation.channels[i];
  89026. var sampler = animation.samplers[channel.sampler];
  89027. if (!sampler) {
  89028. continue;
  89029. }
  89030. var inputData = null;
  89031. var outputData = null;
  89032. if (animation.parameters) {
  89033. inputData = animation.parameters[sampler.input];
  89034. outputData = animation.parameters[sampler.output];
  89035. }
  89036. else {
  89037. inputData = sampler.input;
  89038. outputData = sampler.output;
  89039. }
  89040. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  89041. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  89042. var targetID = channel.target.id;
  89043. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  89044. if (targetNode === null) {
  89045. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  89046. }
  89047. if (targetNode === null) {
  89048. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  89049. continue;
  89050. }
  89051. var isBone = targetNode instanceof BABYLON.Bone;
  89052. // Get target path (position, rotation or scaling)
  89053. var targetPath = channel.target.path;
  89054. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  89055. if (targetPathIndex !== -1) {
  89056. targetPath = babylonAnimationPaths[targetPathIndex];
  89057. }
  89058. // Determine animation type
  89059. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  89060. if (!isBone) {
  89061. if (targetPath === "rotationQuaternion") {
  89062. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  89063. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  89064. }
  89065. else {
  89066. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  89067. }
  89068. }
  89069. // Create animation and key frames
  89070. var babylonAnimation = null;
  89071. var keys = [];
  89072. var arrayOffset = 0;
  89073. var modifyKey = false;
  89074. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  89075. babylonAnimation = lastAnimation;
  89076. modifyKey = true;
  89077. }
  89078. if (!modifyKey) {
  89079. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  89080. }
  89081. // For each frame
  89082. for (var j = 0; j < bufferInput.length; j++) {
  89083. var value = null;
  89084. if (targetPath === "rotationQuaternion") {
  89085. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  89086. arrayOffset += 4;
  89087. }
  89088. else {
  89089. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  89090. arrayOffset += 3;
  89091. }
  89092. if (isBone) {
  89093. var bone = targetNode;
  89094. var translation = BABYLON.Vector3.Zero();
  89095. var rotationQuaternion = new BABYLON.Quaternion();
  89096. var scaling = BABYLON.Vector3.Zero();
  89097. // Warning on decompose
  89098. var mat = bone.getBaseMatrix();
  89099. if (modifyKey && lastAnimation) {
  89100. mat = lastAnimation.getKeys()[j].value;
  89101. }
  89102. mat.decompose(scaling, rotationQuaternion, translation);
  89103. if (targetPath === "position") {
  89104. translation = value;
  89105. }
  89106. else if (targetPath === "rotationQuaternion") {
  89107. rotationQuaternion = value;
  89108. }
  89109. else {
  89110. scaling = value;
  89111. }
  89112. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  89113. }
  89114. if (!modifyKey) {
  89115. keys.push({
  89116. frame: bufferInput[j],
  89117. value: value
  89118. });
  89119. }
  89120. else if (lastAnimation) {
  89121. lastAnimation.getKeys()[j].value = value;
  89122. }
  89123. }
  89124. // Finish
  89125. if (!modifyKey && babylonAnimation) {
  89126. babylonAnimation.setKeys(keys);
  89127. targetNode.animations.push(babylonAnimation);
  89128. }
  89129. lastAnimation = babylonAnimation;
  89130. gltfRuntime.scene.stopAnimation(targetNode);
  89131. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  89132. }
  89133. }
  89134. };
  89135. /**
  89136. * Returns the bones transformation matrix
  89137. */
  89138. var configureBoneTransformation = function (node) {
  89139. var mat = null;
  89140. if (node.translation || node.rotation || node.scale) {
  89141. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  89142. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  89143. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  89144. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  89145. }
  89146. else {
  89147. mat = BABYLON.Matrix.FromArray(node.matrix);
  89148. }
  89149. return mat;
  89150. };
  89151. /**
  89152. * Returns the parent bone
  89153. */
  89154. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  89155. // Try to find
  89156. for (var i = 0; i < newSkeleton.bones.length; i++) {
  89157. if (newSkeleton.bones[i].name === jointName) {
  89158. return newSkeleton.bones[i];
  89159. }
  89160. }
  89161. // Not found, search in gltf nodes
  89162. var nodes = gltfRuntime.nodes;
  89163. for (var nde in nodes) {
  89164. var node = nodes[nde];
  89165. if (!node.jointName) {
  89166. continue;
  89167. }
  89168. var children = node.children;
  89169. for (var i = 0; i < children.length; i++) {
  89170. var child = gltfRuntime.nodes[children[i]];
  89171. if (!child.jointName) {
  89172. continue;
  89173. }
  89174. if (child.jointName === jointName) {
  89175. var mat = configureBoneTransformation(node);
  89176. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  89177. bone.id = nde;
  89178. return bone;
  89179. }
  89180. }
  89181. }
  89182. return null;
  89183. };
  89184. /**
  89185. * Returns the appropriate root node
  89186. */
  89187. var getNodeToRoot = function (nodesToRoot, id) {
  89188. for (var i = 0; i < nodesToRoot.length; i++) {
  89189. var nodeToRoot = nodesToRoot[i];
  89190. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  89191. var child = nodeToRoot.node.children[j];
  89192. if (child === id) {
  89193. return nodeToRoot.bone;
  89194. }
  89195. }
  89196. }
  89197. return null;
  89198. };
  89199. /**
  89200. * Returns the node with the joint name
  89201. */
  89202. var getJointNode = function (gltfRuntime, jointName) {
  89203. var nodes = gltfRuntime.nodes;
  89204. var node = nodes[jointName];
  89205. if (node) {
  89206. return {
  89207. node: node,
  89208. id: jointName
  89209. };
  89210. }
  89211. for (var nde in nodes) {
  89212. node = nodes[nde];
  89213. if (node.jointName === jointName) {
  89214. return {
  89215. node: node,
  89216. id: nde
  89217. };
  89218. }
  89219. }
  89220. return null;
  89221. };
  89222. /**
  89223. * Checks if a nodes is in joints
  89224. */
  89225. var nodeIsInJoints = function (skins, id) {
  89226. for (var i = 0; i < skins.jointNames.length; i++) {
  89227. if (skins.jointNames[i] === id) {
  89228. return true;
  89229. }
  89230. }
  89231. return false;
  89232. };
  89233. /**
  89234. * Fills the nodes to root for bones and builds hierarchy
  89235. */
  89236. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  89237. // Creates nodes for root
  89238. for (var nde in gltfRuntime.nodes) {
  89239. var node = gltfRuntime.nodes[nde];
  89240. var id = nde;
  89241. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  89242. continue;
  89243. }
  89244. // Create node to root bone
  89245. var mat = configureBoneTransformation(node);
  89246. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  89247. bone.id = id;
  89248. nodesToRoot.push({ bone: bone, node: node, id: id });
  89249. }
  89250. // Parenting
  89251. for (var i = 0; i < nodesToRoot.length; i++) {
  89252. var nodeToRoot = nodesToRoot[i];
  89253. var children = nodeToRoot.node.children;
  89254. for (var j = 0; j < children.length; j++) {
  89255. var child = null;
  89256. for (var k = 0; k < nodesToRoot.length; k++) {
  89257. if (nodesToRoot[k].id === children[j]) {
  89258. child = nodesToRoot[k];
  89259. break;
  89260. }
  89261. }
  89262. if (child) {
  89263. child.bone._parent = nodeToRoot.bone;
  89264. nodeToRoot.bone.children.push(child.bone);
  89265. }
  89266. }
  89267. }
  89268. };
  89269. /**
  89270. * Imports a skeleton
  89271. */
  89272. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  89273. if (!newSkeleton) {
  89274. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  89275. }
  89276. if (!skins.babylonSkeleton) {
  89277. return newSkeleton;
  89278. }
  89279. // Find the root bones
  89280. var nodesToRoot = [];
  89281. var nodesToRootToAdd = [];
  89282. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  89283. newSkeleton.bones = [];
  89284. // Joints
  89285. for (var i = 0; i < skins.jointNames.length; i++) {
  89286. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89287. if (!jointNode) {
  89288. continue;
  89289. }
  89290. var node = jointNode.node;
  89291. if (!node) {
  89292. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  89293. continue;
  89294. }
  89295. var id = jointNode.id;
  89296. // Optimize, if the bone already exists...
  89297. var existingBone = gltfRuntime.scene.getBoneByID(id);
  89298. if (existingBone) {
  89299. newSkeleton.bones.push(existingBone);
  89300. continue;
  89301. }
  89302. // Search for parent bone
  89303. var foundBone = false;
  89304. var parentBone = null;
  89305. for (var j = 0; j < i; j++) {
  89306. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  89307. if (!jointNode_1) {
  89308. continue;
  89309. }
  89310. var joint = jointNode_1.node;
  89311. if (!joint) {
  89312. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  89313. continue;
  89314. }
  89315. var children = joint.children;
  89316. if (!children) {
  89317. continue;
  89318. }
  89319. foundBone = false;
  89320. for (var k = 0; k < children.length; k++) {
  89321. if (children[k] === id) {
  89322. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  89323. foundBone = true;
  89324. break;
  89325. }
  89326. }
  89327. if (foundBone) {
  89328. break;
  89329. }
  89330. }
  89331. // Create bone
  89332. var mat = configureBoneTransformation(node);
  89333. if (!parentBone && nodesToRoot.length > 0) {
  89334. parentBone = getNodeToRoot(nodesToRoot, id);
  89335. if (parentBone) {
  89336. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  89337. nodesToRootToAdd.push(parentBone);
  89338. }
  89339. }
  89340. }
  89341. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  89342. bone.id = id;
  89343. }
  89344. // Polish
  89345. var bones = newSkeleton.bones;
  89346. newSkeleton.bones = [];
  89347. for (var i = 0; i < skins.jointNames.length; i++) {
  89348. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  89349. if (!jointNode) {
  89350. continue;
  89351. }
  89352. for (var j = 0; j < bones.length; j++) {
  89353. if (bones[j].id === jointNode.id) {
  89354. newSkeleton.bones.push(bones[j]);
  89355. break;
  89356. }
  89357. }
  89358. }
  89359. newSkeleton.prepare();
  89360. // Finish
  89361. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  89362. newSkeleton.bones.push(nodesToRootToAdd[i]);
  89363. }
  89364. return newSkeleton;
  89365. };
  89366. /**
  89367. * Imports a mesh and its geometries
  89368. */
  89369. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  89370. if (!newMesh) {
  89371. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89372. newMesh.id = id;
  89373. }
  89374. if (!node.babylonNode) {
  89375. return newMesh;
  89376. }
  89377. var subMaterials = [];
  89378. var vertexData = null;
  89379. var verticesStarts = new Array();
  89380. var verticesCounts = new Array();
  89381. var indexStarts = new Array();
  89382. var indexCounts = new Array();
  89383. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89384. var meshID = meshes[meshIndex];
  89385. var mesh = gltfRuntime.meshes[meshID];
  89386. if (!mesh) {
  89387. continue;
  89388. }
  89389. // Positions, normals and UVs
  89390. for (var i = 0; i < mesh.primitives.length; i++) {
  89391. // Temporary vertex data
  89392. var tempVertexData = new BABYLON.VertexData();
  89393. var primitive = mesh.primitives[i];
  89394. if (primitive.mode !== 4) {
  89395. // continue;
  89396. }
  89397. var attributes = primitive.attributes;
  89398. var accessor = null;
  89399. var buffer = null;
  89400. // Set positions, normal and uvs
  89401. for (var semantic in attributes) {
  89402. // Link accessor and buffer view
  89403. accessor = gltfRuntime.accessors[attributes[semantic]];
  89404. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89405. if (semantic === "NORMAL") {
  89406. tempVertexData.normals = new Float32Array(buffer.length);
  89407. tempVertexData.normals.set(buffer);
  89408. }
  89409. else if (semantic === "POSITION") {
  89410. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  89411. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  89412. for (var j = 0; j < buffer.length; j += 4) {
  89413. tempVertexData.positions[j] = buffer[j];
  89414. tempVertexData.positions[j + 1] = buffer[j + 1];
  89415. tempVertexData.positions[j + 2] = buffer[j + 2];
  89416. }
  89417. }
  89418. else {
  89419. tempVertexData.positions = new Float32Array(buffer.length);
  89420. tempVertexData.positions.set(buffer);
  89421. }
  89422. verticesCounts.push(tempVertexData.positions.length);
  89423. }
  89424. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  89425. var channel = Number(semantic.split("_")[1]);
  89426. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  89427. var uvs = new Float32Array(buffer.length);
  89428. uvs.set(buffer);
  89429. normalizeUVs(uvs);
  89430. tempVertexData.set(uvs, uvKind);
  89431. }
  89432. else if (semantic === "JOINT") {
  89433. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  89434. tempVertexData.matricesIndices.set(buffer);
  89435. }
  89436. else if (semantic === "WEIGHT") {
  89437. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  89438. tempVertexData.matricesWeights.set(buffer);
  89439. }
  89440. else if (semantic === "COLOR") {
  89441. tempVertexData.colors = new Float32Array(buffer.length);
  89442. tempVertexData.colors.set(buffer);
  89443. }
  89444. }
  89445. // Indices
  89446. accessor = gltfRuntime.accessors[primitive.indices];
  89447. if (accessor) {
  89448. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  89449. tempVertexData.indices = new Int32Array(buffer.length);
  89450. tempVertexData.indices.set(buffer);
  89451. indexCounts.push(tempVertexData.indices.length);
  89452. }
  89453. else {
  89454. // Set indices on the fly
  89455. var indices = [];
  89456. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  89457. indices.push(j);
  89458. }
  89459. tempVertexData.indices = new Int32Array(indices);
  89460. indexCounts.push(tempVertexData.indices.length);
  89461. }
  89462. if (!vertexData) {
  89463. vertexData = tempVertexData;
  89464. }
  89465. else {
  89466. vertexData.merge(tempVertexData);
  89467. }
  89468. // Sub material
  89469. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  89470. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  89471. // Update vertices start and index start
  89472. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  89473. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  89474. }
  89475. }
  89476. var material;
  89477. if (subMaterials.length > 1) {
  89478. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  89479. material.subMaterials = subMaterials;
  89480. }
  89481. else {
  89482. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  89483. }
  89484. if (subMaterials.length === 1) {
  89485. material = subMaterials[0];
  89486. }
  89487. if (!newMesh.material) {
  89488. newMesh.material = material;
  89489. }
  89490. // Apply geometry
  89491. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  89492. newMesh.computeWorldMatrix(true);
  89493. // Apply submeshes
  89494. newMesh.subMeshes = [];
  89495. var index = 0;
  89496. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  89497. var meshID = meshes[meshIndex];
  89498. var mesh = gltfRuntime.meshes[meshID];
  89499. if (!mesh) {
  89500. continue;
  89501. }
  89502. for (var i = 0; i < mesh.primitives.length; i++) {
  89503. if (mesh.primitives[i].mode !== 4) {
  89504. //continue;
  89505. }
  89506. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  89507. index++;
  89508. }
  89509. }
  89510. // Finish
  89511. return newMesh;
  89512. };
  89513. /**
  89514. * Configure node transformation from position, rotation and scaling
  89515. */
  89516. var configureNode = function (newNode, position, rotation, scaling) {
  89517. if (newNode.position) {
  89518. newNode.position = position;
  89519. }
  89520. if (newNode.rotationQuaternion || newNode.rotation) {
  89521. newNode.rotationQuaternion = rotation;
  89522. }
  89523. if (newNode.scaling) {
  89524. newNode.scaling = scaling;
  89525. }
  89526. };
  89527. /**
  89528. * Configures node from transformation matrix
  89529. */
  89530. var configureNodeFromMatrix = function (newNode, node, parent) {
  89531. if (node.matrix) {
  89532. var position = new BABYLON.Vector3(0, 0, 0);
  89533. var rotation = new BABYLON.Quaternion();
  89534. var scaling = new BABYLON.Vector3(0, 0, 0);
  89535. var mat = BABYLON.Matrix.FromArray(node.matrix);
  89536. mat.decompose(scaling, rotation, position);
  89537. configureNode(newNode, position, rotation, scaling);
  89538. }
  89539. else if (node.translation && node.rotation && node.scale) {
  89540. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  89541. }
  89542. newNode.computeWorldMatrix(true);
  89543. };
  89544. /**
  89545. * Imports a node
  89546. */
  89547. var importNode = function (gltfRuntime, node, id, parent) {
  89548. var lastNode = null;
  89549. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  89550. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  89551. return null;
  89552. }
  89553. }
  89554. // Meshes
  89555. if (node.skin) {
  89556. if (node.meshes) {
  89557. var skin = gltfRuntime.skins[node.skin];
  89558. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  89559. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  89560. if (newMesh.skeleton === null) {
  89561. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  89562. if (!skin.babylonSkeleton) {
  89563. skin.babylonSkeleton = newMesh.skeleton;
  89564. }
  89565. }
  89566. lastNode = newMesh;
  89567. }
  89568. }
  89569. else if (node.meshes) {
  89570. /**
  89571. * Improve meshes property
  89572. */
  89573. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  89574. lastNode = newMesh;
  89575. }
  89576. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89577. var light = gltfRuntime.lights[node.light];
  89578. if (light) {
  89579. if (light.type === "ambient") {
  89580. var ambienLight = light[light.type];
  89581. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89582. hemiLight.name = node.name || "";
  89583. if (ambienLight.color) {
  89584. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  89585. }
  89586. lastNode = hemiLight;
  89587. }
  89588. else if (light.type === "directional") {
  89589. var directionalLight = light[light.type];
  89590. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89591. dirLight.name = node.name || "";
  89592. if (directionalLight.color) {
  89593. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  89594. }
  89595. lastNode = dirLight;
  89596. }
  89597. else if (light.type === "point") {
  89598. var pointLight = light[light.type];
  89599. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89600. ptLight.name = node.name || "";
  89601. if (pointLight.color) {
  89602. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  89603. }
  89604. lastNode = ptLight;
  89605. }
  89606. else if (light.type === "spot") {
  89607. var spotLight = light[light.type];
  89608. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  89609. spLight.name = node.name || "";
  89610. if (spotLight.color) {
  89611. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  89612. }
  89613. if (spotLight.fallOfAngle) {
  89614. spLight.angle = spotLight.fallOfAngle;
  89615. }
  89616. if (spotLight.fallOffExponent) {
  89617. spLight.exponent = spotLight.fallOffExponent;
  89618. }
  89619. lastNode = spLight;
  89620. }
  89621. }
  89622. }
  89623. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  89624. var camera = gltfRuntime.cameras[node.camera];
  89625. if (camera) {
  89626. if (camera.type === "orthographic") {
  89627. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89628. orthoCamera.name = node.name || "";
  89629. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  89630. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89631. lastNode = orthoCamera;
  89632. }
  89633. else if (camera.type === "perspective") {
  89634. var perspectiveCamera = camera[camera.type];
  89635. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  89636. persCamera.name = node.name || "";
  89637. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  89638. if (!perspectiveCamera.aspectRatio) {
  89639. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  89640. }
  89641. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  89642. persCamera.maxZ = perspectiveCamera.zfar;
  89643. persCamera.minZ = perspectiveCamera.znear;
  89644. }
  89645. lastNode = persCamera;
  89646. }
  89647. }
  89648. }
  89649. // Empty node
  89650. if (!node.jointName) {
  89651. if (node.babylonNode) {
  89652. return node.babylonNode;
  89653. }
  89654. else if (lastNode === null) {
  89655. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  89656. node.babylonNode = dummy;
  89657. lastNode = dummy;
  89658. }
  89659. }
  89660. if (lastNode !== null) {
  89661. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  89662. configureNodeFromMatrix(lastNode, node, parent);
  89663. }
  89664. else {
  89665. var translation = node.translation || [0, 0, 0];
  89666. var rotation = node.rotation || [0, 0, 0, 1];
  89667. var scale = node.scale || [1, 1, 1];
  89668. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  89669. }
  89670. lastNode.updateCache(true);
  89671. node.babylonNode = lastNode;
  89672. }
  89673. return lastNode;
  89674. };
  89675. /**
  89676. * Traverses nodes and creates them
  89677. */
  89678. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  89679. if (meshIncluded === void 0) { meshIncluded = false; }
  89680. var node = gltfRuntime.nodes[id];
  89681. var newNode = null;
  89682. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  89683. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  89684. meshIncluded = true;
  89685. }
  89686. else {
  89687. meshIncluded = false;
  89688. }
  89689. }
  89690. else {
  89691. meshIncluded = true;
  89692. }
  89693. if (!node.jointName && meshIncluded) {
  89694. newNode = importNode(gltfRuntime, node, id, parent);
  89695. if (newNode !== null) {
  89696. newNode.id = id;
  89697. newNode.parent = parent;
  89698. }
  89699. }
  89700. if (node.children) {
  89701. for (var i = 0; i < node.children.length; i++) {
  89702. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  89703. }
  89704. }
  89705. };
  89706. /**
  89707. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  89708. */
  89709. var postLoad = function (gltfRuntime) {
  89710. // Nodes
  89711. var currentScene = gltfRuntime.currentScene;
  89712. if (currentScene) {
  89713. for (var i = 0; i < currentScene.nodes.length; i++) {
  89714. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89715. }
  89716. }
  89717. else {
  89718. for (var thing in gltfRuntime.scenes) {
  89719. currentScene = gltfRuntime.scenes[thing];
  89720. for (var i = 0; i < currentScene.nodes.length; i++) {
  89721. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  89722. }
  89723. }
  89724. }
  89725. // Set animations
  89726. loadAnimations(gltfRuntime);
  89727. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  89728. var skeleton = gltfRuntime.scene.skeletons[i];
  89729. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  89730. }
  89731. };
  89732. /**
  89733. * onBind shaderrs callback to set uniforms and matrices
  89734. */
  89735. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  89736. var materialValues = material.values || technique.parameters;
  89737. for (var unif in unTreatedUniforms) {
  89738. var uniform = unTreatedUniforms[unif];
  89739. var type = uniform.type;
  89740. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  89741. if (uniform.semantic && !uniform.source && !uniform.node) {
  89742. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  89743. }
  89744. else if (uniform.semantic && (uniform.source || uniform.node)) {
  89745. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  89746. if (source === null) {
  89747. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  89748. }
  89749. if (source === null) {
  89750. continue;
  89751. }
  89752. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  89753. }
  89754. }
  89755. else {
  89756. var value = materialValues[technique.uniforms[unif]];
  89757. if (!value) {
  89758. continue;
  89759. }
  89760. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89761. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  89762. if (texture === null || texture === undefined) {
  89763. continue;
  89764. }
  89765. shaderMaterial.getEffect().setTexture(unif, texture);
  89766. }
  89767. else {
  89768. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  89769. }
  89770. }
  89771. }
  89772. onSuccess(shaderMaterial);
  89773. };
  89774. /**
  89775. * Prepare uniforms to send the only one time
  89776. * Loads the appropriate textures
  89777. */
  89778. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  89779. var materialValues = material.values || technique.parameters;
  89780. var techniqueUniforms = technique.uniforms;
  89781. /**
  89782. * Prepare values here (not matrices)
  89783. */
  89784. for (var unif in unTreatedUniforms) {
  89785. var uniform = unTreatedUniforms[unif];
  89786. var type = uniform.type;
  89787. var value = materialValues[techniqueUniforms[unif]];
  89788. if (value === undefined) {
  89789. // In case the value is the same for all materials
  89790. value = uniform.value;
  89791. }
  89792. if (!value) {
  89793. continue;
  89794. }
  89795. var onLoadTexture = function (uniformName) {
  89796. return function (texture) {
  89797. if (uniform.value && uniformName) {
  89798. // Static uniform
  89799. shaderMaterial.setTexture(uniformName, texture);
  89800. delete unTreatedUniforms[uniformName];
  89801. }
  89802. };
  89803. };
  89804. // Texture (sampler2D)
  89805. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  89806. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  89807. }
  89808. else {
  89809. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  89810. // Static uniform
  89811. delete unTreatedUniforms[unif];
  89812. }
  89813. }
  89814. }
  89815. };
  89816. /**
  89817. * Shader compilation failed
  89818. */
  89819. var onShaderCompileError = function (program, shaderMaterial, onError) {
  89820. return function (effect, error) {
  89821. shaderMaterial.dispose(true);
  89822. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  89823. };
  89824. };
  89825. /**
  89826. * Shader compilation success
  89827. */
  89828. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  89829. return function (_) {
  89830. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  89831. shaderMaterial.onBind = function (mesh) {
  89832. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  89833. };
  89834. };
  89835. };
  89836. /**
  89837. * Returns the appropriate uniform if already handled by babylon
  89838. */
  89839. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  89840. for (var unif in technique.uniforms) {
  89841. var uniform = technique.uniforms[unif];
  89842. var uniformParameter = technique.parameters[uniform];
  89843. if (tokenizer.currentIdentifier === unif) {
  89844. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  89845. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  89846. if (transformIndex !== -1) {
  89847. delete unTreatedUniforms[unif];
  89848. return babylonTransforms[transformIndex];
  89849. }
  89850. }
  89851. }
  89852. }
  89853. return tokenizer.currentIdentifier;
  89854. };
  89855. /**
  89856. * All shaders loaded. Create materials one by one
  89857. */
  89858. var importMaterials = function (gltfRuntime) {
  89859. // Create materials
  89860. for (var mat in gltfRuntime.materials) {
  89861. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  89862. }
  89863. };
  89864. /**
  89865. * Implementation of the base glTF spec
  89866. */
  89867. var GLTFLoaderBase = /** @class */ (function () {
  89868. function GLTFLoaderBase() {
  89869. }
  89870. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  89871. var gltfRuntime = {
  89872. extensions: {},
  89873. accessors: {},
  89874. buffers: {},
  89875. bufferViews: {},
  89876. meshes: {},
  89877. lights: {},
  89878. cameras: {},
  89879. nodes: {},
  89880. images: {},
  89881. textures: {},
  89882. shaders: {},
  89883. programs: {},
  89884. samplers: {},
  89885. techniques: {},
  89886. materials: {},
  89887. animations: {},
  89888. skins: {},
  89889. extensionsUsed: [],
  89890. scenes: {},
  89891. buffersCount: 0,
  89892. shaderscount: 0,
  89893. scene: scene,
  89894. rootUrl: rootUrl,
  89895. loadedBufferCount: 0,
  89896. loadedBufferViews: {},
  89897. loadedShaderCount: 0,
  89898. importOnlyMeshes: false,
  89899. dummyNodes: []
  89900. };
  89901. // Parse
  89902. if (parsedData.extensions) {
  89903. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  89904. }
  89905. if (parsedData.extensionsUsed) {
  89906. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  89907. }
  89908. if (parsedData.buffers) {
  89909. parseBuffers(parsedData.buffers, gltfRuntime);
  89910. }
  89911. if (parsedData.bufferViews) {
  89912. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  89913. }
  89914. if (parsedData.accessors) {
  89915. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  89916. }
  89917. if (parsedData.meshes) {
  89918. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  89919. }
  89920. if (parsedData.lights) {
  89921. parseObject(parsedData.lights, "lights", gltfRuntime);
  89922. }
  89923. if (parsedData.cameras) {
  89924. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  89925. }
  89926. if (parsedData.nodes) {
  89927. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  89928. }
  89929. if (parsedData.images) {
  89930. parseObject(parsedData.images, "images", gltfRuntime);
  89931. }
  89932. if (parsedData.textures) {
  89933. parseObject(parsedData.textures, "textures", gltfRuntime);
  89934. }
  89935. if (parsedData.shaders) {
  89936. parseShaders(parsedData.shaders, gltfRuntime);
  89937. }
  89938. if (parsedData.programs) {
  89939. parseObject(parsedData.programs, "programs", gltfRuntime);
  89940. }
  89941. if (parsedData.samplers) {
  89942. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  89943. }
  89944. if (parsedData.techniques) {
  89945. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  89946. }
  89947. if (parsedData.materials) {
  89948. parseObject(parsedData.materials, "materials", gltfRuntime);
  89949. }
  89950. if (parsedData.animations) {
  89951. parseObject(parsedData.animations, "animations", gltfRuntime);
  89952. }
  89953. if (parsedData.skins) {
  89954. parseObject(parsedData.skins, "skins", gltfRuntime);
  89955. }
  89956. if (parsedData.scenes) {
  89957. gltfRuntime.scenes = parsedData.scenes;
  89958. }
  89959. if (parsedData.scene && parsedData.scenes) {
  89960. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  89961. }
  89962. return gltfRuntime;
  89963. };
  89964. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  89965. var buffer = gltfRuntime.buffers[id];
  89966. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  89967. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  89968. }
  89969. else {
  89970. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  89971. if (request) {
  89972. onError(request.status + " " + request.statusText);
  89973. }
  89974. });
  89975. }
  89976. };
  89977. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  89978. var texture = gltfRuntime.textures[id];
  89979. if (!texture || !texture.source) {
  89980. onError("");
  89981. return;
  89982. }
  89983. if (texture.babylonTexture) {
  89984. onSuccess(null);
  89985. return;
  89986. }
  89987. var source = gltfRuntime.images[texture.source];
  89988. if (BABYLON.Tools.IsBase64(source.uri)) {
  89989. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  89990. }
  89991. else {
  89992. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  89993. if (request) {
  89994. onError(request.status + " " + request.statusText);
  89995. }
  89996. });
  89997. }
  89998. };
  89999. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90000. var texture = gltfRuntime.textures[id];
  90001. if (texture.babylonTexture) {
  90002. onSuccess(texture.babylonTexture);
  90003. return;
  90004. }
  90005. var sampler = gltfRuntime.samplers[texture.sampler];
  90006. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  90007. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  90008. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  90009. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  90010. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90011. var blob = new Blob([buffer]);
  90012. var blobURL = URL.createObjectURL(blob);
  90013. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  90014. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  90015. if (sampler.wrapS !== undefined) {
  90016. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  90017. }
  90018. if (sampler.wrapT !== undefined) {
  90019. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  90020. }
  90021. newTexture.name = id;
  90022. texture.babylonTexture = newTexture;
  90023. onSuccess(newTexture);
  90024. };
  90025. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90026. var shader = gltfRuntime.shaders[id];
  90027. if (BABYLON.Tools.IsBase64(shader.uri)) {
  90028. var shaderString = atob(shader.uri.split(",")[1]);
  90029. onSuccess(shaderString);
  90030. }
  90031. else {
  90032. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  90033. if (request) {
  90034. onError(request.status + " " + request.statusText);
  90035. }
  90036. });
  90037. }
  90038. };
  90039. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90040. var material = gltfRuntime.materials[id];
  90041. if (!material.technique) {
  90042. if (onError) {
  90043. onError("No technique found.");
  90044. }
  90045. return;
  90046. }
  90047. var technique = gltfRuntime.techniques[material.technique];
  90048. if (!technique) {
  90049. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90050. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  90051. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90052. onSuccess(defaultMaterial);
  90053. return;
  90054. }
  90055. var program = gltfRuntime.programs[technique.program];
  90056. var states = technique.states;
  90057. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  90058. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  90059. var newVertexShader = "";
  90060. var newPixelShader = "";
  90061. var vertexTokenizer = new Tokenizer(vertexShader);
  90062. var pixelTokenizer = new Tokenizer(pixelShader);
  90063. var unTreatedUniforms = {};
  90064. var uniforms = [];
  90065. var attributes = [];
  90066. var samplers = [];
  90067. // Fill uniform, sampler2D and attributes
  90068. for (var unif in technique.uniforms) {
  90069. var uniform = technique.uniforms[unif];
  90070. var uniformParameter = technique.parameters[uniform];
  90071. unTreatedUniforms[unif] = uniformParameter;
  90072. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  90073. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  90074. if (transformIndex !== -1) {
  90075. uniforms.push(babylonTransforms[transformIndex]);
  90076. delete unTreatedUniforms[unif];
  90077. }
  90078. else {
  90079. uniforms.push(unif);
  90080. }
  90081. }
  90082. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  90083. samplers.push(unif);
  90084. }
  90085. else {
  90086. uniforms.push(unif);
  90087. }
  90088. }
  90089. for (var attr in technique.attributes) {
  90090. var attribute = technique.attributes[attr];
  90091. var attributeParameter = technique.parameters[attribute];
  90092. if (attributeParameter.semantic) {
  90093. attributes.push(getAttribute(attributeParameter));
  90094. }
  90095. }
  90096. // Configure vertex shader
  90097. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  90098. var tokenType = vertexTokenizer.currentToken;
  90099. if (tokenType !== ETokenType.IDENTIFIER) {
  90100. newVertexShader += vertexTokenizer.currentString;
  90101. continue;
  90102. }
  90103. var foundAttribute = false;
  90104. for (var attr in technique.attributes) {
  90105. var attribute = technique.attributes[attr];
  90106. var attributeParameter = technique.parameters[attribute];
  90107. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  90108. newVertexShader += getAttribute(attributeParameter);
  90109. foundAttribute = true;
  90110. break;
  90111. }
  90112. }
  90113. if (foundAttribute) {
  90114. continue;
  90115. }
  90116. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  90117. }
  90118. // Configure pixel shader
  90119. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  90120. var tokenType = pixelTokenizer.currentToken;
  90121. if (tokenType !== ETokenType.IDENTIFIER) {
  90122. newPixelShader += pixelTokenizer.currentString;
  90123. continue;
  90124. }
  90125. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  90126. }
  90127. // Create shader material
  90128. var shaderPath = {
  90129. vertex: program.vertexShader + id,
  90130. fragment: program.fragmentShader + id
  90131. };
  90132. var options = {
  90133. attributes: attributes,
  90134. uniforms: uniforms,
  90135. samplers: samplers,
  90136. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  90137. };
  90138. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  90139. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  90140. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  90141. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  90142. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  90143. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90144. if (states && states.functions) {
  90145. var functions = states.functions;
  90146. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  90147. shaderMaterial.backFaceCulling = false;
  90148. }
  90149. var blendFunc = functions.blendFuncSeparate;
  90150. if (blendFunc) {
  90151. 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) {
  90152. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  90153. }
  90154. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90155. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  90156. }
  90157. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90158. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  90159. }
  90160. 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) {
  90161. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  90162. }
  90163. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  90164. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  90165. }
  90166. 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) {
  90167. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  90168. }
  90169. }
  90170. }
  90171. };
  90172. return GLTFLoaderBase;
  90173. }());
  90174. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  90175. /**
  90176. * glTF V1 Loader
  90177. */
  90178. var GLTFLoader = /** @class */ (function () {
  90179. function GLTFLoader() {
  90180. // #region Stubs for IGLTFLoader interface
  90181. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90182. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90183. this.compileMaterials = false;
  90184. this.useClipPlane = false;
  90185. this.compileShadowGenerators = false;
  90186. this.onDisposeObservable = new BABYLON.Observable();
  90187. this.onMeshLoadedObservable = new BABYLON.Observable();
  90188. this.onTextureLoadedObservable = new BABYLON.Observable();
  90189. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90190. this.onCompleteObservable = new BABYLON.Observable();
  90191. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90192. this.state = null;
  90193. }
  90194. GLTFLoader.RegisterExtension = function (extension) {
  90195. if (GLTFLoader.Extensions[extension.name]) {
  90196. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  90197. return;
  90198. }
  90199. GLTFLoader.Extensions[extension.name] = extension;
  90200. };
  90201. GLTFLoader.prototype.dispose = function () { };
  90202. // #endregion
  90203. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  90204. var _this = this;
  90205. scene.useRightHandedSystem = true;
  90206. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  90207. gltfRuntime.importOnlyMeshes = true;
  90208. if (meshesNames === "") {
  90209. gltfRuntime.importMeshesNames = [];
  90210. }
  90211. else if (typeof meshesNames === "string") {
  90212. gltfRuntime.importMeshesNames = [meshesNames];
  90213. }
  90214. else if (meshesNames && !(meshesNames instanceof Array)) {
  90215. gltfRuntime.importMeshesNames = [meshesNames];
  90216. }
  90217. else {
  90218. gltfRuntime.importMeshesNames = [];
  90219. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  90220. }
  90221. // Create nodes
  90222. _this._createNodes(gltfRuntime);
  90223. var meshes = new Array();
  90224. var skeletons = new Array();
  90225. // Fill arrays of meshes and skeletons
  90226. for (var nde in gltfRuntime.nodes) {
  90227. var node = gltfRuntime.nodes[nde];
  90228. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  90229. meshes.push(node.babylonNode);
  90230. }
  90231. }
  90232. for (var skl in gltfRuntime.skins) {
  90233. var skin = gltfRuntime.skins[skl];
  90234. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  90235. skeletons.push(skin.babylonSkeleton);
  90236. }
  90237. }
  90238. // Load buffers, shaders, materials, etc.
  90239. _this._loadBuffersAsync(gltfRuntime, function () {
  90240. _this._loadShadersAsync(gltfRuntime, function () {
  90241. importMaterials(gltfRuntime);
  90242. postLoad(gltfRuntime);
  90243. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  90244. onSuccess(meshes, [], skeletons);
  90245. }
  90246. });
  90247. }, onProgress);
  90248. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  90249. onSuccess(meshes, [], skeletons);
  90250. }
  90251. }, onError);
  90252. return true;
  90253. };
  90254. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  90255. var _this = this;
  90256. return new Promise(function (resolve, reject) {
  90257. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  90258. resolve({
  90259. meshes: meshes,
  90260. particleSystems: particleSystems,
  90261. skeletons: skeletons
  90262. });
  90263. }, onProgress, function (message) {
  90264. reject(new Error(message));
  90265. });
  90266. });
  90267. };
  90268. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  90269. var _this = this;
  90270. scene.useRightHandedSystem = true;
  90271. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  90272. // Load runtime extensios
  90273. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  90274. // Create nodes
  90275. _this._createNodes(gltfRuntime);
  90276. // Load buffers, shaders, materials, etc.
  90277. _this._loadBuffersAsync(gltfRuntime, function () {
  90278. _this._loadShadersAsync(gltfRuntime, function () {
  90279. importMaterials(gltfRuntime);
  90280. postLoad(gltfRuntime);
  90281. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  90282. onSuccess();
  90283. }
  90284. });
  90285. });
  90286. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  90287. onSuccess();
  90288. }
  90289. }, onError);
  90290. }, onError);
  90291. };
  90292. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  90293. var _this = this;
  90294. return new Promise(function (resolve, reject) {
  90295. _this._loadAsync(scene, data, rootUrl, function () {
  90296. resolve();
  90297. }, onProgress, function (message) {
  90298. reject(new Error(message));
  90299. });
  90300. });
  90301. };
  90302. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  90303. var hasShaders = false;
  90304. var processShader = function (sha, shader) {
  90305. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  90306. gltfRuntime.loadedShaderCount++;
  90307. if (shaderString) {
  90308. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  90309. }
  90310. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  90311. onload();
  90312. }
  90313. }, function () {
  90314. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  90315. });
  90316. };
  90317. for (var sha in gltfRuntime.shaders) {
  90318. hasShaders = true;
  90319. var shader = gltfRuntime.shaders[sha];
  90320. if (shader) {
  90321. processShader.bind(this, sha, shader)();
  90322. }
  90323. else {
  90324. BABYLON.Tools.Error("No shader named: " + sha);
  90325. }
  90326. }
  90327. if (!hasShaders) {
  90328. onload();
  90329. }
  90330. };
  90331. ;
  90332. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  90333. var hasBuffers = false;
  90334. var processBuffer = function (buf, buffer) {
  90335. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  90336. gltfRuntime.loadedBufferCount++;
  90337. if (bufferView) {
  90338. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  90339. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  90340. }
  90341. gltfRuntime.loadedBufferViews[buf] = bufferView;
  90342. }
  90343. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  90344. onLoad();
  90345. }
  90346. }, function () {
  90347. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  90348. });
  90349. };
  90350. for (var buf in gltfRuntime.buffers) {
  90351. hasBuffers = true;
  90352. var buffer = gltfRuntime.buffers[buf];
  90353. if (buffer) {
  90354. processBuffer.bind(this, buf, buffer)();
  90355. }
  90356. else {
  90357. BABYLON.Tools.Error("No buffer named: " + buf);
  90358. }
  90359. }
  90360. if (!hasBuffers) {
  90361. onLoad();
  90362. }
  90363. };
  90364. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  90365. var currentScene = gltfRuntime.currentScene;
  90366. if (currentScene) {
  90367. // Only one scene even if multiple scenes are defined
  90368. for (var i = 0; i < currentScene.nodes.length; i++) {
  90369. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90370. }
  90371. }
  90372. else {
  90373. // Load all scenes
  90374. for (var thing in gltfRuntime.scenes) {
  90375. currentScene = gltfRuntime.scenes[thing];
  90376. for (var i = 0; i < currentScene.nodes.length; i++) {
  90377. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  90378. }
  90379. }
  90380. }
  90381. };
  90382. GLTFLoader.Extensions = {};
  90383. return GLTFLoader;
  90384. }());
  90385. GLTF1.GLTFLoader = GLTFLoader;
  90386. ;
  90387. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  90388. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90389. })(BABYLON || (BABYLON = {}));
  90390. //# sourceMappingURL=babylon.glTFLoader.js.map
  90391. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90392. var BABYLON;
  90393. (function (BABYLON) {
  90394. var GLTF1;
  90395. (function (GLTF1) {
  90396. /**
  90397. * Utils functions for GLTF
  90398. */
  90399. var GLTFUtils = /** @class */ (function () {
  90400. function GLTFUtils() {
  90401. }
  90402. /**
  90403. * Sets the given "parameter" matrix
  90404. * @param scene: the {BABYLON.Scene} object
  90405. * @param source: the source node where to pick the matrix
  90406. * @param parameter: the GLTF technique parameter
  90407. * @param uniformName: the name of the shader's uniform
  90408. * @param shaderMaterial: the shader material
  90409. */
  90410. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  90411. var mat = null;
  90412. if (parameter.semantic === "MODEL") {
  90413. mat = source.getWorldMatrix();
  90414. }
  90415. else if (parameter.semantic === "PROJECTION") {
  90416. mat = scene.getProjectionMatrix();
  90417. }
  90418. else if (parameter.semantic === "VIEW") {
  90419. mat = scene.getViewMatrix();
  90420. }
  90421. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  90422. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  90423. }
  90424. else if (parameter.semantic === "MODELVIEW") {
  90425. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  90426. }
  90427. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  90428. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  90429. }
  90430. else if (parameter.semantic === "MODELINVERSE") {
  90431. mat = source.getWorldMatrix().invert();
  90432. }
  90433. else if (parameter.semantic === "VIEWINVERSE") {
  90434. mat = scene.getViewMatrix().invert();
  90435. }
  90436. else if (parameter.semantic === "PROJECTIONINVERSE") {
  90437. mat = scene.getProjectionMatrix().invert();
  90438. }
  90439. else if (parameter.semantic === "MODELVIEWINVERSE") {
  90440. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  90441. }
  90442. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  90443. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  90444. }
  90445. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  90446. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  90447. }
  90448. else {
  90449. debugger;
  90450. }
  90451. if (mat) {
  90452. switch (parameter.type) {
  90453. case GLTF1.EParameterType.FLOAT_MAT2:
  90454. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  90455. break;
  90456. case GLTF1.EParameterType.FLOAT_MAT3:
  90457. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  90458. break;
  90459. case GLTF1.EParameterType.FLOAT_MAT4:
  90460. shaderMaterial.setMatrix(uniformName, mat);
  90461. break;
  90462. default: break;
  90463. }
  90464. }
  90465. };
  90466. /**
  90467. * Sets the given "parameter" matrix
  90468. * @param shaderMaterial: the shader material
  90469. * @param uniform: the name of the shader's uniform
  90470. * @param value: the value of the uniform
  90471. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  90472. */
  90473. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  90474. switch (type) {
  90475. case GLTF1.EParameterType.FLOAT:
  90476. shaderMaterial.setFloat(uniform, value);
  90477. return true;
  90478. case GLTF1.EParameterType.FLOAT_VEC2:
  90479. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  90480. return true;
  90481. case GLTF1.EParameterType.FLOAT_VEC3:
  90482. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  90483. return true;
  90484. case GLTF1.EParameterType.FLOAT_VEC4:
  90485. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  90486. return true;
  90487. default: return false;
  90488. }
  90489. };
  90490. /**
  90491. * Returns the wrap mode of the texture
  90492. * @param mode: the mode value
  90493. */
  90494. GLTFUtils.GetWrapMode = function (mode) {
  90495. switch (mode) {
  90496. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  90497. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  90498. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90499. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  90500. }
  90501. };
  90502. /**
  90503. * Returns the byte stride giving an accessor
  90504. * @param accessor: the GLTF accessor objet
  90505. */
  90506. GLTFUtils.GetByteStrideFromType = function (accessor) {
  90507. // Needs this function since "byteStride" isn't requiered in glTF format
  90508. var type = accessor.type;
  90509. switch (type) {
  90510. case "VEC2": return 2;
  90511. case "VEC3": return 3;
  90512. case "VEC4": return 4;
  90513. case "MAT2": return 4;
  90514. case "MAT3": return 9;
  90515. case "MAT4": return 16;
  90516. default: return 1;
  90517. }
  90518. };
  90519. /**
  90520. * Returns the texture filter mode giving a mode value
  90521. * @param mode: the filter mode value
  90522. */
  90523. GLTFUtils.GetTextureFilterMode = function (mode) {
  90524. switch (mode) {
  90525. case GLTF1.ETextureFilterType.LINEAR:
  90526. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  90527. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  90528. case GLTF1.ETextureFilterType.NEAREST:
  90529. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  90530. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  90531. }
  90532. };
  90533. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  90534. var byteOffset = bufferView.byteOffset + byteOffset;
  90535. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  90536. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  90537. throw new Error("Buffer access is out of range");
  90538. }
  90539. var buffer = loadedBufferView.buffer;
  90540. byteOffset += loadedBufferView.byteOffset;
  90541. switch (componentType) {
  90542. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  90543. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  90544. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  90545. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  90546. default: return new Float32Array(buffer, byteOffset, byteLength);
  90547. }
  90548. };
  90549. /**
  90550. * Returns a buffer from its accessor
  90551. * @param gltfRuntime: the GLTF runtime
  90552. * @param accessor: the GLTF accessor
  90553. */
  90554. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  90555. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  90556. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  90557. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  90558. };
  90559. /**
  90560. * Decodes a buffer view into a string
  90561. * @param view: the buffer view
  90562. */
  90563. GLTFUtils.DecodeBufferToText = function (view) {
  90564. var result = "";
  90565. var length = view.byteLength;
  90566. for (var i = 0; i < length; ++i) {
  90567. result += String.fromCharCode(view[i]);
  90568. }
  90569. return result;
  90570. };
  90571. /**
  90572. * Returns the default material of gltf. Related to
  90573. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  90574. * @param scene: the Babylon.js scene
  90575. */
  90576. GLTFUtils.GetDefaultMaterial = function (scene) {
  90577. if (!GLTFUtils._DefaultMaterial) {
  90578. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  90579. "precision highp float;",
  90580. "",
  90581. "uniform mat4 worldView;",
  90582. "uniform mat4 projection;",
  90583. "",
  90584. "attribute vec3 position;",
  90585. "",
  90586. "void main(void)",
  90587. "{",
  90588. " gl_Position = projection * worldView * vec4(position, 1.0);",
  90589. "}"
  90590. ].join("\n");
  90591. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  90592. "precision highp float;",
  90593. "",
  90594. "uniform vec4 u_emission;",
  90595. "",
  90596. "void main(void)",
  90597. "{",
  90598. " gl_FragColor = u_emission;",
  90599. "}"
  90600. ].join("\n");
  90601. var shaderPath = {
  90602. vertex: "GLTFDefaultMaterial",
  90603. fragment: "GLTFDefaultMaterial"
  90604. };
  90605. var options = {
  90606. attributes: ["position"],
  90607. uniforms: ["worldView", "projection", "u_emission"],
  90608. samplers: new Array(),
  90609. needAlphaBlending: false
  90610. };
  90611. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  90612. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  90613. }
  90614. return GLTFUtils._DefaultMaterial;
  90615. };
  90616. // The GLTF default material
  90617. GLTFUtils._DefaultMaterial = null;
  90618. return GLTFUtils;
  90619. }());
  90620. GLTF1.GLTFUtils = GLTFUtils;
  90621. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90622. })(BABYLON || (BABYLON = {}));
  90623. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  90624. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90625. var BABYLON;
  90626. (function (BABYLON) {
  90627. var GLTF1;
  90628. (function (GLTF1) {
  90629. var GLTFLoaderExtension = /** @class */ (function () {
  90630. function GLTFLoaderExtension(name) {
  90631. this._name = name;
  90632. }
  90633. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  90634. get: function () {
  90635. return this._name;
  90636. },
  90637. enumerable: true,
  90638. configurable: true
  90639. });
  90640. /**
  90641. * Defines an override for loading the runtime
  90642. * Return true to stop further extensions from loading the runtime
  90643. */
  90644. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90645. return false;
  90646. };
  90647. /**
  90648. * Defines an onverride for creating gltf runtime
  90649. * Return true to stop further extensions from creating the runtime
  90650. */
  90651. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90652. return false;
  90653. };
  90654. /**
  90655. * Defines an override for loading buffers
  90656. * Return true to stop further extensions from loading this buffer
  90657. */
  90658. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90659. return false;
  90660. };
  90661. /**
  90662. * Defines an override for loading texture buffers
  90663. * Return true to stop further extensions from loading this texture data
  90664. */
  90665. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90666. return false;
  90667. };
  90668. /**
  90669. * Defines an override for creating textures
  90670. * Return true to stop further extensions from loading this texture
  90671. */
  90672. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90673. return false;
  90674. };
  90675. /**
  90676. * Defines an override for loading shader strings
  90677. * Return true to stop further extensions from loading this shader data
  90678. */
  90679. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90680. return false;
  90681. };
  90682. /**
  90683. * Defines an override for loading materials
  90684. * Return true to stop further extensions from loading this material
  90685. */
  90686. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90687. return false;
  90688. };
  90689. // ---------
  90690. // Utilities
  90691. // ---------
  90692. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90693. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90694. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  90695. }, function () {
  90696. setTimeout(function () {
  90697. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90698. });
  90699. });
  90700. };
  90701. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90702. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90703. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  90704. }, function () {
  90705. setTimeout(function () {
  90706. onSuccess();
  90707. });
  90708. });
  90709. };
  90710. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  90711. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90712. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90713. }, function () {
  90714. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  90715. });
  90716. };
  90717. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  90718. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  90719. };
  90720. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90721. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90722. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90723. }, function () {
  90724. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  90725. });
  90726. };
  90727. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90728. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90729. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90730. }, function () {
  90731. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  90732. });
  90733. };
  90734. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90735. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90736. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90737. }, function () {
  90738. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  90739. });
  90740. };
  90741. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  90742. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  90743. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90744. }, function () {
  90745. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  90746. });
  90747. };
  90748. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  90749. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  90750. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  90751. if (func(loaderExtension)) {
  90752. return;
  90753. }
  90754. }
  90755. defaultFunc();
  90756. };
  90757. return GLTFLoaderExtension;
  90758. }());
  90759. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  90760. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90761. })(BABYLON || (BABYLON = {}));
  90762. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  90763. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90764. var BABYLON;
  90765. (function (BABYLON) {
  90766. var GLTF1;
  90767. (function (GLTF1) {
  90768. var BinaryExtensionBufferName = "binary_glTF";
  90769. ;
  90770. ;
  90771. var GLTFBinaryExtension = /** @class */ (function (_super) {
  90772. __extends(GLTFBinaryExtension, _super);
  90773. function GLTFBinaryExtension() {
  90774. return _super.call(this, "KHR_binary_glTF") || this;
  90775. }
  90776. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  90777. var extensionsUsed = data.json.extensionsUsed;
  90778. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  90779. return false;
  90780. }
  90781. this._bin = data.bin;
  90782. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  90783. return true;
  90784. };
  90785. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90786. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  90787. return false;
  90788. }
  90789. if (id !== BinaryExtensionBufferName) {
  90790. return false;
  90791. }
  90792. onSuccess(this._bin);
  90793. return true;
  90794. };
  90795. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  90796. var texture = gltfRuntime.textures[id];
  90797. var source = gltfRuntime.images[texture.source];
  90798. if (!source.extensions || !(this.name in source.extensions)) {
  90799. return false;
  90800. }
  90801. var sourceExt = source.extensions[this.name];
  90802. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  90803. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90804. onSuccess(buffer);
  90805. return true;
  90806. };
  90807. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  90808. var shader = gltfRuntime.shaders[id];
  90809. if (!shader.extensions || !(this.name in shader.extensions)) {
  90810. return false;
  90811. }
  90812. var binaryExtensionShader = shader.extensions[this.name];
  90813. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  90814. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  90815. setTimeout(function () {
  90816. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  90817. onSuccess(shaderString);
  90818. });
  90819. return true;
  90820. };
  90821. return GLTFBinaryExtension;
  90822. }(GLTF1.GLTFLoaderExtension));
  90823. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  90824. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  90825. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90826. })(BABYLON || (BABYLON = {}));
  90827. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  90828. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90829. var BABYLON;
  90830. (function (BABYLON) {
  90831. var GLTF1;
  90832. (function (GLTF1) {
  90833. ;
  90834. ;
  90835. ;
  90836. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  90837. __extends(GLTFMaterialsCommonExtension, _super);
  90838. function GLTFMaterialsCommonExtension() {
  90839. return _super.call(this, "KHR_materials_common") || this;
  90840. }
  90841. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  90842. if (!gltfRuntime.extensions)
  90843. return false;
  90844. var extension = gltfRuntime.extensions[this.name];
  90845. if (!extension)
  90846. return false;
  90847. // Create lights
  90848. var lights = extension.lights;
  90849. if (lights) {
  90850. for (var thing in lights) {
  90851. var light = lights[thing];
  90852. switch (light.type) {
  90853. case "ambient":
  90854. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  90855. var ambient = light.ambient;
  90856. if (ambient) {
  90857. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  90858. }
  90859. break;
  90860. case "point":
  90861. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  90862. var point = light.point;
  90863. if (point) {
  90864. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  90865. }
  90866. break;
  90867. case "directional":
  90868. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  90869. var directional = light.directional;
  90870. if (directional) {
  90871. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  90872. }
  90873. break;
  90874. case "spot":
  90875. var spot = light.spot;
  90876. if (spot) {
  90877. 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);
  90878. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  90879. }
  90880. break;
  90881. default:
  90882. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  90883. break;
  90884. }
  90885. }
  90886. }
  90887. return false;
  90888. };
  90889. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  90890. var material = gltfRuntime.materials[id];
  90891. if (!material || !material.extensions)
  90892. return false;
  90893. var extension = material.extensions[this.name];
  90894. if (!extension)
  90895. return false;
  90896. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  90897. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  90898. if (extension.technique === "CONSTANT") {
  90899. standardMaterial.disableLighting = true;
  90900. }
  90901. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  90902. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  90903. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  90904. // Ambient
  90905. if (typeof extension.values.ambient === "string") {
  90906. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  90907. }
  90908. else {
  90909. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  90910. }
  90911. // Diffuse
  90912. if (typeof extension.values.diffuse === "string") {
  90913. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  90914. }
  90915. else {
  90916. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  90917. }
  90918. // Emission
  90919. if (typeof extension.values.emission === "string") {
  90920. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  90921. }
  90922. else {
  90923. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  90924. }
  90925. // Specular
  90926. if (typeof extension.values.specular === "string") {
  90927. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  90928. }
  90929. else {
  90930. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  90931. }
  90932. return true;
  90933. };
  90934. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  90935. // Create buffer from texture url
  90936. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  90937. // Create texture from buffer
  90938. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  90939. }, onError);
  90940. };
  90941. return GLTFMaterialsCommonExtension;
  90942. }(GLTF1.GLTFLoaderExtension));
  90943. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  90944. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  90945. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  90946. })(BABYLON || (BABYLON = {}));
  90947. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  90948. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90949. var BABYLON;
  90950. (function (BABYLON) {
  90951. var GLTF2;
  90952. (function (GLTF2) {
  90953. var ArrayItem = /** @class */ (function () {
  90954. function ArrayItem() {
  90955. }
  90956. ArrayItem.Assign = function (values) {
  90957. if (values) {
  90958. for (var index = 0; index < values.length; index++) {
  90959. values[index]._index = index;
  90960. }
  90961. }
  90962. };
  90963. return ArrayItem;
  90964. }());
  90965. GLTF2.ArrayItem = ArrayItem;
  90966. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  90967. })(BABYLON || (BABYLON = {}));
  90968. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  90969. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90970. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  90971. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  90972. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  90973. var BABYLON;
  90974. (function (BABYLON) {
  90975. var GLTF2;
  90976. (function (GLTF2) {
  90977. var GLTFLoader = /** @class */ (function () {
  90978. function GLTFLoader() {
  90979. this._completePromises = new Array();
  90980. this._disposed = false;
  90981. this._state = null;
  90982. this._extensions = {};
  90983. this._defaultSampler = {};
  90984. this._requests = new Array();
  90985. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  90986. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  90987. this.compileMaterials = false;
  90988. this.useClipPlane = false;
  90989. this.compileShadowGenerators = false;
  90990. this.onDisposeObservable = new BABYLON.Observable();
  90991. this.onMeshLoadedObservable = new BABYLON.Observable();
  90992. this.onTextureLoadedObservable = new BABYLON.Observable();
  90993. this.onMaterialLoadedObservable = new BABYLON.Observable();
  90994. this.onExtensionLoadedObservable = new BABYLON.Observable();
  90995. this.onCompleteObservable = new BABYLON.Observable();
  90996. }
  90997. GLTFLoader._Register = function (name, factory) {
  90998. if (GLTFLoader._Factories[name]) {
  90999. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  91000. return;
  91001. }
  91002. GLTFLoader._Factories[name] = factory;
  91003. // Keep the order of registration so that extensions registered first are called first.
  91004. GLTFLoader._Names.push(name);
  91005. };
  91006. Object.defineProperty(GLTFLoader.prototype, "state", {
  91007. get: function () {
  91008. return this._state;
  91009. },
  91010. enumerable: true,
  91011. configurable: true
  91012. });
  91013. GLTFLoader.prototype.dispose = function () {
  91014. if (this._disposed) {
  91015. return;
  91016. }
  91017. this._disposed = true;
  91018. this.onDisposeObservable.notifyObservers(this);
  91019. this.onDisposeObservable.clear();
  91020. this._clear();
  91021. };
  91022. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  91023. var _this = this;
  91024. return Promise.resolve().then(function () {
  91025. var nodes = null;
  91026. if (meshesNames) {
  91027. var nodeMap_1 = {};
  91028. if (_this._gltf.nodes) {
  91029. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  91030. var node = _a[_i];
  91031. if (node.name) {
  91032. nodeMap_1[node.name] = node;
  91033. }
  91034. }
  91035. }
  91036. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  91037. nodes = names.map(function (name) {
  91038. var node = nodeMap_1[name];
  91039. if (!node) {
  91040. throw new Error("Failed to find node " + name);
  91041. }
  91042. return node;
  91043. });
  91044. }
  91045. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  91046. return {
  91047. meshes: _this._getMeshes(),
  91048. particleSystems: [],
  91049. skeletons: _this._getSkeletons(),
  91050. };
  91051. });
  91052. });
  91053. };
  91054. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  91055. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  91056. };
  91057. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  91058. var _this = this;
  91059. return Promise.resolve().then(function () {
  91060. _this._loadExtensions();
  91061. _this._babylonScene = scene;
  91062. _this._rootUrl = rootUrl;
  91063. _this._progressCallback = onProgress;
  91064. _this._state = BABYLON.GLTFLoaderState.Loading;
  91065. _this._loadData(data);
  91066. var promises = new Array();
  91067. if (nodes) {
  91068. promises.push(_this._loadNodesAsync(nodes));
  91069. }
  91070. else {
  91071. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  91072. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  91073. }
  91074. if (_this.compileMaterials) {
  91075. promises.push(_this._compileMaterialsAsync());
  91076. }
  91077. if (_this.compileShadowGenerators) {
  91078. promises.push(_this._compileShadowGeneratorsAsync());
  91079. }
  91080. return Promise.all(promises).then(function () {
  91081. _this._state = BABYLON.GLTFLoaderState.Ready;
  91082. _this._startAnimations();
  91083. BABYLON.Tools.SetImmediate(function () {
  91084. if (!_this._disposed) {
  91085. Promise.all(_this._completePromises).then(function () {
  91086. _this._state = BABYLON.GLTFLoaderState.Complete;
  91087. _this.onCompleteObservable.notifyObservers(_this);
  91088. _this.onCompleteObservable.clear();
  91089. _this._clear();
  91090. }).catch(function (error) {
  91091. BABYLON.Tools.Error("glTF Loader: " + error.message);
  91092. _this._clear();
  91093. });
  91094. }
  91095. });
  91096. });
  91097. }).catch(function (error) {
  91098. BABYLON.Tools.Error("glTF Loader: " + error.message);
  91099. _this._clear();
  91100. throw error;
  91101. });
  91102. };
  91103. GLTFLoader.prototype._loadExtensions = function () {
  91104. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  91105. var name_1 = _a[_i];
  91106. var extension = GLTFLoader._Factories[name_1](this);
  91107. this._extensions[name_1] = extension;
  91108. this.onExtensionLoadedObservable.notifyObservers(extension);
  91109. }
  91110. this.onExtensionLoadedObservable.clear();
  91111. };
  91112. GLTFLoader.prototype._loadData = function (data) {
  91113. this._gltf = data.json;
  91114. this._setupData();
  91115. if (data.bin) {
  91116. var buffers = this._gltf.buffers;
  91117. if (buffers && buffers[0] && !buffers[0].uri) {
  91118. var binaryBuffer = buffers[0];
  91119. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  91120. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  91121. }
  91122. binaryBuffer._data = Promise.resolve(data.bin);
  91123. }
  91124. else {
  91125. BABYLON.Tools.Warn("Unexpected BIN chunk");
  91126. }
  91127. }
  91128. };
  91129. GLTFLoader.prototype._setupData = function () {
  91130. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  91131. GLTF2.ArrayItem.Assign(this._gltf.animations);
  91132. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  91133. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  91134. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  91135. GLTF2.ArrayItem.Assign(this._gltf.images);
  91136. GLTF2.ArrayItem.Assign(this._gltf.materials);
  91137. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  91138. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  91139. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  91140. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  91141. GLTF2.ArrayItem.Assign(this._gltf.skins);
  91142. GLTF2.ArrayItem.Assign(this._gltf.textures);
  91143. if (this._gltf.nodes) {
  91144. var nodeParents = {};
  91145. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  91146. var node = _a[_i];
  91147. if (node.children) {
  91148. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  91149. var index = _c[_b];
  91150. nodeParents[index] = node._index;
  91151. }
  91152. }
  91153. }
  91154. var rootNode = this._createRootNode();
  91155. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  91156. var node = _e[_d];
  91157. var parentIndex = nodeParents[node._index];
  91158. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  91159. }
  91160. }
  91161. };
  91162. GLTFLoader.prototype._createRootNode = function () {
  91163. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  91164. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  91165. switch (this.coordinateSystemMode) {
  91166. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  91167. if (!this._babylonScene.useRightHandedSystem) {
  91168. rootNode.rotation = [0, 1, 0, 0];
  91169. rootNode.scale = [1, 1, -1];
  91170. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  91171. }
  91172. break;
  91173. }
  91174. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  91175. this._babylonScene.useRightHandedSystem = true;
  91176. break;
  91177. }
  91178. default: {
  91179. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  91180. }
  91181. }
  91182. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  91183. return rootNode;
  91184. };
  91185. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  91186. var promises = new Array();
  91187. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  91188. var node = nodes_1[_i];
  91189. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  91190. }
  91191. promises.push(this._loadAnimationsAsync());
  91192. return Promise.all(promises).then(function () { });
  91193. };
  91194. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  91195. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  91196. if (promise) {
  91197. return promise;
  91198. }
  91199. var promises = new Array();
  91200. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  91201. var index = _a[_i];
  91202. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  91203. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  91204. }
  91205. promises.push(this._loadAnimationsAsync());
  91206. return Promise.all(promises).then(function () { });
  91207. };
  91208. GLTFLoader.prototype._getMeshes = function () {
  91209. var meshes = new Array();
  91210. // Root mesh is always first.
  91211. meshes.push(this._rootBabylonMesh);
  91212. var nodes = this._gltf.nodes;
  91213. if (nodes) {
  91214. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  91215. var node = nodes_2[_i];
  91216. if (node._babylonMesh) {
  91217. meshes.push(node._babylonMesh);
  91218. }
  91219. if (node._primitiveBabylonMeshes) {
  91220. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  91221. var babylonMesh = _b[_a];
  91222. meshes.push(babylonMesh);
  91223. }
  91224. }
  91225. }
  91226. }
  91227. return meshes;
  91228. };
  91229. GLTFLoader.prototype._getSkeletons = function () {
  91230. var skeletons = new Array();
  91231. var skins = this._gltf.skins;
  91232. if (skins) {
  91233. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  91234. var skin = skins_1[_i];
  91235. if (skin._babylonSkeleton) {
  91236. skeletons.push(skin._babylonSkeleton);
  91237. }
  91238. }
  91239. }
  91240. return skeletons;
  91241. };
  91242. GLTFLoader.prototype._startAnimations = function () {
  91243. var animations = this._gltf.animations;
  91244. if (!animations) {
  91245. return;
  91246. }
  91247. switch (this.animationStartMode) {
  91248. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  91249. // do nothing
  91250. break;
  91251. }
  91252. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  91253. var animation = animations[0];
  91254. animation._babylonAnimationGroup.start(true);
  91255. break;
  91256. }
  91257. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  91258. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  91259. var animation = animations_1[_i];
  91260. animation._babylonAnimationGroup.start(true);
  91261. }
  91262. break;
  91263. }
  91264. default: {
  91265. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  91266. return;
  91267. }
  91268. }
  91269. };
  91270. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  91271. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  91272. if (promise) {
  91273. return promise;
  91274. }
  91275. if (node._babylonMesh) {
  91276. throw new Error(context + ": Invalid recursive node hierarchy");
  91277. }
  91278. var promises = new Array();
  91279. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  91280. node._babylonMesh = babylonMesh;
  91281. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91282. node._babylonAnimationTargets.push(babylonMesh);
  91283. GLTFLoader._LoadTransform(node, babylonMesh);
  91284. if (node.mesh != undefined) {
  91285. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  91286. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  91287. }
  91288. if (node.children) {
  91289. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  91290. var index = _a[_i];
  91291. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  91292. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  91293. }
  91294. }
  91295. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91296. return Promise.all(promises).then(function () { });
  91297. };
  91298. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  91299. // TODO: instancing
  91300. var promises = new Array();
  91301. var primitives = mesh.primitives;
  91302. if (!primitives || primitives.length === 0) {
  91303. throw new Error(context + ": Primitives are missing");
  91304. }
  91305. GLTF2.ArrayItem.Assign(primitives);
  91306. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  91307. var primitive = primitives_1[_i];
  91308. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  91309. }
  91310. if (node.skin != undefined) {
  91311. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  91312. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  91313. }
  91314. return Promise.all(promises).then(function () {
  91315. if (node._primitiveBabylonMeshes) {
  91316. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91317. var primitiveBabylonMesh = _a[_i];
  91318. primitiveBabylonMesh._refreshBoundingInfo(true);
  91319. }
  91320. }
  91321. });
  91322. };
  91323. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  91324. var _this = this;
  91325. var promises = new Array();
  91326. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  91327. babylonMesh.setEnabled(false);
  91328. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  91329. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  91330. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  91331. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  91332. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  91333. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  91334. }));
  91335. if (primitive.material == undefined) {
  91336. babylonMesh.material = this._getDefaultMaterial();
  91337. }
  91338. else {
  91339. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  91340. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  91341. }
  91342. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  91343. return Promise.all(promises).then(function () {
  91344. babylonMesh.setEnabled(true);
  91345. });
  91346. };
  91347. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  91348. var _this = this;
  91349. var attributes = primitive.attributes;
  91350. if (!attributes) {
  91351. throw new Error(context + ": Attributes are missing");
  91352. }
  91353. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  91354. // TODO: handle other primitive modes
  91355. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  91356. }
  91357. var promises = new Array();
  91358. var babylonVertexData = new BABYLON.VertexData();
  91359. if (primitive.indices == undefined) {
  91360. var positionAccessorIndex = attributes["POSITION"];
  91361. if (positionAccessorIndex != undefined) {
  91362. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  91363. babylonVertexData.indices = new Uint32Array(accessor.count);
  91364. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  91365. babylonVertexData.indices[i] = i;
  91366. }
  91367. }
  91368. }
  91369. else {
  91370. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  91371. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  91372. babylonVertexData.indices = data;
  91373. }));
  91374. }
  91375. var loadAttribute = function (attribute, kind) {
  91376. if (attributes[attribute] == undefined) {
  91377. return;
  91378. }
  91379. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  91380. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  91381. babylonMesh._delayInfo.push(kind);
  91382. }
  91383. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91384. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91385. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  91386. if (attribute === "COLOR_0") {
  91387. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  91388. babylonMesh.hasVertexAlpha = true;
  91389. if (accessor.type === "VEC3") {
  91390. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  91391. }
  91392. }
  91393. babylonVertexData.set(attributeData, kind);
  91394. }));
  91395. };
  91396. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  91397. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  91398. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  91399. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  91400. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  91401. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  91402. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  91403. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  91404. return Promise.all(promises).then(function () {
  91405. return babylonVertexData;
  91406. });
  91407. };
  91408. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  91409. if (!primitive.targets) {
  91410. return;
  91411. }
  91412. if (node._numMorphTargets == undefined) {
  91413. node._numMorphTargets = primitive.targets.length;
  91414. }
  91415. else if (primitive.targets.length !== node._numMorphTargets) {
  91416. throw new Error(context + ": Primitives do not have the same number of targets");
  91417. }
  91418. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  91419. for (var index = 0; index < primitive.targets.length; index++) {
  91420. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  91421. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  91422. // TODO: tell the target whether it has positions, normals, tangents
  91423. }
  91424. };
  91425. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  91426. if (!primitive.targets) {
  91427. return Promise.resolve();
  91428. }
  91429. var promises = new Array();
  91430. var morphTargetManager = babylonMesh.morphTargetManager;
  91431. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  91432. var babylonMorphTarget = morphTargetManager.getTarget(index);
  91433. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  91434. }
  91435. return Promise.all(promises).then(function () { });
  91436. };
  91437. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  91438. var _this = this;
  91439. var promises = new Array();
  91440. var loadAttribute = function (attribute, setData) {
  91441. if (attributes[attribute] == undefined) {
  91442. return;
  91443. }
  91444. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  91445. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91446. setData(data);
  91447. }));
  91448. };
  91449. loadAttribute("POSITION", function (data) {
  91450. if (babylonVertexData.positions) {
  91451. for (var i = 0; i < data.length; i++) {
  91452. data[i] += babylonVertexData.positions[i];
  91453. }
  91454. babylonMorphTarget.setPositions(data);
  91455. }
  91456. });
  91457. loadAttribute("NORMAL", function (data) {
  91458. if (babylonVertexData.normals) {
  91459. for (var i = 0; i < data.length; i++) {
  91460. data[i] += babylonVertexData.normals[i];
  91461. }
  91462. babylonMorphTarget.setNormals(data);
  91463. }
  91464. });
  91465. loadAttribute("TANGENT", function (data) {
  91466. if (babylonVertexData.tangents) {
  91467. // Tangent data for morph targets is stored as xyz delta.
  91468. // The vertexData.tangent is stored as xyzw.
  91469. // So we need to skip every fourth vertexData.tangent.
  91470. for (var i = 0, j = 0; i < data.length; i++) {
  91471. data[i] += babylonVertexData.tangents[j++];
  91472. if ((i + 1) % 3 == 0) {
  91473. j++;
  91474. }
  91475. }
  91476. babylonMorphTarget.setTangents(data);
  91477. }
  91478. });
  91479. return Promise.all(promises).then(function () { });
  91480. };
  91481. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  91482. if (accessor.componentType == 5126 /* FLOAT */) {
  91483. return data;
  91484. }
  91485. var factor = 1;
  91486. if (accessor.normalized) {
  91487. switch (accessor.componentType) {
  91488. case 5121 /* UNSIGNED_BYTE */: {
  91489. factor = 1 / 255;
  91490. break;
  91491. }
  91492. case 5123 /* UNSIGNED_SHORT */: {
  91493. factor = 1 / 65535;
  91494. break;
  91495. }
  91496. default: {
  91497. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91498. }
  91499. }
  91500. }
  91501. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  91502. for (var i = 0; i < result.length; i++) {
  91503. result[i] = data[i] * factor;
  91504. }
  91505. return result;
  91506. };
  91507. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  91508. var result = new Float32Array(data.length / 3 * 4);
  91509. var offset = 0;
  91510. for (var i = 0; i < result.length; i++) {
  91511. if ((i + 1) % 4 === 0) {
  91512. result[i] = 1;
  91513. }
  91514. else {
  91515. result[i] = data[offset++];
  91516. }
  91517. }
  91518. return result;
  91519. };
  91520. GLTFLoader._LoadTransform = function (node, babylonNode) {
  91521. var position = BABYLON.Vector3.Zero();
  91522. var rotation = BABYLON.Quaternion.Identity();
  91523. var scaling = BABYLON.Vector3.One();
  91524. if (node.matrix) {
  91525. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  91526. matrix.decompose(scaling, rotation, position);
  91527. }
  91528. else {
  91529. if (node.translation)
  91530. position = BABYLON.Vector3.FromArray(node.translation);
  91531. if (node.rotation)
  91532. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  91533. if (node.scale)
  91534. scaling = BABYLON.Vector3.FromArray(node.scale);
  91535. }
  91536. babylonNode.position = position;
  91537. babylonNode.rotationQuaternion = rotation;
  91538. babylonNode.scaling = scaling;
  91539. };
  91540. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  91541. var _this = this;
  91542. var assignSkeleton = function () {
  91543. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91544. var babylonMesh = _a[_i];
  91545. babylonMesh.skeleton = skin._babylonSkeleton;
  91546. }
  91547. node._babylonMesh.parent = _this._rootBabylonMesh;
  91548. node._babylonMesh.position = BABYLON.Vector3.Zero();
  91549. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  91550. node._babylonMesh.scaling = BABYLON.Vector3.One();
  91551. };
  91552. if (skin._loaded) {
  91553. assignSkeleton();
  91554. return skin._loaded;
  91555. }
  91556. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  91557. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  91558. var skeletonId = "skeleton" + skin._index;
  91559. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  91560. skin._babylonSkeleton = babylonSkeleton;
  91561. _this._loadBones(context, skin, inverseBindMatricesData);
  91562. assignSkeleton();
  91563. }));
  91564. };
  91565. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  91566. if (skin.inverseBindMatrices == undefined) {
  91567. return Promise.resolve(null);
  91568. }
  91569. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  91570. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  91571. return data;
  91572. });
  91573. };
  91574. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  91575. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  91576. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  91577. node._babylonAnimationTargets.push(babylonBone);
  91578. return babylonBone;
  91579. };
  91580. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  91581. var babylonBones = {};
  91582. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  91583. var index = _a[_i];
  91584. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  91585. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  91586. }
  91587. };
  91588. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  91589. var babylonBone = babylonBones[node._index];
  91590. if (babylonBone) {
  91591. return babylonBone;
  91592. }
  91593. var boneIndex = skin.joints.indexOf(node._index);
  91594. var baseMatrix = BABYLON.Matrix.Identity();
  91595. if (inverseBindMatricesData && boneIndex !== -1) {
  91596. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  91597. baseMatrix.invertToRef(baseMatrix);
  91598. }
  91599. var babylonParentBone = null;
  91600. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  91601. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  91602. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  91603. }
  91604. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  91605. babylonBones[node._index] = babylonBone;
  91606. return babylonBone;
  91607. };
  91608. GLTFLoader.prototype._getNodeMatrix = function (node) {
  91609. return node.matrix ?
  91610. BABYLON.Matrix.FromArray(node.matrix) :
  91611. 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());
  91612. };
  91613. GLTFLoader.prototype._loadAnimationsAsync = function () {
  91614. var animations = this._gltf.animations;
  91615. if (!animations) {
  91616. return Promise.resolve();
  91617. }
  91618. var promises = new Array();
  91619. for (var index = 0; index < animations.length; index++) {
  91620. var animation = animations[index];
  91621. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  91622. }
  91623. return Promise.all(promises).then(function () { });
  91624. };
  91625. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  91626. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  91627. animation._babylonAnimationGroup = babylonAnimationGroup;
  91628. var promises = new Array();
  91629. GLTF2.ArrayItem.Assign(animation.channels);
  91630. GLTF2.ArrayItem.Assign(animation.samplers);
  91631. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  91632. var channel = _a[_i];
  91633. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  91634. }
  91635. return Promise.all(promises).then(function () {
  91636. babylonAnimationGroup.normalize();
  91637. });
  91638. };
  91639. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  91640. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  91641. if (!targetNode._babylonMesh) {
  91642. return Promise.resolve();
  91643. }
  91644. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  91645. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  91646. var targetPath;
  91647. var animationType;
  91648. switch (channel.target.path) {
  91649. case "translation" /* TRANSLATION */: {
  91650. targetPath = "position";
  91651. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91652. break;
  91653. }
  91654. case "rotation" /* ROTATION */: {
  91655. targetPath = "rotationQuaternion";
  91656. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  91657. break;
  91658. }
  91659. case "scale" /* SCALE */: {
  91660. targetPath = "scaling";
  91661. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  91662. break;
  91663. }
  91664. case "weights" /* WEIGHTS */: {
  91665. targetPath = "influence";
  91666. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  91667. break;
  91668. }
  91669. default: {
  91670. throw new Error(context + ": Invalid target path " + channel.target.path);
  91671. }
  91672. }
  91673. var outputBufferOffset = 0;
  91674. var getNextOutputValue;
  91675. switch (targetPath) {
  91676. case "position": {
  91677. getNextOutputValue = function () {
  91678. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91679. outputBufferOffset += 3;
  91680. return value;
  91681. };
  91682. break;
  91683. }
  91684. case "rotationQuaternion": {
  91685. getNextOutputValue = function () {
  91686. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  91687. outputBufferOffset += 4;
  91688. return value;
  91689. };
  91690. break;
  91691. }
  91692. case "scaling": {
  91693. getNextOutputValue = function () {
  91694. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  91695. outputBufferOffset += 3;
  91696. return value;
  91697. };
  91698. break;
  91699. }
  91700. case "influence": {
  91701. getNextOutputValue = function () {
  91702. var value = new Array(targetNode._numMorphTargets);
  91703. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  91704. value[i] = data.output[outputBufferOffset++];
  91705. }
  91706. return value;
  91707. };
  91708. break;
  91709. }
  91710. }
  91711. var getNextKey;
  91712. switch (data.interpolation) {
  91713. case "STEP" /* STEP */: {
  91714. getNextKey = function (frameIndex) { return ({
  91715. frame: data.input[frameIndex],
  91716. value: getNextOutputValue(),
  91717. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  91718. }); };
  91719. break;
  91720. }
  91721. case "LINEAR" /* LINEAR */: {
  91722. getNextKey = function (frameIndex) { return ({
  91723. frame: data.input[frameIndex],
  91724. value: getNextOutputValue()
  91725. }); };
  91726. break;
  91727. }
  91728. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91729. getNextKey = function (frameIndex) { return ({
  91730. frame: data.input[frameIndex],
  91731. inTangent: getNextOutputValue(),
  91732. value: getNextOutputValue(),
  91733. outTangent: getNextOutputValue()
  91734. }); };
  91735. break;
  91736. }
  91737. }
  91738. var keys;
  91739. if (data.input.length === 1) {
  91740. var key = getNextKey(0);
  91741. keys = [
  91742. { frame: key.frame, value: key.value },
  91743. { frame: key.frame + 1, value: key.value }
  91744. ];
  91745. }
  91746. else {
  91747. keys = new Array(data.input.length);
  91748. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  91749. keys[frameIndex] = getNextKey(frameIndex);
  91750. }
  91751. }
  91752. if (targetPath === "influence") {
  91753. var _loop_1 = function (targetIndex) {
  91754. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91755. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91756. babylonAnimation.setKeys(keys.map(function (key) { return ({
  91757. frame: key.frame,
  91758. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  91759. value: key.value[targetIndex],
  91760. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  91761. }); }));
  91762. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  91763. var babylonMesh = _a[_i];
  91764. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  91765. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  91766. }
  91767. };
  91768. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  91769. _loop_1(targetIndex);
  91770. }
  91771. }
  91772. else {
  91773. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  91774. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  91775. babylonAnimation.setKeys(keys);
  91776. if (targetNode._babylonAnimationTargets) {
  91777. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  91778. var target = _a[_i];
  91779. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  91780. }
  91781. }
  91782. }
  91783. });
  91784. };
  91785. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  91786. if (sampler._data) {
  91787. return sampler._data;
  91788. }
  91789. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  91790. switch (interpolation) {
  91791. case "STEP" /* STEP */:
  91792. case "LINEAR" /* LINEAR */:
  91793. case "CUBICSPLINE" /* CUBICSPLINE */: {
  91794. break;
  91795. }
  91796. default: {
  91797. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  91798. }
  91799. }
  91800. var inputData;
  91801. var outputData;
  91802. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  91803. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  91804. sampler._data = Promise.all([
  91805. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  91806. inputData = data;
  91807. }),
  91808. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  91809. outputData = data;
  91810. })
  91811. ]).then(function () {
  91812. return {
  91813. input: inputData,
  91814. interpolation: interpolation,
  91815. output: outputData,
  91816. };
  91817. });
  91818. return sampler._data;
  91819. };
  91820. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  91821. if (buffer._data) {
  91822. return buffer._data;
  91823. }
  91824. if (!buffer.uri) {
  91825. throw new Error(context + ": Uri is missing");
  91826. }
  91827. buffer._data = this._loadUriAsync(context, buffer.uri);
  91828. return buffer._data;
  91829. };
  91830. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  91831. if (bufferView._data) {
  91832. return bufferView._data;
  91833. }
  91834. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  91835. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  91836. try {
  91837. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  91838. }
  91839. catch (e) {
  91840. throw new Error(context + ": " + e.message);
  91841. }
  91842. });
  91843. return bufferView._data;
  91844. };
  91845. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  91846. var _this = this;
  91847. if (accessor.sparse) {
  91848. throw new Error(context + ": Sparse accessors are not currently supported");
  91849. }
  91850. if (accessor._data) {
  91851. return accessor._data;
  91852. }
  91853. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  91854. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  91855. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  91856. var byteOffset = accessor.byteOffset || 0;
  91857. var byteStride = bufferView.byteStride;
  91858. if (byteStride === 0) {
  91859. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  91860. }
  91861. try {
  91862. switch (accessor.componentType) {
  91863. case 5120 /* BYTE */: {
  91864. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91865. }
  91866. case 5121 /* UNSIGNED_BYTE */: {
  91867. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91868. }
  91869. case 5122 /* SHORT */: {
  91870. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91871. }
  91872. case 5123 /* UNSIGNED_SHORT */: {
  91873. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91874. }
  91875. case 5125 /* UNSIGNED_INT */: {
  91876. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91877. }
  91878. case 5126 /* FLOAT */: {
  91879. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  91880. }
  91881. default: {
  91882. throw new Error(context + ": Invalid component type " + accessor.componentType);
  91883. }
  91884. }
  91885. }
  91886. catch (e) {
  91887. throw new Error(context + ": " + e);
  91888. }
  91889. });
  91890. return accessor._data;
  91891. };
  91892. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  91893. byteOffset += data.byteOffset;
  91894. var targetLength = count * numComponents;
  91895. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  91896. return new typedArray(data.buffer, byteOffset, targetLength);
  91897. }
  91898. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  91899. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  91900. var targetBuffer = new typedArray(targetLength);
  91901. var sourceIndex = 0;
  91902. var targetIndex = 0;
  91903. while (targetIndex < targetLength) {
  91904. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  91905. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  91906. targetIndex++;
  91907. }
  91908. sourceIndex += elementStride;
  91909. }
  91910. return targetBuffer;
  91911. };
  91912. GLTFLoader.prototype._getDefaultMaterial = function () {
  91913. var id = "__gltf_default";
  91914. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  91915. if (!babylonMaterial) {
  91916. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  91917. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  91918. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91919. babylonMaterial.metallic = 1;
  91920. babylonMaterial.roughness = 1;
  91921. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91922. }
  91923. return babylonMaterial;
  91924. };
  91925. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  91926. var promises = new Array();
  91927. var babylonMaterial = material._babylonMaterial;
  91928. // Ensure metallic workflow
  91929. babylonMaterial.metallic = 1;
  91930. babylonMaterial.roughness = 1;
  91931. var properties = material.pbrMetallicRoughness;
  91932. if (properties) {
  91933. if (properties.baseColorFactor) {
  91934. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  91935. babylonMaterial.alpha = properties.baseColorFactor[3];
  91936. }
  91937. else {
  91938. babylonMaterial.albedoColor = BABYLON.Color3.White();
  91939. }
  91940. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  91941. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  91942. if (properties.baseColorTexture) {
  91943. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  91944. babylonMaterial.albedoTexture = texture;
  91945. }));
  91946. }
  91947. if (properties.metallicRoughnessTexture) {
  91948. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  91949. babylonMaterial.metallicTexture = texture;
  91950. }));
  91951. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  91952. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  91953. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  91954. }
  91955. }
  91956. this._loadMaterialAlphaProperties(context, material);
  91957. return Promise.all(promises).then(function () { });
  91958. };
  91959. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  91960. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  91961. if (promise) {
  91962. return promise;
  91963. }
  91964. material._babylonMeshes = material._babylonMeshes || [];
  91965. material._babylonMeshes.push(babylonMesh);
  91966. if (material._loaded) {
  91967. babylonMesh.material = material._babylonMaterial;
  91968. return material._loaded;
  91969. }
  91970. var promises = new Array();
  91971. var babylonMaterial = this._createMaterial(material);
  91972. material._babylonMaterial = babylonMaterial;
  91973. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  91974. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  91975. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  91976. babylonMesh.material = babylonMaterial;
  91977. return (material._loaded = Promise.all(promises).then(function () { }));
  91978. };
  91979. GLTFLoader.prototype._createMaterial = function (material) {
  91980. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  91981. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  91982. return babylonMaterial;
  91983. };
  91984. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  91985. var promises = new Array();
  91986. var babylonMaterial = material._babylonMaterial;
  91987. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  91988. if (material.doubleSided) {
  91989. babylonMaterial.backFaceCulling = false;
  91990. babylonMaterial.twoSidedLighting = true;
  91991. }
  91992. if (material.normalTexture) {
  91993. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  91994. babylonMaterial.bumpTexture = texture;
  91995. }));
  91996. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  91997. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  91998. if (material.normalTexture.scale != undefined) {
  91999. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  92000. }
  92001. }
  92002. if (material.occlusionTexture) {
  92003. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  92004. babylonMaterial.ambientTexture = texture;
  92005. }));
  92006. babylonMaterial.useAmbientInGrayScale = true;
  92007. if (material.occlusionTexture.strength != undefined) {
  92008. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  92009. }
  92010. }
  92011. if (material.emissiveTexture) {
  92012. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  92013. babylonMaterial.emissiveTexture = texture;
  92014. }));
  92015. }
  92016. return Promise.all(promises).then(function () { });
  92017. };
  92018. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  92019. var babylonMaterial = material._babylonMaterial;
  92020. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  92021. switch (alphaMode) {
  92022. case "OPAQUE" /* OPAQUE */: {
  92023. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  92024. break;
  92025. }
  92026. case "MASK" /* MASK */: {
  92027. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  92028. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  92029. if (babylonMaterial.alpha) {
  92030. if (babylonMaterial.alpha === 0) {
  92031. babylonMaterial.alphaCutOff = 1;
  92032. }
  92033. else {
  92034. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  92035. }
  92036. babylonMaterial.alpha = 1;
  92037. }
  92038. if (babylonMaterial.albedoTexture) {
  92039. babylonMaterial.albedoTexture.hasAlpha = true;
  92040. }
  92041. break;
  92042. }
  92043. case "BLEND" /* BLEND */: {
  92044. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  92045. if (babylonMaterial.albedoTexture) {
  92046. babylonMaterial.albedoTexture.hasAlpha = true;
  92047. babylonMaterial.useAlphaFromAlbedoTexture = true;
  92048. }
  92049. break;
  92050. }
  92051. default: {
  92052. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  92053. }
  92054. }
  92055. };
  92056. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  92057. var _this = this;
  92058. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  92059. context = "#/textures/" + textureInfo.index;
  92060. var promises = new Array();
  92061. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  92062. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  92063. var deferred = new BABYLON.Deferred();
  92064. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  92065. if (!_this._disposed) {
  92066. deferred.resolve();
  92067. }
  92068. }, function (message, exception) {
  92069. if (!_this._disposed) {
  92070. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  92071. }
  92072. });
  92073. promises.push(deferred.promise);
  92074. babylonTexture.name = texture.name || "texture" + texture._index;
  92075. babylonTexture.wrapU = samplerData.wrapU;
  92076. babylonTexture.wrapV = samplerData.wrapV;
  92077. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  92078. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  92079. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  92080. babylonTexture.updateURL(objectURL);
  92081. }));
  92082. assign(babylonTexture);
  92083. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  92084. return Promise.all(promises).then(function () { });
  92085. };
  92086. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  92087. if (!sampler._data) {
  92088. sampler._data = {
  92089. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  92090. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  92091. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  92092. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  92093. };
  92094. }
  92095. ;
  92096. return sampler._data;
  92097. };
  92098. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  92099. if (image._objectURL) {
  92100. return image._objectURL;
  92101. }
  92102. var promise;
  92103. if (image.uri) {
  92104. promise = this._loadUriAsync(context, image.uri);
  92105. }
  92106. else {
  92107. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  92108. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  92109. }
  92110. image._objectURL = promise.then(function (data) {
  92111. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  92112. });
  92113. return image._objectURL;
  92114. };
  92115. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  92116. var _this = this;
  92117. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  92118. if (promise) {
  92119. return promise;
  92120. }
  92121. if (!GLTFLoader._ValidateUri(uri)) {
  92122. throw new Error(context + ": Uri '" + uri + "' is invalid");
  92123. }
  92124. if (BABYLON.Tools.IsBase64(uri)) {
  92125. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  92126. }
  92127. return new Promise(function (resolve, reject) {
  92128. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  92129. if (!_this._disposed) {
  92130. resolve(new Uint8Array(data));
  92131. }
  92132. }, function (event) {
  92133. if (!_this._disposed) {
  92134. try {
  92135. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  92136. request._lengthComputable = event.lengthComputable;
  92137. request._loaded = event.loaded;
  92138. request._total = event.total;
  92139. _this._onProgress();
  92140. }
  92141. }
  92142. catch (e) {
  92143. reject(e);
  92144. }
  92145. }
  92146. }, _this._babylonScene.database, true, function (request, exception) {
  92147. if (!_this._disposed) {
  92148. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  92149. }
  92150. });
  92151. _this._requests.push(request);
  92152. });
  92153. };
  92154. GLTFLoader.prototype._onProgress = function () {
  92155. if (!this._progressCallback) {
  92156. return;
  92157. }
  92158. var lengthComputable = true;
  92159. var loaded = 0;
  92160. var total = 0;
  92161. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  92162. var request = _a[_i];
  92163. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  92164. return;
  92165. }
  92166. lengthComputable = lengthComputable && request._lengthComputable;
  92167. loaded += request._loaded;
  92168. total += request._total;
  92169. }
  92170. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  92171. };
  92172. GLTFLoader._GetProperty = function (context, array, index) {
  92173. if (!array || index == undefined || !array[index]) {
  92174. throw new Error(context + ": Failed to find index " + index);
  92175. }
  92176. return array[index];
  92177. };
  92178. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  92179. // Set defaults if undefined
  92180. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  92181. switch (mode) {
  92182. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  92183. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  92184. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  92185. default:
  92186. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  92187. return BABYLON.Texture.WRAP_ADDRESSMODE;
  92188. }
  92189. };
  92190. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  92191. // Set defaults if undefined
  92192. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  92193. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  92194. if (magFilter === 9729 /* LINEAR */) {
  92195. switch (minFilter) {
  92196. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  92197. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  92198. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  92199. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  92200. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  92201. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  92202. default:
  92203. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  92204. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  92205. }
  92206. }
  92207. else {
  92208. if (magFilter !== 9728 /* NEAREST */) {
  92209. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  92210. }
  92211. switch (minFilter) {
  92212. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  92213. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  92214. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  92215. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  92216. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  92217. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  92218. default:
  92219. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  92220. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  92221. }
  92222. }
  92223. };
  92224. GLTFLoader._GetNumComponents = function (context, type) {
  92225. switch (type) {
  92226. case "SCALAR": return 1;
  92227. case "VEC2": return 2;
  92228. case "VEC3": return 3;
  92229. case "VEC4": return 4;
  92230. case "MAT2": return 4;
  92231. case "MAT3": return 9;
  92232. case "MAT4": return 16;
  92233. }
  92234. throw new Error(context + ": Invalid type " + type);
  92235. };
  92236. GLTFLoader._ValidateUri = function (uri) {
  92237. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  92238. };
  92239. GLTFLoader.prototype._compileMaterialsAsync = function () {
  92240. var promises = new Array();
  92241. if (this._gltf.materials) {
  92242. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  92243. var material = _a[_i];
  92244. var babylonMaterial = material._babylonMaterial;
  92245. var babylonMeshes = material._babylonMeshes;
  92246. if (babylonMaterial && babylonMeshes) {
  92247. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  92248. var babylonMesh = babylonMeshes_1[_b];
  92249. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  92250. if (this.useClipPlane) {
  92251. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  92252. }
  92253. }
  92254. }
  92255. }
  92256. }
  92257. return Promise.all(promises).then(function () { });
  92258. };
  92259. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  92260. var promises = new Array();
  92261. var lights = this._babylonScene.lights;
  92262. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  92263. var light = lights_1[_i];
  92264. var generator = light.getShadowGenerator();
  92265. if (generator) {
  92266. promises.push(generator.forceCompilationAsync());
  92267. }
  92268. }
  92269. return Promise.all(promises).then(function () { });
  92270. };
  92271. GLTFLoader.prototype._clear = function () {
  92272. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  92273. var request = _a[_i];
  92274. request.abort();
  92275. }
  92276. this._requests.length = 0;
  92277. if (this._gltf && this._gltf.images) {
  92278. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  92279. var image = _c[_b];
  92280. if (image._objectURL) {
  92281. image._objectURL.then(function (value) {
  92282. URL.revokeObjectURL(value);
  92283. });
  92284. image._objectURL = undefined;
  92285. }
  92286. }
  92287. }
  92288. delete this._gltf;
  92289. delete this._babylonScene;
  92290. this._completePromises.length = 0;
  92291. this._extensions = {};
  92292. delete this._rootBabylonMesh;
  92293. delete this._progressCallback;
  92294. this.onMeshLoadedObservable.clear();
  92295. this.onTextureLoadedObservable.clear();
  92296. this.onMaterialLoadedObservable.clear();
  92297. };
  92298. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  92299. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  92300. var name_2 = _a[_i];
  92301. var extension = this._extensions[name_2];
  92302. if (extension.enabled) {
  92303. var promise = actionAsync(extension);
  92304. if (promise) {
  92305. return promise;
  92306. }
  92307. }
  92308. }
  92309. return null;
  92310. };
  92311. GLTFLoader._Names = new Array();
  92312. GLTFLoader._Factories = {};
  92313. return GLTFLoader;
  92314. }());
  92315. GLTF2.GLTFLoader = GLTFLoader;
  92316. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  92317. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92318. })(BABYLON || (BABYLON = {}));
  92319. //# sourceMappingURL=babylon.glTFLoader.js.map
  92320. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  92321. var BABYLON;
  92322. (function (BABYLON) {
  92323. var GLTF2;
  92324. (function (GLTF2) {
  92325. var GLTFLoaderExtension = /** @class */ (function () {
  92326. function GLTFLoaderExtension(loader) {
  92327. this.enabled = true;
  92328. this._loader = loader;
  92329. }
  92330. // #region Overridable Methods
  92331. /** Override this method to modify the default behavior for loading scenes. */
  92332. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  92333. /** Override this method to modify the default behavior for loading nodes. */
  92334. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  92335. /** Override this method to modify the default behavior for loading materials. */
  92336. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  92337. /** Override this method to modify the default behavior for loading uris. */
  92338. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  92339. // #endregion
  92340. /** Helper method called by a loader extension to load an glTF extension. */
  92341. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  92342. var _this = this;
  92343. if (!property.extensions) {
  92344. return null;
  92345. }
  92346. var extensions = property.extensions;
  92347. var extension = extensions[this.name];
  92348. if (!extension) {
  92349. return null;
  92350. }
  92351. // Clear out the extension before executing the action to avoid recursing into the same property.
  92352. delete extensions[this.name];
  92353. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  92354. // Restore the extension after completing the action.
  92355. extensions[_this.name] = extension;
  92356. });
  92357. };
  92358. /** Helper method called by the loader to allow extensions to override loading scenes. */
  92359. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  92360. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  92361. };
  92362. /** Helper method called by the loader to allow extensions to override loading nodes. */
  92363. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  92364. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  92365. };
  92366. /** Helper method called by the loader to allow extensions to override loading materials. */
  92367. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  92368. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  92369. };
  92370. /** Helper method called by the loader to allow extensions to override loading uris. */
  92371. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  92372. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  92373. };
  92374. return GLTFLoaderExtension;
  92375. }());
  92376. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  92377. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92378. })(BABYLON || (BABYLON = {}));
  92379. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  92380. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92381. var BABYLON;
  92382. (function (BABYLON) {
  92383. var GLTF2;
  92384. (function (GLTF2) {
  92385. var Extensions;
  92386. (function (Extensions) {
  92387. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  92388. var NAME = "MSFT_lod";
  92389. var MSFT_lod = /** @class */ (function (_super) {
  92390. __extends(MSFT_lod, _super);
  92391. function MSFT_lod() {
  92392. var _this = _super !== null && _super.apply(this, arguments) || this;
  92393. _this.name = NAME;
  92394. /**
  92395. * Maximum number of LODs to load, starting from the lowest LOD.
  92396. */
  92397. _this.maxLODsToLoad = Number.MAX_VALUE;
  92398. _this._loadingNodeLOD = null;
  92399. _this._loadNodeSignals = {};
  92400. _this._loadingMaterialLOD = null;
  92401. _this._loadMaterialSignals = {};
  92402. return _this;
  92403. }
  92404. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  92405. var _this = this;
  92406. return this._loadExtensionAsync(context, node, function (context, extension) {
  92407. var firstPromise;
  92408. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  92409. var _loop_1 = function (indexLOD) {
  92410. var nodeLOD = nodeLODs[indexLOD];
  92411. if (indexLOD !== 0) {
  92412. _this._loadingNodeLOD = nodeLOD;
  92413. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  92414. }
  92415. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  92416. if (indexLOD !== 0) {
  92417. var previousNodeLOD = nodeLODs[indexLOD - 1];
  92418. previousNodeLOD._babylonMesh.setEnabled(false);
  92419. }
  92420. if (indexLOD !== nodeLODs.length - 1) {
  92421. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  92422. _this._loadNodeSignals[nodeIndex].resolve();
  92423. delete _this._loadNodeSignals[nodeIndex];
  92424. }
  92425. });
  92426. if (indexLOD === 0) {
  92427. firstPromise = promise;
  92428. }
  92429. else {
  92430. _this._loader._completePromises.push(promise);
  92431. _this._loadingNodeLOD = null;
  92432. }
  92433. };
  92434. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  92435. _loop_1(indexLOD);
  92436. }
  92437. return firstPromise;
  92438. });
  92439. };
  92440. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92441. var _this = this;
  92442. // Don't load material LODs if already loading a node LOD.
  92443. if (this._loadingNodeLOD) {
  92444. return null;
  92445. }
  92446. return this._loadExtensionAsync(context, material, function (context, extension) {
  92447. var firstPromise;
  92448. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  92449. var _loop_2 = function (indexLOD) {
  92450. var materialLOD = materialLODs[indexLOD];
  92451. if (indexLOD !== 0) {
  92452. _this._loadingMaterialLOD = materialLOD;
  92453. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  92454. }
  92455. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  92456. if (indexLOD !== materialLODs.length - 1) {
  92457. var materialIndex = materialLODs[indexLOD + 1]._index;
  92458. _this._loadMaterialSignals[materialIndex].resolve();
  92459. delete _this._loadMaterialSignals[materialIndex];
  92460. }
  92461. });
  92462. if (indexLOD === 0) {
  92463. firstPromise = promise;
  92464. }
  92465. else {
  92466. _this._loader._completePromises.push(promise);
  92467. _this._loadingMaterialLOD = null;
  92468. }
  92469. };
  92470. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  92471. _loop_2(indexLOD);
  92472. }
  92473. return firstPromise;
  92474. });
  92475. };
  92476. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  92477. var _this = this;
  92478. // Defer the loading of uris if loading a material or node LOD.
  92479. if (this._loadingMaterialLOD) {
  92480. var index = this._loadingMaterialLOD._index;
  92481. return this._loadMaterialSignals[index].promise.then(function () {
  92482. return _this._loader._loadUriAsync(context, uri);
  92483. });
  92484. }
  92485. else if (this._loadingNodeLOD) {
  92486. var index = this._loadingNodeLOD._index;
  92487. return this._loadNodeSignals[index].promise.then(function () {
  92488. return _this._loader._loadUriAsync(context, uri);
  92489. });
  92490. }
  92491. return null;
  92492. };
  92493. /**
  92494. * Gets an array of LOD properties from lowest to highest.
  92495. */
  92496. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  92497. if (this.maxLODsToLoad <= 0) {
  92498. throw new Error("maxLODsToLoad must be greater than zero");
  92499. }
  92500. var properties = new Array();
  92501. for (var i = ids.length - 1; i >= 0; i--) {
  92502. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  92503. if (properties.length === this.maxLODsToLoad) {
  92504. return properties;
  92505. }
  92506. }
  92507. properties.push(property);
  92508. return properties;
  92509. };
  92510. return MSFT_lod;
  92511. }(GLTF2.GLTFLoaderExtension));
  92512. Extensions.MSFT_lod = MSFT_lod;
  92513. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  92514. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92515. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92516. })(BABYLON || (BABYLON = {}));
  92517. //# sourceMappingURL=MSFT_lod.js.map
  92518. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92519. var BABYLON;
  92520. (function (BABYLON) {
  92521. var GLTF2;
  92522. (function (GLTF2) {
  92523. var Extensions;
  92524. (function (Extensions) {
  92525. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  92526. var NAME = "KHR_materials_pbrSpecularGlossiness";
  92527. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  92528. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  92529. function KHR_materials_pbrSpecularGlossiness() {
  92530. var _this = _super !== null && _super.apply(this, arguments) || this;
  92531. _this.name = NAME;
  92532. return _this;
  92533. }
  92534. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  92535. var _this = this;
  92536. return this._loadExtensionAsync(context, material, function (context, extension) {
  92537. material._babylonMeshes = material._babylonMeshes || [];
  92538. material._babylonMeshes.push(babylonMesh);
  92539. if (material._loaded) {
  92540. babylonMesh.material = material._babylonMaterial;
  92541. return material._loaded;
  92542. }
  92543. var promises = new Array();
  92544. var babylonMaterial = _this._loader._createMaterial(material);
  92545. material._babylonMaterial = babylonMaterial;
  92546. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  92547. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  92548. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  92549. babylonMesh.material = babylonMaterial;
  92550. return (material._loaded = Promise.all(promises).then(function () { }));
  92551. });
  92552. };
  92553. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  92554. var promises = new Array();
  92555. var babylonMaterial = material._babylonMaterial;
  92556. if (properties.diffuseFactor) {
  92557. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  92558. babylonMaterial.alpha = properties.diffuseFactor[3];
  92559. }
  92560. else {
  92561. babylonMaterial.albedoColor = BABYLON.Color3.White();
  92562. }
  92563. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  92564. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  92565. if (properties.diffuseTexture) {
  92566. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  92567. babylonMaterial.albedoTexture = texture;
  92568. }));
  92569. }
  92570. if (properties.specularGlossinessTexture) {
  92571. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  92572. babylonMaterial.reflectivityTexture = texture;
  92573. }));
  92574. babylonMaterial.reflectivityTexture.hasAlpha = true;
  92575. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  92576. }
  92577. loader._loadMaterialAlphaProperties(context, material);
  92578. return Promise.all(promises).then(function () { });
  92579. };
  92580. return KHR_materials_pbrSpecularGlossiness;
  92581. }(GLTF2.GLTFLoaderExtension));
  92582. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  92583. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  92584. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92585. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92586. })(BABYLON || (BABYLON = {}));
  92587. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  92588. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  92589. var BABYLON;
  92590. (function (BABYLON) {
  92591. var GLTF2;
  92592. (function (GLTF2) {
  92593. var Extensions;
  92594. (function (Extensions) {
  92595. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  92596. var NAME = "KHR_lights";
  92597. var LightType;
  92598. (function (LightType) {
  92599. LightType["AMBIENT"] = "ambient";
  92600. LightType["DIRECTIONAL"] = "directional";
  92601. LightType["POINT"] = "point";
  92602. LightType["SPOT"] = "spot";
  92603. })(LightType || (LightType = {}));
  92604. var KHR_lights = /** @class */ (function (_super) {
  92605. __extends(KHR_lights, _super);
  92606. function KHR_lights() {
  92607. var _this = _super !== null && _super.apply(this, arguments) || this;
  92608. _this.name = NAME;
  92609. return _this;
  92610. }
  92611. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  92612. var _this = this;
  92613. return this._loadExtensionAsync(context, scene, function (context, extension) {
  92614. var promise = _this._loader._loadSceneAsync(context, scene);
  92615. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92616. if (light.type !== LightType.AMBIENT) {
  92617. throw new Error(context + ": Only ambient lights are allowed on a scene");
  92618. }
  92619. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  92620. return promise;
  92621. });
  92622. };
  92623. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  92624. var _this = this;
  92625. return this._loadExtensionAsync(context, node, function (context, extension) {
  92626. var promise = _this._loader._loadNodeAsync(context, node);
  92627. var babylonLight;
  92628. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  92629. var name = node._babylonMesh.name;
  92630. switch (light.type) {
  92631. case LightType.AMBIENT: {
  92632. throw new Error(context + ": Ambient lights are not allowed on a node");
  92633. }
  92634. case LightType.DIRECTIONAL: {
  92635. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  92636. break;
  92637. }
  92638. case LightType.POINT: {
  92639. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  92640. break;
  92641. }
  92642. case LightType.SPOT: {
  92643. var spotLight = light;
  92644. // TODO: support inner and outer cone angles
  92645. //const innerConeAngle = spotLight.innerConeAngle || 0;
  92646. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  92647. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  92648. break;
  92649. }
  92650. default: {
  92651. throw new Error(context + ": Invalid light type " + light.type);
  92652. }
  92653. }
  92654. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  92655. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  92656. babylonLight.parent = node._babylonMesh;
  92657. return promise;
  92658. });
  92659. };
  92660. Object.defineProperty(KHR_lights.prototype, "_lights", {
  92661. get: function () {
  92662. var extensions = this._loader._gltf.extensions;
  92663. if (!extensions || !extensions[this.name]) {
  92664. throw new Error("#/extensions: " + this.name + " not found");
  92665. }
  92666. var extension = extensions[this.name];
  92667. return extension.lights;
  92668. },
  92669. enumerable: true,
  92670. configurable: true
  92671. });
  92672. return KHR_lights;
  92673. }(GLTF2.GLTFLoaderExtension));
  92674. Extensions.KHR_lights = KHR_lights;
  92675. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  92676. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  92677. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  92678. })(BABYLON || (BABYLON = {}));
  92679. //# sourceMappingURL=KHR_lights.js.map
  92680. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92681. globalObject["BABYLON"] = BABYLON;
  92682. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  92683. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };