es6.js 4.2 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128
  1. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  2. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  3. var BABYLON;
  4. (function (BABYLON) {
  5. var EffectFallbacks = /** @class */ (function () {
  6. function EffectFallbacks() {
  7. this._defines = {};
  8. this._currentRank = 32;
  9. this._maxRank = -1;
  10. }
  11. EffectFallbacks.prototype.unBindMesh = function () {
  12. this._mesh = null;
  13. };
  14. EffectFallbacks.prototype.addFallback = function (rank, define) {
  15. if (!this._defines[rank]) {
  16. if (rank < this._currentRank) {
  17. this._currentRank = rank;
  18. }
  19. if (rank > this._maxRank) {
  20. this._maxRank = rank;
  21. }
  22. this._defines[rank] = new Array();
  23. }
  24. this._defines[rank].push(define);
  25. };
  26. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  27. this._mesh = mesh;
  28. if (rank < this._currentRank) {
  29. this._currentRank = rank;
  30. }
  31. if (rank > this._maxRank) {
  32. this._maxRank = rank;
  33. }
  34. };
  35. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  36. get: function () {
  37. return this._currentRank <= this._maxRank;
  38. },
  39. enumerable: true,
  40. configurable: true
  41. });
  42. EffectFallbacks.prototype.reduce = function (currentDefines) {
  43. // First we try to switch to CPU skinning
  44. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  45. this._mesh.computeBonesUsingShaders = false;
  46. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  47. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  48. var scene = this._mesh.getScene();
  49. for (var index = 0; index < scene.meshes.length; index++) {
  50. var otherMesh = scene.meshes[index];
  51. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  52. otherMesh.computeBonesUsingShaders = false;
  53. }
  54. }
  55. }
  56. else {
  57. var currentFallbacks = this._defines[this._currentRank];
  58. if (currentFallbacks) {
  59. for (var index = 0; index < currentFallbacks.length; index++) {
  60. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  61. }
  62. }
  63. this._currentRank++;
  64. }
  65. return currentDefines;
  66. };
  67. return EffectFallbacks;
  68. }());
  69. BABYLON.EffectFallbacks = EffectFallbacks;
  70. var EffectCreationOptions = /** @class */ (function () {
  71. function EffectCreationOptions() {
  72. }
  73. return EffectCreationOptions;
  74. }());
  75. BABYLON.EffectCreationOptions = EffectCreationOptions;
  76. var Effect = /** @class */ (function () {
  77. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  78. if (samplers === void 0) { samplers = null; }
  79. if (defines === void 0) { defines = null; }
  80. if (fallbacks === void 0) { fallbacks = null; }
  81. if (onCompiled === void 0) { onCompiled = null; }
  82. if (onError === void 0) { onError = null; }
  83. var _this = this;
  84. this.uniqueId = 0;
  85. this.onCompileObservable = new BABYLON.Observable();
  86. this.onErrorObservable = new BABYLON.Observable();
  87. this.onBindObservable = new BABYLON.Observable();
  88. this._uniformBuffersNames = {};
  89. this._isReady = false;
  90. this._compilationError = "";
  91. this.name = baseName;
  92. if (attributesNamesOrOptions.attributes) {
  93. var options = attributesNamesOrOptions;
  94. this._engine = uniformsNamesOrEngine;
  95. this._attributesNames = options.attributes;
  96. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  97. this._samplers = options.samplers;
  98. this.defines = options.defines;
  99. this.onError = options.onError;
  100. this.onCompiled = options.onCompiled;
  101. this._fallbacks = options.fallbacks;
  102. this._indexParameters = options.indexParameters;
  103. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  104. if (options.uniformBuffersNames) {
  105. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  106. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  107. }
  108. }
  109. }
  110. else {
  111. this._engine = engine;
  112. this.defines = defines;
  113. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  114. this._samplers = samplers;
  115. this._attributesNames = attributesNamesOrOptions;
  116. this.onError = onError;
  117. this.onCompiled = onCompiled;
  118. this._indexParameters = indexParameters;
  119. this._fallbacks = fallbacks;
  120. }
  121. this.uniqueId = Effect._uniqueIdSeed++;
  122. var vertexSource;
  123. var fragmentSource;
  124. if (baseName.vertexElement) {
  125. vertexSource = document.getElementById(baseName.vertexElement);
  126. if (!vertexSource) {
  127. vertexSource = baseName.vertexElement;
  128. }
  129. }
  130. else {
  131. vertexSource = baseName.vertex || baseName;
  132. }
  133. if (baseName.fragmentElement) {
  134. fragmentSource = document.getElementById(baseName.fragmentElement);
  135. if (!fragmentSource) {
  136. fragmentSource = baseName.fragmentElement;
  137. }
  138. }
  139. else {
  140. fragmentSource = baseName.fragment || baseName;
  141. }
  142. this._loadVertexShader(vertexSource, function (vertexCode) {
  143. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  144. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  145. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  146. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  147. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  148. if (baseName) {
  149. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  150. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  151. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  152. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  153. }
  154. else {
  155. _this._vertexSourceCode = migratedVertexCode;
  156. _this._fragmentSourceCode = migratedFragmentCode;
  157. }
  158. _this._prepareEffect();
  159. });
  160. });
  161. });
  162. });
  163. });
  164. });
  165. }
  166. Object.defineProperty(Effect.prototype, "key", {
  167. get: function () {
  168. return this._key;
  169. },
  170. enumerable: true,
  171. configurable: true
  172. });
  173. // Properties
  174. Effect.prototype.isReady = function () {
  175. return this._isReady;
  176. };
  177. Effect.prototype.getEngine = function () {
  178. return this._engine;
  179. };
  180. Effect.prototype.getProgram = function () {
  181. return this._program;
  182. };
  183. Effect.prototype.getAttributesNames = function () {
  184. return this._attributesNames;
  185. };
  186. Effect.prototype.getAttributeLocation = function (index) {
  187. return this._attributes[index];
  188. };
  189. Effect.prototype.getAttributeLocationByName = function (name) {
  190. var index = this._attributesNames.indexOf(name);
  191. return this._attributes[index];
  192. };
  193. Effect.prototype.getAttributesCount = function () {
  194. return this._attributes.length;
  195. };
  196. Effect.prototype.getUniformIndex = function (uniformName) {
  197. return this._uniformsNames.indexOf(uniformName);
  198. };
  199. Effect.prototype.getUniform = function (uniformName) {
  200. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  201. };
  202. Effect.prototype.getSamplers = function () {
  203. return this._samplers;
  204. };
  205. Effect.prototype.getCompilationError = function () {
  206. return this._compilationError;
  207. };
  208. // Methods
  209. Effect.prototype.executeWhenCompiled = function (func) {
  210. if (this.isReady()) {
  211. func(this);
  212. return;
  213. }
  214. this.onCompileObservable.add(function (effect) {
  215. func(effect);
  216. });
  217. };
  218. Effect.prototype._loadVertexShader = function (vertex, callback) {
  219. if (BABYLON.Tools.IsWindowObjectExist()) {
  220. // DOM element ?
  221. if (vertex instanceof HTMLElement) {
  222. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  223. callback(vertexCode);
  224. return;
  225. }
  226. }
  227. // Base64 encoded ?
  228. if (vertex.substr(0, 7) === "base64:") {
  229. var vertexBinary = window.atob(vertex.substr(7));
  230. callback(vertexBinary);
  231. return;
  232. }
  233. // Is in local store ?
  234. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  235. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  236. return;
  237. }
  238. var vertexShaderUrl;
  239. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  240. vertexShaderUrl = vertex;
  241. }
  242. else {
  243. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  244. }
  245. // Vertex shader
  246. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  247. };
  248. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  249. if (BABYLON.Tools.IsWindowObjectExist()) {
  250. // DOM element ?
  251. if (fragment instanceof HTMLElement) {
  252. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  253. callback(fragmentCode);
  254. return;
  255. }
  256. }
  257. // Base64 encoded ?
  258. if (fragment.substr(0, 7) === "base64:") {
  259. var fragmentBinary = window.atob(fragment.substr(7));
  260. callback(fragmentBinary);
  261. return;
  262. }
  263. // Is in local store ?
  264. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  265. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  266. return;
  267. }
  268. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  269. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  270. return;
  271. }
  272. var fragmentShaderUrl;
  273. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  274. fragmentShaderUrl = fragment;
  275. }
  276. else {
  277. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  278. }
  279. // Fragment shader
  280. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  281. };
  282. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  283. // Rebuild shaders source code
  284. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  285. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  286. vertexCode = prefix + vertexCode;
  287. fragmentCode = prefix + fragmentCode;
  288. // Number lines of shaders source code
  289. var i = 2;
  290. var regex = /\n/gm;
  291. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  292. i = 2;
  293. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  294. // Dump shaders name and formatted source code
  295. if (this.name.vertexElement) {
  296. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  297. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  298. }
  299. else if (this.name.vertex) {
  300. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  301. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  302. }
  303. else {
  304. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  305. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  306. }
  307. };
  308. ;
  309. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  310. var preparedSourceCode = this._processPrecision(sourceCode);
  311. if (this._engine.webGLVersion == 1) {
  312. callback(preparedSourceCode);
  313. return;
  314. }
  315. // Already converted
  316. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  317. callback(preparedSourceCode.replace("#version 300 es", ""));
  318. return;
  319. }
  320. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  321. // Remove extensions
  322. // #extension GL_OES_standard_derivatives : enable
  323. // #extension GL_EXT_shader_texture_lod : enable
  324. // #extension GL_EXT_frag_depth : enable
  325. // #extension GL_EXT_draw_buffers : require
  326. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  327. var result = preparedSourceCode.replace(regex, "");
  328. // Migrate to GLSL v300
  329. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  330. result = result.replace(/attribute[ \t]/g, "in ");
  331. result = result.replace(/[ \t]attribute/g, " in");
  332. if (isFragment) {
  333. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  334. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  335. result = result.replace(/texture2D\s*\(/g, "texture(");
  336. result = result.replace(/textureCube\s*\(/g, "texture(");
  337. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  338. result = result.replace(/gl_FragColor/g, "glFragColor");
  339. result = result.replace(/gl_FragData/g, "glFragData");
  340. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  341. }
  342. callback(result);
  343. };
  344. Effect.prototype._processIncludes = function (sourceCode, callback) {
  345. var _this = this;
  346. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  347. var match = regex.exec(sourceCode);
  348. var returnValue = new String(sourceCode);
  349. while (match != null) {
  350. var includeFile = match[1];
  351. // Uniform declaration
  352. if (includeFile.indexOf("__decl__") !== -1) {
  353. includeFile = includeFile.replace(/__decl__/, "");
  354. if (this._engine.supportsUniformBuffers) {
  355. includeFile = includeFile.replace(/Vertex/, "Ubo");
  356. includeFile = includeFile.replace(/Fragment/, "Ubo");
  357. }
  358. includeFile = includeFile + "Declaration";
  359. }
  360. if (Effect.IncludesShadersStore[includeFile]) {
  361. // Substitution
  362. var includeContent = Effect.IncludesShadersStore[includeFile];
  363. if (match[2]) {
  364. var splits = match[3].split(",");
  365. for (var index = 0; index < splits.length; index += 2) {
  366. var source = new RegExp(splits[index], "g");
  367. var dest = splits[index + 1];
  368. includeContent = includeContent.replace(source, dest);
  369. }
  370. }
  371. if (match[4]) {
  372. var indexString = match[5];
  373. if (indexString.indexOf("..") !== -1) {
  374. var indexSplits = indexString.split("..");
  375. var minIndex = parseInt(indexSplits[0]);
  376. var maxIndex = parseInt(indexSplits[1]);
  377. var sourceIncludeContent = includeContent.slice(0);
  378. includeContent = "";
  379. if (isNaN(maxIndex)) {
  380. maxIndex = this._indexParameters[indexSplits[1]];
  381. }
  382. for (var i = minIndex; i < maxIndex; i++) {
  383. if (!this._engine.supportsUniformBuffers) {
  384. // Ubo replacement
  385. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  386. return p1 + "{X}";
  387. });
  388. }
  389. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  390. }
  391. }
  392. else {
  393. if (!this._engine.supportsUniformBuffers) {
  394. // Ubo replacement
  395. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  396. return p1 + "{X}";
  397. });
  398. }
  399. includeContent = includeContent.replace(/\{X\}/g, indexString);
  400. }
  401. }
  402. // Replace
  403. returnValue = returnValue.replace(match[0], includeContent);
  404. }
  405. else {
  406. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  407. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  408. Effect.IncludesShadersStore[includeFile] = fileContent;
  409. _this._processIncludes(returnValue, callback);
  410. });
  411. return;
  412. }
  413. match = regex.exec(sourceCode);
  414. }
  415. callback(returnValue);
  416. };
  417. Effect.prototype._processPrecision = function (source) {
  418. if (source.indexOf("precision highp float") === -1) {
  419. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  420. source = "precision mediump float;\n" + source;
  421. }
  422. else {
  423. source = "precision highp float;\n" + source;
  424. }
  425. }
  426. else {
  427. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  428. source = source.replace("precision highp float", "precision mediump float");
  429. }
  430. }
  431. return source;
  432. };
  433. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  434. var _this = this;
  435. this._isReady = false;
  436. this._vertexSourceCodeOverride = vertexSourceCode;
  437. this._fragmentSourceCodeOverride = fragmentSourceCode;
  438. this.onError = function (effect, error) {
  439. if (onError) {
  440. onError(error);
  441. }
  442. };
  443. this.onCompiled = function () {
  444. var scenes = _this.getEngine().scenes;
  445. for (var i = 0; i < scenes.length; i++) {
  446. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  447. }
  448. if (onCompiled) {
  449. onCompiled(_this._program);
  450. }
  451. };
  452. this._fallbacks = null;
  453. this._prepareEffect();
  454. };
  455. Effect.prototype.getSpecificUniformLocations = function (names) {
  456. var engine = this._engine;
  457. return engine.getUniforms(this._program, names);
  458. };
  459. Effect.prototype._prepareEffect = function () {
  460. var attributesNames = this._attributesNames;
  461. var defines = this.defines;
  462. var fallbacks = this._fallbacks;
  463. this._valueCache = {};
  464. var previousProgram = this._program;
  465. try {
  466. var engine = this._engine;
  467. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  468. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  469. }
  470. else {
  471. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  472. }
  473. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  474. if (engine.supportsUniformBuffers) {
  475. for (var name in this._uniformBuffersNames) {
  476. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  477. }
  478. }
  479. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  480. this._attributes = engine.getAttributes(this._program, attributesNames);
  481. var index;
  482. for (index = 0; index < this._samplers.length; index++) {
  483. var sampler = this.getUniform(this._samplers[index]);
  484. if (sampler == null) {
  485. this._samplers.splice(index, 1);
  486. index--;
  487. }
  488. }
  489. engine.bindSamplers(this);
  490. this._compilationError = "";
  491. this._isReady = true;
  492. if (this.onCompiled) {
  493. this.onCompiled(this);
  494. }
  495. this.onCompileObservable.notifyObservers(this);
  496. this.onCompileObservable.clear();
  497. // Unbind mesh reference in fallbacks
  498. if (this._fallbacks) {
  499. this._fallbacks.unBindMesh();
  500. }
  501. if (previousProgram) {
  502. this.getEngine()._deleteProgram(previousProgram);
  503. }
  504. }
  505. catch (e) {
  506. this._compilationError = e.message;
  507. // Let's go through fallbacks then
  508. BABYLON.Tools.Error("Unable to compile effect:");
  509. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  510. return " " + uniform;
  511. }));
  512. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  513. return " " + attribute;
  514. }));
  515. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  516. BABYLON.Tools.Error("Error: " + this._compilationError);
  517. if (previousProgram) {
  518. this._program = previousProgram;
  519. this._isReady = true;
  520. if (this.onError) {
  521. this.onError(this, this._compilationError);
  522. }
  523. this.onErrorObservable.notifyObservers(this);
  524. }
  525. if (fallbacks && fallbacks.isMoreFallbacks) {
  526. BABYLON.Tools.Error("Trying next fallback.");
  527. this.defines = fallbacks.reduce(this.defines);
  528. this._prepareEffect();
  529. }
  530. else {
  531. if (this.onError) {
  532. this.onError(this, this._compilationError);
  533. }
  534. this.onErrorObservable.notifyObservers(this);
  535. this.onErrorObservable.clear();
  536. // Unbind mesh reference in fallbacks
  537. if (this._fallbacks) {
  538. this._fallbacks.unBindMesh();
  539. }
  540. }
  541. }
  542. };
  543. Object.defineProperty(Effect.prototype, "isSupported", {
  544. get: function () {
  545. return this._compilationError === "";
  546. },
  547. enumerable: true,
  548. configurable: true
  549. });
  550. Effect.prototype._bindTexture = function (channel, texture) {
  551. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  552. };
  553. Effect.prototype.setTexture = function (channel, texture) {
  554. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  555. };
  556. Effect.prototype.setTextureArray = function (channel, textures) {
  557. if (this._samplers.indexOf(channel + "Ex") === -1) {
  558. var initialPos = this._samplers.indexOf(channel);
  559. for (var index = 1; index < textures.length; index++) {
  560. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  561. }
  562. }
  563. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  564. };
  565. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  566. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  567. };
  568. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  569. var cache = this._valueCache[uniformName];
  570. var flag = matrix.updateFlag;
  571. if (cache !== undefined && cache === flag) {
  572. return false;
  573. }
  574. this._valueCache[uniformName] = flag;
  575. return true;
  576. };
  577. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  578. var cache = this._valueCache[uniformName];
  579. if (!cache) {
  580. cache = [x, y];
  581. this._valueCache[uniformName] = cache;
  582. return true;
  583. }
  584. var changed = false;
  585. if (cache[0] !== x) {
  586. cache[0] = x;
  587. changed = true;
  588. }
  589. if (cache[1] !== y) {
  590. cache[1] = y;
  591. changed = true;
  592. }
  593. return changed;
  594. };
  595. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  596. var cache = this._valueCache[uniformName];
  597. if (!cache) {
  598. cache = [x, y, z];
  599. this._valueCache[uniformName] = cache;
  600. return true;
  601. }
  602. var changed = false;
  603. if (cache[0] !== x) {
  604. cache[0] = x;
  605. changed = true;
  606. }
  607. if (cache[1] !== y) {
  608. cache[1] = y;
  609. changed = true;
  610. }
  611. if (cache[2] !== z) {
  612. cache[2] = z;
  613. changed = true;
  614. }
  615. return changed;
  616. };
  617. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  618. var cache = this._valueCache[uniformName];
  619. if (!cache) {
  620. cache = [x, y, z, w];
  621. this._valueCache[uniformName] = cache;
  622. return true;
  623. }
  624. var changed = false;
  625. if (cache[0] !== x) {
  626. cache[0] = x;
  627. changed = true;
  628. }
  629. if (cache[1] !== y) {
  630. cache[1] = y;
  631. changed = true;
  632. }
  633. if (cache[2] !== z) {
  634. cache[2] = z;
  635. changed = true;
  636. }
  637. if (cache[3] !== w) {
  638. cache[3] = w;
  639. changed = true;
  640. }
  641. return changed;
  642. };
  643. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  644. var bufferName = this._uniformBuffersNames[name];
  645. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  646. return;
  647. }
  648. Effect._baseCache[bufferName] = buffer;
  649. this._engine.bindUniformBufferBase(buffer, bufferName);
  650. };
  651. Effect.prototype.bindUniformBlock = function (blockName, index) {
  652. this._engine.bindUniformBlock(this._program, blockName, index);
  653. };
  654. Effect.prototype.setInt = function (uniformName, value) {
  655. var cache = this._valueCache[uniformName];
  656. if (cache !== undefined && cache === value)
  657. return this;
  658. this._valueCache[uniformName] = value;
  659. this._engine.setInt(this.getUniform(uniformName), value);
  660. return this;
  661. };
  662. Effect.prototype.setIntArray = function (uniformName, array) {
  663. this._valueCache[uniformName] = null;
  664. this._engine.setIntArray(this.getUniform(uniformName), array);
  665. return this;
  666. };
  667. Effect.prototype.setIntArray2 = function (uniformName, array) {
  668. this._valueCache[uniformName] = null;
  669. this._engine.setIntArray2(this.getUniform(uniformName), array);
  670. return this;
  671. };
  672. Effect.prototype.setIntArray3 = function (uniformName, array) {
  673. this._valueCache[uniformName] = null;
  674. this._engine.setIntArray3(this.getUniform(uniformName), array);
  675. return this;
  676. };
  677. Effect.prototype.setIntArray4 = function (uniformName, array) {
  678. this._valueCache[uniformName] = null;
  679. this._engine.setIntArray4(this.getUniform(uniformName), array);
  680. return this;
  681. };
  682. Effect.prototype.setFloatArray = function (uniformName, array) {
  683. this._valueCache[uniformName] = null;
  684. this._engine.setFloatArray(this.getUniform(uniformName), array);
  685. return this;
  686. };
  687. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  688. this._valueCache[uniformName] = null;
  689. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  690. return this;
  691. };
  692. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  693. this._valueCache[uniformName] = null;
  694. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  695. return this;
  696. };
  697. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  698. this._valueCache[uniformName] = null;
  699. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  700. return this;
  701. };
  702. Effect.prototype.setArray = function (uniformName, array) {
  703. this._valueCache[uniformName] = null;
  704. this._engine.setArray(this.getUniform(uniformName), array);
  705. return this;
  706. };
  707. Effect.prototype.setArray2 = function (uniformName, array) {
  708. this._valueCache[uniformName] = null;
  709. this._engine.setArray2(this.getUniform(uniformName), array);
  710. return this;
  711. };
  712. Effect.prototype.setArray3 = function (uniformName, array) {
  713. this._valueCache[uniformName] = null;
  714. this._engine.setArray3(this.getUniform(uniformName), array);
  715. return this;
  716. };
  717. Effect.prototype.setArray4 = function (uniformName, array) {
  718. this._valueCache[uniformName] = null;
  719. this._engine.setArray4(this.getUniform(uniformName), array);
  720. return this;
  721. };
  722. Effect.prototype.setMatrices = function (uniformName, matrices) {
  723. if (!matrices) {
  724. return this;
  725. }
  726. this._valueCache[uniformName] = null;
  727. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  728. return this;
  729. };
  730. Effect.prototype.setMatrix = function (uniformName, matrix) {
  731. if (this._cacheMatrix(uniformName, matrix)) {
  732. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  733. }
  734. return this;
  735. };
  736. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  737. this._valueCache[uniformName] = null;
  738. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  739. return this;
  740. };
  741. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  742. this._valueCache[uniformName] = null;
  743. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  744. return this;
  745. };
  746. Effect.prototype.setFloat = function (uniformName, value) {
  747. var cache = this._valueCache[uniformName];
  748. if (cache !== undefined && cache === value)
  749. return this;
  750. this._valueCache[uniformName] = value;
  751. this._engine.setFloat(this.getUniform(uniformName), value);
  752. return this;
  753. };
  754. Effect.prototype.setBool = function (uniformName, bool) {
  755. var cache = this._valueCache[uniformName];
  756. if (cache !== undefined && cache === bool)
  757. return this;
  758. this._valueCache[uniformName] = bool;
  759. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  760. return this;
  761. };
  762. Effect.prototype.setVector2 = function (uniformName, vector2) {
  763. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  764. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  765. }
  766. return this;
  767. };
  768. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  769. if (this._cacheFloat2(uniformName, x, y)) {
  770. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  771. }
  772. return this;
  773. };
  774. Effect.prototype.setVector3 = function (uniformName, vector3) {
  775. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  776. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  777. }
  778. return this;
  779. };
  780. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  781. if (this._cacheFloat3(uniformName, x, y, z)) {
  782. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  783. }
  784. return this;
  785. };
  786. Effect.prototype.setVector4 = function (uniformName, vector4) {
  787. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  788. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  789. }
  790. return this;
  791. };
  792. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  793. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  794. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  795. }
  796. return this;
  797. };
  798. Effect.prototype.setColor3 = function (uniformName, color3) {
  799. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  800. this._engine.setColor3(this.getUniform(uniformName), color3);
  801. }
  802. return this;
  803. };
  804. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  805. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  806. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  807. }
  808. return this;
  809. };
  810. Effect.ResetCache = function () {
  811. Effect._baseCache = {};
  812. };
  813. Effect._uniqueIdSeed = 0;
  814. Effect._baseCache = {};
  815. // Statics
  816. Effect.ShadersStore = {};
  817. Effect.IncludesShadersStore = {};
  818. return Effect;
  819. }());
  820. BABYLON.Effect = Effect;
  821. })(BABYLON || (BABYLON = {}));
  822. //# sourceMappingURL=babylon.effect.js.map
  823. //# sourceMappingURL=babylon.types.js.map
  824. var BABYLON;
  825. (function (BABYLON) {
  826. var KeyboardEventTypes = /** @class */ (function () {
  827. function KeyboardEventTypes() {
  828. }
  829. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  830. get: function () {
  831. return KeyboardEventTypes._KEYDOWN;
  832. },
  833. enumerable: true,
  834. configurable: true
  835. });
  836. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  837. get: function () {
  838. return KeyboardEventTypes._KEYUP;
  839. },
  840. enumerable: true,
  841. configurable: true
  842. });
  843. KeyboardEventTypes._KEYDOWN = 0x01;
  844. KeyboardEventTypes._KEYUP = 0x02;
  845. return KeyboardEventTypes;
  846. }());
  847. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  848. var KeyboardInfo = /** @class */ (function () {
  849. function KeyboardInfo(type, event) {
  850. this.type = type;
  851. this.event = event;
  852. }
  853. return KeyboardInfo;
  854. }());
  855. BABYLON.KeyboardInfo = KeyboardInfo;
  856. /**
  857. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  858. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  859. */
  860. var KeyboardInfoPre = /** @class */ (function (_super) {
  861. __extends(KeyboardInfoPre, _super);
  862. function KeyboardInfoPre(type, event) {
  863. var _this = _super.call(this, type, event) || this;
  864. _this.skipOnPointerObservable = false;
  865. return _this;
  866. }
  867. return KeyboardInfoPre;
  868. }(KeyboardInfo));
  869. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  870. })(BABYLON || (BABYLON = {}));
  871. //# sourceMappingURL=babylon.keyboardEvents.js.map
  872. var BABYLON;
  873. (function (BABYLON) {
  874. var PointerEventTypes = /** @class */ (function () {
  875. function PointerEventTypes() {
  876. }
  877. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  878. get: function () {
  879. return PointerEventTypes._POINTERDOWN;
  880. },
  881. enumerable: true,
  882. configurable: true
  883. });
  884. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  885. get: function () {
  886. return PointerEventTypes._POINTERUP;
  887. },
  888. enumerable: true,
  889. configurable: true
  890. });
  891. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  892. get: function () {
  893. return PointerEventTypes._POINTERMOVE;
  894. },
  895. enumerable: true,
  896. configurable: true
  897. });
  898. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  899. get: function () {
  900. return PointerEventTypes._POINTERWHEEL;
  901. },
  902. enumerable: true,
  903. configurable: true
  904. });
  905. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  906. get: function () {
  907. return PointerEventTypes._POINTERPICK;
  908. },
  909. enumerable: true,
  910. configurable: true
  911. });
  912. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  913. get: function () {
  914. return PointerEventTypes._POINTERTAP;
  915. },
  916. enumerable: true,
  917. configurable: true
  918. });
  919. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  920. get: function () {
  921. return PointerEventTypes._POINTERDOUBLETAP;
  922. },
  923. enumerable: true,
  924. configurable: true
  925. });
  926. PointerEventTypes._POINTERDOWN = 0x01;
  927. PointerEventTypes._POINTERUP = 0x02;
  928. PointerEventTypes._POINTERMOVE = 0x04;
  929. PointerEventTypes._POINTERWHEEL = 0x08;
  930. PointerEventTypes._POINTERPICK = 0x10;
  931. PointerEventTypes._POINTERTAP = 0x20;
  932. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  933. return PointerEventTypes;
  934. }());
  935. BABYLON.PointerEventTypes = PointerEventTypes;
  936. var PointerInfoBase = /** @class */ (function () {
  937. function PointerInfoBase(type, event) {
  938. this.type = type;
  939. this.event = event;
  940. }
  941. return PointerInfoBase;
  942. }());
  943. BABYLON.PointerInfoBase = PointerInfoBase;
  944. /**
  945. * This class is used to store pointer related info for the onPrePointerObservable event.
  946. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  947. */
  948. var PointerInfoPre = /** @class */ (function (_super) {
  949. __extends(PointerInfoPre, _super);
  950. function PointerInfoPre(type, event, localX, localY) {
  951. var _this = _super.call(this, type, event) || this;
  952. _this.skipOnPointerObservable = false;
  953. _this.localPosition = new BABYLON.Vector2(localX, localY);
  954. return _this;
  955. }
  956. return PointerInfoPre;
  957. }(PointerInfoBase));
  958. BABYLON.PointerInfoPre = PointerInfoPre;
  959. /**
  960. * This type contains all the data related to a pointer event in Babylon.js.
  961. * 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.
  962. */
  963. var PointerInfo = /** @class */ (function (_super) {
  964. __extends(PointerInfo, _super);
  965. function PointerInfo(type, event, pickInfo) {
  966. var _this = _super.call(this, type, event) || this;
  967. _this.pickInfo = pickInfo;
  968. return _this;
  969. }
  970. return PointerInfo;
  971. }(PointerInfoBase));
  972. BABYLON.PointerInfo = PointerInfo;
  973. })(BABYLON || (BABYLON = {}));
  974. //# sourceMappingURL=babylon.pointerEvents.js.map
  975. var BABYLON;
  976. (function (BABYLON) {
  977. BABYLON.ToGammaSpace = 1 / 2.2;
  978. BABYLON.ToLinearSpace = 2.2;
  979. BABYLON.Epsilon = 0.001;
  980. var Color3 = /** @class */ (function () {
  981. /**
  982. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  983. */
  984. function Color3(r, g, b) {
  985. if (r === void 0) { r = 0; }
  986. if (g === void 0) { g = 0; }
  987. if (b === void 0) { b = 0; }
  988. this.r = r;
  989. this.g = g;
  990. this.b = b;
  991. }
  992. /**
  993. * Returns a string with the Color3 current values.
  994. */
  995. Color3.prototype.toString = function () {
  996. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  997. };
  998. /**
  999. * Returns the string "Color3".
  1000. */
  1001. Color3.prototype.getClassName = function () {
  1002. return "Color3";
  1003. };
  1004. /**
  1005. * Returns the Color3 hash code.
  1006. */
  1007. Color3.prototype.getHashCode = function () {
  1008. var hash = this.r || 0;
  1009. hash = (hash * 397) ^ (this.g || 0);
  1010. hash = (hash * 397) ^ (this.b || 0);
  1011. return hash;
  1012. };
  1013. // Operators
  1014. /**
  1015. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  1016. * Returns the Color3.
  1017. */
  1018. Color3.prototype.toArray = function (array, index) {
  1019. if (index === undefined) {
  1020. index = 0;
  1021. }
  1022. array[index] = this.r;
  1023. array[index + 1] = this.g;
  1024. array[index + 2] = this.b;
  1025. return this;
  1026. };
  1027. /**
  1028. * Returns a new Color4 object from the current Color3 and the passed alpha.
  1029. */
  1030. Color3.prototype.toColor4 = function (alpha) {
  1031. if (alpha === void 0) { alpha = 1; }
  1032. return new Color4(this.r, this.g, this.b, alpha);
  1033. };
  1034. /**
  1035. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  1036. */
  1037. Color3.prototype.asArray = function () {
  1038. var result = new Array();
  1039. this.toArray(result, 0);
  1040. return result;
  1041. };
  1042. /**
  1043. * Returns the luminance value (float).
  1044. */
  1045. Color3.prototype.toLuminance = function () {
  1046. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1047. };
  1048. /**
  1049. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  1050. * Returns this new object.
  1051. */
  1052. Color3.prototype.multiply = function (otherColor) {
  1053. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1054. };
  1055. /**
  1056. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  1057. * Returns the current Color3.
  1058. */
  1059. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1060. result.r = this.r * otherColor.r;
  1061. result.g = this.g * otherColor.g;
  1062. result.b = this.b * otherColor.b;
  1063. return this;
  1064. };
  1065. /**
  1066. * Boolean : True if the rgb values are equal to the passed ones.
  1067. */
  1068. Color3.prototype.equals = function (otherColor) {
  1069. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1070. };
  1071. /**
  1072. * Boolean : True if the rgb values are equal to the passed ones.
  1073. */
  1074. Color3.prototype.equalsFloats = function (r, g, b) {
  1075. return this.r === r && this.g === g && this.b === b;
  1076. };
  1077. /**
  1078. * Multiplies in place each rgb value by scale.
  1079. * Returns the updated Color3.
  1080. */
  1081. Color3.prototype.scale = function (scale) {
  1082. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1083. };
  1084. /**
  1085. * Multiplies the rgb values by scale and stores the result into "result".
  1086. * Returns the unmodified current Color3.
  1087. */
  1088. Color3.prototype.scaleToRef = function (scale, result) {
  1089. result.r = this.r * scale;
  1090. result.g = this.g * scale;
  1091. result.b = this.b * scale;
  1092. return this;
  1093. };
  1094. /**
  1095. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  1096. */
  1097. Color3.prototype.add = function (otherColor) {
  1098. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1099. };
  1100. /**
  1101. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  1102. * Returns the unmodified current Color3.
  1103. */
  1104. Color3.prototype.addToRef = function (otherColor, result) {
  1105. result.r = this.r + otherColor.r;
  1106. result.g = this.g + otherColor.g;
  1107. result.b = this.b + otherColor.b;
  1108. return this;
  1109. };
  1110. /**
  1111. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  1112. */
  1113. Color3.prototype.subtract = function (otherColor) {
  1114. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1115. };
  1116. /**
  1117. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  1118. * Returns the unmodified current Color3.
  1119. */
  1120. Color3.prototype.subtractToRef = function (otherColor, result) {
  1121. result.r = this.r - otherColor.r;
  1122. result.g = this.g - otherColor.g;
  1123. result.b = this.b - otherColor.b;
  1124. return this;
  1125. };
  1126. /**
  1127. * Returns a new Color3 copied the current one.
  1128. */
  1129. Color3.prototype.clone = function () {
  1130. return new Color3(this.r, this.g, this.b);
  1131. };
  1132. /**
  1133. * Copies the rgb values from the source in the current Color3.
  1134. * Returns the updated Color3.
  1135. */
  1136. Color3.prototype.copyFrom = function (source) {
  1137. this.r = source.r;
  1138. this.g = source.g;
  1139. this.b = source.b;
  1140. return this;
  1141. };
  1142. /**
  1143. * Updates the Color3 rgb values from the passed floats.
  1144. * Returns the Color3.
  1145. */
  1146. Color3.prototype.copyFromFloats = function (r, g, b) {
  1147. this.r = r;
  1148. this.g = g;
  1149. this.b = b;
  1150. return this;
  1151. };
  1152. /**
  1153. * Updates the Color3 rgb values from the passed floats.
  1154. * Returns the Color3.
  1155. */
  1156. Color3.prototype.set = function (r, g, b) {
  1157. return this.copyFromFloats(r, g, b);
  1158. };
  1159. /**
  1160. * Returns the Color3 hexadecimal code as a string.
  1161. */
  1162. Color3.prototype.toHexString = function () {
  1163. var intR = (this.r * 255) | 0;
  1164. var intG = (this.g * 255) | 0;
  1165. var intB = (this.b * 255) | 0;
  1166. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1167. };
  1168. /**
  1169. * Returns a new Color3 converted to linear space.
  1170. */
  1171. Color3.prototype.toLinearSpace = function () {
  1172. var convertedColor = new Color3();
  1173. this.toLinearSpaceToRef(convertedColor);
  1174. return convertedColor;
  1175. };
  1176. /**
  1177. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  1178. * Returns the unmodified Color3.
  1179. */
  1180. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1181. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1182. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1183. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1184. return this;
  1185. };
  1186. /**
  1187. * Returns a new Color3 converted to gamma space.
  1188. */
  1189. Color3.prototype.toGammaSpace = function () {
  1190. var convertedColor = new Color3();
  1191. this.toGammaSpaceToRef(convertedColor);
  1192. return convertedColor;
  1193. };
  1194. /**
  1195. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  1196. * Returns the unmodified Color3.
  1197. */
  1198. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1199. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1200. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1201. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1202. return this;
  1203. };
  1204. // Statics
  1205. /**
  1206. * Creates a new Color3 from the string containing valid hexadecimal values.
  1207. */
  1208. Color3.FromHexString = function (hex) {
  1209. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1210. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1211. return new Color3(0, 0, 0);
  1212. }
  1213. var r = parseInt(hex.substring(1, 3), 16);
  1214. var g = parseInt(hex.substring(3, 5), 16);
  1215. var b = parseInt(hex.substring(5, 7), 16);
  1216. return Color3.FromInts(r, g, b);
  1217. };
  1218. /**
  1219. * Creates a new Vector3 from the startind index of the passed array.
  1220. */
  1221. Color3.FromArray = function (array, offset) {
  1222. if (offset === void 0) { offset = 0; }
  1223. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1224. };
  1225. /**
  1226. * Creates a new Color3 from integer values ( < 256).
  1227. */
  1228. Color3.FromInts = function (r, g, b) {
  1229. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1230. };
  1231. /**
  1232. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  1233. */
  1234. Color3.Lerp = function (start, end, amount) {
  1235. var r = start.r + ((end.r - start.r) * amount);
  1236. var g = start.g + ((end.g - start.g) * amount);
  1237. var b = start.b + ((end.b - start.b) * amount);
  1238. return new Color3(r, g, b);
  1239. };
  1240. Color3.Red = function () { return new Color3(1, 0, 0); };
  1241. Color3.Green = function () { return new Color3(0, 1, 0); };
  1242. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1243. Color3.Black = function () { return new Color3(0, 0, 0); };
  1244. Color3.White = function () { return new Color3(1, 1, 1); };
  1245. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1246. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1247. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1248. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1249. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1250. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1251. return Color3;
  1252. }());
  1253. BABYLON.Color3 = Color3;
  1254. var Color4 = /** @class */ (function () {
  1255. /**
  1256. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  1257. */
  1258. function Color4(r, g, b, a) {
  1259. if (r === void 0) { r = 0; }
  1260. if (g === void 0) { g = 0; }
  1261. if (b === void 0) { b = 0; }
  1262. if (a === void 0) { a = 1; }
  1263. this.r = r;
  1264. this.g = g;
  1265. this.b = b;
  1266. this.a = a;
  1267. }
  1268. // Operators
  1269. /**
  1270. * Adds in place the passed Color4 values to the current Color4.
  1271. * Returns the updated Color4.
  1272. */
  1273. Color4.prototype.addInPlace = function (right) {
  1274. this.r += right.r;
  1275. this.g += right.g;
  1276. this.b += right.b;
  1277. this.a += right.a;
  1278. return this;
  1279. };
  1280. /**
  1281. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  1282. */
  1283. Color4.prototype.asArray = function () {
  1284. var result = new Array();
  1285. this.toArray(result, 0);
  1286. return result;
  1287. };
  1288. /**
  1289. * Stores from the starting index in the passed array the Color4 successive values.
  1290. * Returns the Color4.
  1291. */
  1292. Color4.prototype.toArray = function (array, index) {
  1293. if (index === undefined) {
  1294. index = 0;
  1295. }
  1296. array[index] = this.r;
  1297. array[index + 1] = this.g;
  1298. array[index + 2] = this.b;
  1299. array[index + 3] = this.a;
  1300. return this;
  1301. };
  1302. /**
  1303. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  1304. */
  1305. Color4.prototype.add = function (right) {
  1306. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1307. };
  1308. /**
  1309. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  1310. */
  1311. Color4.prototype.subtract = function (right) {
  1312. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1313. };
  1314. /**
  1315. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  1316. * Returns the Color4.
  1317. */
  1318. Color4.prototype.subtractToRef = function (right, result) {
  1319. result.r = this.r - right.r;
  1320. result.g = this.g - right.g;
  1321. result.b = this.b - right.b;
  1322. result.a = this.a - right.a;
  1323. return this;
  1324. };
  1325. /**
  1326. * Creates a new Color4 with the current Color4 values multiplied by scale.
  1327. */
  1328. Color4.prototype.scale = function (scale) {
  1329. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1330. };
  1331. /**
  1332. * Multiplies the current Color4 values by scale and stores the result in "result".
  1333. * Returns the Color4.
  1334. */
  1335. Color4.prototype.scaleToRef = function (scale, result) {
  1336. result.r = this.r * scale;
  1337. result.g = this.g * scale;
  1338. result.b = this.b * scale;
  1339. result.a = this.a * scale;
  1340. return this;
  1341. };
  1342. /**
  1343. * Multipy an RGBA Color4 value by another and return a new Color4 object
  1344. * @param color The Color4 (RGBA) value to multiply by
  1345. * @returns A new Color4.
  1346. */
  1347. Color4.prototype.multiply = function (color) {
  1348. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1349. };
  1350. /**
  1351. * Multipy an RGBA Color4 value by another and push the result in a reference value
  1352. * @param color The Color4 (RGBA) value to multiply by
  1353. * @param result The Color4 (RGBA) to fill the result in
  1354. * @returns the result Color4.
  1355. */
  1356. Color4.prototype.multiplyToRef = function (color, result) {
  1357. result.r = this.r * color.r;
  1358. result.g = this.g * color.g;
  1359. result.b = this.b * color.b;
  1360. result.a = this.a * color.a;
  1361. return result;
  1362. };
  1363. /**
  1364. * Returns a string with the Color4 values.
  1365. */
  1366. Color4.prototype.toString = function () {
  1367. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1368. };
  1369. /**
  1370. * Returns the string "Color4"
  1371. */
  1372. Color4.prototype.getClassName = function () {
  1373. return "Color4";
  1374. };
  1375. /**
  1376. * Return the Color4 hash code as a number.
  1377. */
  1378. Color4.prototype.getHashCode = function () {
  1379. var hash = this.r || 0;
  1380. hash = (hash * 397) ^ (this.g || 0);
  1381. hash = (hash * 397) ^ (this.b || 0);
  1382. hash = (hash * 397) ^ (this.a || 0);
  1383. return hash;
  1384. };
  1385. /**
  1386. * Creates a new Color4 copied from the current one.
  1387. */
  1388. Color4.prototype.clone = function () {
  1389. return new Color4(this.r, this.g, this.b, this.a);
  1390. };
  1391. /**
  1392. * Copies the passed Color4 values into the current one.
  1393. * Returns the updated Color4.
  1394. */
  1395. Color4.prototype.copyFrom = function (source) {
  1396. this.r = source.r;
  1397. this.g = source.g;
  1398. this.b = source.b;
  1399. this.a = source.a;
  1400. return this;
  1401. };
  1402. /**
  1403. * Copies the passed float values into the current one.
  1404. * Returns the updated Color4.
  1405. */
  1406. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1407. this.r = r;
  1408. this.g = g;
  1409. this.b = b;
  1410. this.a = a;
  1411. return this;
  1412. };
  1413. /**
  1414. * Copies the passed float values into the current one.
  1415. * Returns the updated Color4.
  1416. */
  1417. Color4.prototype.set = function (r, g, b, a) {
  1418. return this.copyFromFloats(r, g, b, a);
  1419. };
  1420. /**
  1421. * Returns a string containing the hexadecimal Color4 code.
  1422. */
  1423. Color4.prototype.toHexString = function () {
  1424. var intR = (this.r * 255) | 0;
  1425. var intG = (this.g * 255) | 0;
  1426. var intB = (this.b * 255) | 0;
  1427. var intA = (this.a * 255) | 0;
  1428. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1429. };
  1430. /**
  1431. * Returns a new Color4 converted to linear space.
  1432. */
  1433. Color4.prototype.toLinearSpace = function () {
  1434. var convertedColor = new Color4();
  1435. this.toLinearSpaceToRef(convertedColor);
  1436. return convertedColor;
  1437. };
  1438. /**
  1439. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  1440. * Returns the unmodified Color4.
  1441. */
  1442. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  1443. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1444. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1445. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1446. convertedColor.a = this.a;
  1447. return this;
  1448. };
  1449. /**
  1450. * Returns a new Color4 converted to gamma space.
  1451. */
  1452. Color4.prototype.toGammaSpace = function () {
  1453. var convertedColor = new Color4();
  1454. this.toGammaSpaceToRef(convertedColor);
  1455. return convertedColor;
  1456. };
  1457. /**
  1458. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  1459. * Returns the unmodified Color4.
  1460. */
  1461. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  1462. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1463. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1464. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1465. convertedColor.a = this.a;
  1466. return this;
  1467. };
  1468. // Statics
  1469. /**
  1470. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  1471. */
  1472. Color4.FromHexString = function (hex) {
  1473. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  1474. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  1475. return new Color4(0.0, 0.0, 0.0, 0.0);
  1476. }
  1477. var r = parseInt(hex.substring(1, 3), 16);
  1478. var g = parseInt(hex.substring(3, 5), 16);
  1479. var b = parseInt(hex.substring(5, 7), 16);
  1480. var a = parseInt(hex.substring(7, 9), 16);
  1481. return Color4.FromInts(r, g, b, a);
  1482. };
  1483. /**
  1484. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1485. */
  1486. Color4.Lerp = function (left, right, amount) {
  1487. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  1488. Color4.LerpToRef(left, right, amount, result);
  1489. return result;
  1490. };
  1491. /**
  1492. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  1493. */
  1494. Color4.LerpToRef = function (left, right, amount, result) {
  1495. result.r = left.r + (right.r - left.r) * amount;
  1496. result.g = left.g + (right.g - left.g) * amount;
  1497. result.b = left.b + (right.b - left.b) * amount;
  1498. result.a = left.a + (right.a - left.a) * amount;
  1499. };
  1500. /**
  1501. * Creates a new Color4 from the starting index element of the passed array.
  1502. */
  1503. Color4.FromArray = function (array, offset) {
  1504. if (offset === void 0) { offset = 0; }
  1505. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1506. };
  1507. /**
  1508. * Creates a new Color4 from the passed integers ( < 256 ).
  1509. */
  1510. Color4.FromInts = function (r, g, b, a) {
  1511. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  1512. };
  1513. Color4.CheckColors4 = function (colors, count) {
  1514. // Check if color3 was used
  1515. if (colors.length === count * 3) {
  1516. var colors4 = [];
  1517. for (var index = 0; index < colors.length; index += 3) {
  1518. var newIndex = (index / 3) * 4;
  1519. colors4[newIndex] = colors[index];
  1520. colors4[newIndex + 1] = colors[index + 1];
  1521. colors4[newIndex + 2] = colors[index + 2];
  1522. colors4[newIndex + 3] = 1.0;
  1523. }
  1524. return colors4;
  1525. }
  1526. return colors;
  1527. };
  1528. return Color4;
  1529. }());
  1530. BABYLON.Color4 = Color4;
  1531. var Vector2 = /** @class */ (function () {
  1532. /**
  1533. * Creates a new Vector2 from the passed x and y coordinates.
  1534. */
  1535. function Vector2(x, y) {
  1536. this.x = x;
  1537. this.y = y;
  1538. }
  1539. /**
  1540. * Returns a string with the Vector2 coordinates.
  1541. */
  1542. Vector2.prototype.toString = function () {
  1543. return "{X: " + this.x + " Y:" + this.y + "}";
  1544. };
  1545. /**
  1546. * Returns the string "Vector2"
  1547. */
  1548. Vector2.prototype.getClassName = function () {
  1549. return "Vector2";
  1550. };
  1551. /**
  1552. * Returns the Vector2 hash code as a number.
  1553. */
  1554. Vector2.prototype.getHashCode = function () {
  1555. var hash = this.x || 0;
  1556. hash = (hash * 397) ^ (this.y || 0);
  1557. return hash;
  1558. };
  1559. // Operators
  1560. /**
  1561. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  1562. * Returns the Vector2.
  1563. */
  1564. Vector2.prototype.toArray = function (array, index) {
  1565. if (index === void 0) { index = 0; }
  1566. array[index] = this.x;
  1567. array[index + 1] = this.y;
  1568. return this;
  1569. };
  1570. /**
  1571. * Returns a new array with 2 elements : the Vector2 coordinates.
  1572. */
  1573. Vector2.prototype.asArray = function () {
  1574. var result = new Array();
  1575. this.toArray(result, 0);
  1576. return result;
  1577. };
  1578. /**
  1579. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  1580. * Returns the updated Vector2.
  1581. */
  1582. Vector2.prototype.copyFrom = function (source) {
  1583. this.x = source.x;
  1584. this.y = source.y;
  1585. return this;
  1586. };
  1587. /**
  1588. * Sets the Vector2 coordinates with the passed floats.
  1589. * Returns the updated Vector2.
  1590. */
  1591. Vector2.prototype.copyFromFloats = function (x, y) {
  1592. this.x = x;
  1593. this.y = y;
  1594. return this;
  1595. };
  1596. /**
  1597. * Sets the Vector2 coordinates with the passed floats.
  1598. * Returns the updated Vector2.
  1599. */
  1600. Vector2.prototype.set = function (x, y) {
  1601. return this.copyFromFloats(x, y);
  1602. };
  1603. /**
  1604. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  1605. */
  1606. Vector2.prototype.add = function (otherVector) {
  1607. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1608. };
  1609. /**
  1610. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  1611. * Returns the Vector2.
  1612. */
  1613. Vector2.prototype.addToRef = function (otherVector, result) {
  1614. result.x = this.x + otherVector.x;
  1615. result.y = this.y + otherVector.y;
  1616. return this;
  1617. };
  1618. /**
  1619. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  1620. * Returns the updated Vector2.
  1621. */
  1622. Vector2.prototype.addInPlace = function (otherVector) {
  1623. this.x += otherVector.x;
  1624. this.y += otherVector.y;
  1625. return this;
  1626. };
  1627. /**
  1628. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  1629. */
  1630. Vector2.prototype.addVector3 = function (otherVector) {
  1631. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  1632. };
  1633. /**
  1634. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  1635. */
  1636. Vector2.prototype.subtract = function (otherVector) {
  1637. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  1638. };
  1639. /**
  1640. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  1641. * Returns the Vector2.
  1642. */
  1643. Vector2.prototype.subtractToRef = function (otherVector, result) {
  1644. result.x = this.x - otherVector.x;
  1645. result.y = this.y - otherVector.y;
  1646. return this;
  1647. };
  1648. /**
  1649. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  1650. * Returns the updated Vector2.
  1651. */
  1652. Vector2.prototype.subtractInPlace = function (otherVector) {
  1653. this.x -= otherVector.x;
  1654. this.y -= otherVector.y;
  1655. return this;
  1656. };
  1657. /**
  1658. * Multiplies in place the current Vector2 coordinates by the passed ones.
  1659. * Returns the updated Vector2.
  1660. */
  1661. Vector2.prototype.multiplyInPlace = function (otherVector) {
  1662. this.x *= otherVector.x;
  1663. this.y *= otherVector.y;
  1664. return this;
  1665. };
  1666. /**
  1667. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  1668. */
  1669. Vector2.prototype.multiply = function (otherVector) {
  1670. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  1671. };
  1672. /**
  1673. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  1674. * Returns the Vector2.
  1675. */
  1676. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  1677. result.x = this.x * otherVector.x;
  1678. result.y = this.y * otherVector.y;
  1679. return this;
  1680. };
  1681. /**
  1682. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  1683. */
  1684. Vector2.prototype.multiplyByFloats = function (x, y) {
  1685. return new Vector2(this.x * x, this.y * y);
  1686. };
  1687. /**
  1688. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  1689. */
  1690. Vector2.prototype.divide = function (otherVector) {
  1691. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  1692. };
  1693. /**
  1694. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  1695. * Returns the Vector2.
  1696. */
  1697. Vector2.prototype.divideToRef = function (otherVector, result) {
  1698. result.x = this.x / otherVector.x;
  1699. result.y = this.y / otherVector.y;
  1700. return this;
  1701. };
  1702. /**
  1703. * Divides the current Vector3 coordinates by the passed ones.
  1704. * Returns the updated Vector3.
  1705. */
  1706. Vector2.prototype.divideInPlace = function (otherVector) {
  1707. return this.divideToRef(otherVector, this);
  1708. };
  1709. /**
  1710. * Returns a new Vector2 with current Vector2 negated coordinates.
  1711. */
  1712. Vector2.prototype.negate = function () {
  1713. return new Vector2(-this.x, -this.y);
  1714. };
  1715. /**
  1716. * Multiply the Vector2 coordinates by scale.
  1717. * Returns the updated Vector2.
  1718. */
  1719. Vector2.prototype.scaleInPlace = function (scale) {
  1720. this.x *= scale;
  1721. this.y *= scale;
  1722. return this;
  1723. };
  1724. /**
  1725. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  1726. */
  1727. Vector2.prototype.scale = function (scale) {
  1728. return new Vector2(this.x * scale, this.y * scale);
  1729. };
  1730. /**
  1731. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  1732. */
  1733. Vector2.prototype.equals = function (otherVector) {
  1734. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  1735. };
  1736. /**
  1737. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  1738. */
  1739. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1740. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1741. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  1742. };
  1743. // Properties
  1744. /**
  1745. * Returns the vector length (float).
  1746. */
  1747. Vector2.prototype.length = function () {
  1748. return Math.sqrt(this.x * this.x + this.y * this.y);
  1749. };
  1750. /**
  1751. * Returns the vector squared length (float);
  1752. */
  1753. Vector2.prototype.lengthSquared = function () {
  1754. return (this.x * this.x + this.y * this.y);
  1755. };
  1756. // Methods
  1757. /**
  1758. * Normalize the vector.
  1759. * Returns the updated Vector2.
  1760. */
  1761. Vector2.prototype.normalize = function () {
  1762. var len = this.length();
  1763. if (len === 0)
  1764. return this;
  1765. var num = 1.0 / len;
  1766. this.x *= num;
  1767. this.y *= num;
  1768. return this;
  1769. };
  1770. /**
  1771. * Returns a new Vector2 copied from the Vector2.
  1772. */
  1773. Vector2.prototype.clone = function () {
  1774. return new Vector2(this.x, this.y);
  1775. };
  1776. // Statics
  1777. /**
  1778. * Returns a new Vector2(0, 0)
  1779. */
  1780. Vector2.Zero = function () {
  1781. return new Vector2(0, 0);
  1782. };
  1783. /**
  1784. * Returns a new Vector2(1, 1)
  1785. */
  1786. Vector2.One = function () {
  1787. return new Vector2(1, 1);
  1788. };
  1789. /**
  1790. * Returns a new Vector2 set from the passed index element of the passed array.
  1791. */
  1792. Vector2.FromArray = function (array, offset) {
  1793. if (offset === void 0) { offset = 0; }
  1794. return new Vector2(array[offset], array[offset + 1]);
  1795. };
  1796. /**
  1797. * Sets "result" from the passed index element of the passed array.
  1798. */
  1799. Vector2.FromArrayToRef = function (array, offset, result) {
  1800. result.x = array[offset];
  1801. result.y = array[offset + 1];
  1802. };
  1803. /**
  1804. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  1805. */
  1806. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  1807. var squared = amount * amount;
  1808. var cubed = amount * squared;
  1809. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1810. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1811. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1812. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1813. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1814. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1815. return new Vector2(x, y);
  1816. };
  1817. /**
  1818. * 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".
  1819. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1820. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1821. */
  1822. Vector2.Clamp = function (value, min, max) {
  1823. var x = value.x;
  1824. x = (x > max.x) ? max.x : x;
  1825. x = (x < min.x) ? min.x : x;
  1826. var y = value.y;
  1827. y = (y > max.y) ? max.y : y;
  1828. y = (y < min.y) ? min.y : y;
  1829. return new Vector2(x, y);
  1830. };
  1831. /**
  1832. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1833. */
  1834. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1835. var squared = amount * amount;
  1836. var cubed = amount * squared;
  1837. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1838. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1839. var part3 = (cubed - (2.0 * squared)) + amount;
  1840. var part4 = cubed - squared;
  1841. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1842. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1843. return new Vector2(x, y);
  1844. };
  1845. /**
  1846. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1847. */
  1848. Vector2.Lerp = function (start, end, amount) {
  1849. var x = start.x + ((end.x - start.x) * amount);
  1850. var y = start.y + ((end.y - start.y) * amount);
  1851. return new Vector2(x, y);
  1852. };
  1853. /**
  1854. * Returns the dot product (float) of the vector "left" and the vector "right".
  1855. */
  1856. Vector2.Dot = function (left, right) {
  1857. return left.x * right.x + left.y * right.y;
  1858. };
  1859. /**
  1860. * Returns a new Vector2 equal to the normalized passed vector.
  1861. */
  1862. Vector2.Normalize = function (vector) {
  1863. var newVector = vector.clone();
  1864. newVector.normalize();
  1865. return newVector;
  1866. };
  1867. /**
  1868. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1869. */
  1870. Vector2.Minimize = function (left, right) {
  1871. var x = (left.x < right.x) ? left.x : right.x;
  1872. var y = (left.y < right.y) ? left.y : right.y;
  1873. return new Vector2(x, y);
  1874. };
  1875. /**
  1876. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1877. */
  1878. Vector2.Maximize = function (left, right) {
  1879. var x = (left.x > right.x) ? left.x : right.x;
  1880. var y = (left.y > right.y) ? left.y : right.y;
  1881. return new Vector2(x, y);
  1882. };
  1883. /**
  1884. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1885. */
  1886. Vector2.Transform = function (vector, transformation) {
  1887. var r = Vector2.Zero();
  1888. Vector2.TransformToRef(vector, transformation, r);
  1889. return r;
  1890. };
  1891. /**
  1892. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1893. */
  1894. Vector2.TransformToRef = function (vector, transformation, result) {
  1895. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1896. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1897. result.x = x;
  1898. result.y = y;
  1899. };
  1900. /**
  1901. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1902. */
  1903. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1904. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1905. var sign = a < 0 ? -1 : 1;
  1906. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1907. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1908. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1909. };
  1910. /**
  1911. * Returns the distance (float) between the vectors "value1" and "value2".
  1912. */
  1913. Vector2.Distance = function (value1, value2) {
  1914. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1915. };
  1916. /**
  1917. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1918. */
  1919. Vector2.DistanceSquared = function (value1, value2) {
  1920. var x = value1.x - value2.x;
  1921. var y = value1.y - value2.y;
  1922. return (x * x) + (y * y);
  1923. };
  1924. /**
  1925. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1926. */
  1927. Vector2.Center = function (value1, value2) {
  1928. var center = value1.add(value2);
  1929. center.scaleInPlace(0.5);
  1930. return center;
  1931. };
  1932. /**
  1933. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1934. */
  1935. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1936. var l2 = Vector2.DistanceSquared(segA, segB);
  1937. if (l2 === 0.0) {
  1938. return Vector2.Distance(p, segA);
  1939. }
  1940. var v = segB.subtract(segA);
  1941. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1942. var proj = segA.add(v.multiplyByFloats(t, t));
  1943. return Vector2.Distance(p, proj);
  1944. };
  1945. return Vector2;
  1946. }());
  1947. BABYLON.Vector2 = Vector2;
  1948. var Vector3 = /** @class */ (function () {
  1949. /**
  1950. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1951. * A Vector3 is the main object used in 3D geometry.
  1952. * It can represent etiher the coordinates of a point the space, either a direction.
  1953. */
  1954. function Vector3(x, y, z) {
  1955. this.x = x;
  1956. this.y = y;
  1957. this.z = z;
  1958. }
  1959. /**
  1960. * Returns a string with the Vector3 coordinates.
  1961. */
  1962. Vector3.prototype.toString = function () {
  1963. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1964. };
  1965. /**
  1966. * Returns the string "Vector3"
  1967. */
  1968. Vector3.prototype.getClassName = function () {
  1969. return "Vector3";
  1970. };
  1971. /**
  1972. * Returns the Vector hash code.
  1973. */
  1974. Vector3.prototype.getHashCode = function () {
  1975. var hash = this.x || 0;
  1976. hash = (hash * 397) ^ (this.y || 0);
  1977. hash = (hash * 397) ^ (this.z || 0);
  1978. return hash;
  1979. };
  1980. // Operators
  1981. /**
  1982. * Returns a new array with three elements : the coordinates the Vector3.
  1983. */
  1984. Vector3.prototype.asArray = function () {
  1985. var result = [];
  1986. this.toArray(result, 0);
  1987. return result;
  1988. };
  1989. /**
  1990. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1991. * Returns the Vector3.
  1992. */
  1993. Vector3.prototype.toArray = function (array, index) {
  1994. if (index === void 0) { index = 0; }
  1995. array[index] = this.x;
  1996. array[index + 1] = this.y;
  1997. array[index + 2] = this.z;
  1998. return this;
  1999. };
  2000. /**
  2001. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  2002. */
  2003. Vector3.prototype.toQuaternion = function () {
  2004. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2005. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2006. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2007. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2008. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2009. var cosy = Math.cos(this.y * 0.5);
  2010. var siny = Math.sin(this.y * 0.5);
  2011. result.x = coszMinusx * siny;
  2012. result.y = -sinzMinusx * siny;
  2013. result.z = sinxPlusz * cosy;
  2014. result.w = cosxPlusz * cosy;
  2015. return result;
  2016. };
  2017. /**
  2018. * Adds the passed vector to the current Vector3.
  2019. * Returns the updated Vector3.
  2020. */
  2021. Vector3.prototype.addInPlace = function (otherVector) {
  2022. this.x += otherVector.x;
  2023. this.y += otherVector.y;
  2024. this.z += otherVector.z;
  2025. return this;
  2026. };
  2027. /**
  2028. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  2029. */
  2030. Vector3.prototype.add = function (otherVector) {
  2031. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2032. };
  2033. /**
  2034. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  2035. * Returns the current Vector3.
  2036. */
  2037. Vector3.prototype.addToRef = function (otherVector, result) {
  2038. result.x = this.x + otherVector.x;
  2039. result.y = this.y + otherVector.y;
  2040. result.z = this.z + otherVector.z;
  2041. return this;
  2042. };
  2043. /**
  2044. * Subtract the passed vector from the current Vector3.
  2045. * Returns the updated Vector3.
  2046. */
  2047. Vector3.prototype.subtractInPlace = function (otherVector) {
  2048. this.x -= otherVector.x;
  2049. this.y -= otherVector.y;
  2050. this.z -= otherVector.z;
  2051. return this;
  2052. };
  2053. /**
  2054. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  2055. */
  2056. Vector3.prototype.subtract = function (otherVector) {
  2057. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2058. };
  2059. /**
  2060. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2061. * Returns the current Vector3.
  2062. */
  2063. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2064. result.x = this.x - otherVector.x;
  2065. result.y = this.y - otherVector.y;
  2066. result.z = this.z - otherVector.z;
  2067. return this;
  2068. };
  2069. /**
  2070. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  2071. */
  2072. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2073. return new Vector3(this.x - x, this.y - y, this.z - z);
  2074. };
  2075. /**
  2076. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  2077. * Returns the current Vector3.
  2078. */
  2079. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2080. result.x = this.x - x;
  2081. result.y = this.y - y;
  2082. result.z = this.z - z;
  2083. return this;
  2084. };
  2085. /**
  2086. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  2087. */
  2088. Vector3.prototype.negate = function () {
  2089. return new Vector3(-this.x, -this.y, -this.z);
  2090. };
  2091. /**
  2092. * Multiplies the Vector3 coordinates by the float "scale".
  2093. * Returns the updated Vector3.
  2094. */
  2095. Vector3.prototype.scaleInPlace = function (scale) {
  2096. this.x *= scale;
  2097. this.y *= scale;
  2098. this.z *= scale;
  2099. return this;
  2100. };
  2101. /**
  2102. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  2103. */
  2104. Vector3.prototype.scale = function (scale) {
  2105. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2106. };
  2107. /**
  2108. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  2109. * Returns the current Vector3.
  2110. */
  2111. Vector3.prototype.scaleToRef = function (scale, result) {
  2112. result.x = this.x * scale;
  2113. result.y = this.y * scale;
  2114. result.z = this.z * scale;
  2115. return this;
  2116. };
  2117. /**
  2118. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  2119. */
  2120. Vector3.prototype.equals = function (otherVector) {
  2121. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2122. };
  2123. /**
  2124. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  2125. */
  2126. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2127. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2128. 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);
  2129. };
  2130. /**
  2131. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  2132. */
  2133. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2134. return this.x === x && this.y === y && this.z === z;
  2135. };
  2136. /**
  2137. * Muliplies the current Vector3 coordinates by the passed ones.
  2138. * Returns the updated Vector3.
  2139. */
  2140. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2141. this.x *= otherVector.x;
  2142. this.y *= otherVector.y;
  2143. this.z *= otherVector.z;
  2144. return this;
  2145. };
  2146. /**
  2147. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  2148. */
  2149. Vector3.prototype.multiply = function (otherVector) {
  2150. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2151. };
  2152. /**
  2153. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  2154. * Returns the current Vector3.
  2155. */
  2156. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2157. result.x = this.x * otherVector.x;
  2158. result.y = this.y * otherVector.y;
  2159. result.z = this.z * otherVector.z;
  2160. return this;
  2161. };
  2162. /**
  2163. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  2164. */
  2165. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2166. return new Vector3(this.x * x, this.y * y, this.z * z);
  2167. };
  2168. /**
  2169. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  2170. */
  2171. Vector3.prototype.divide = function (otherVector) {
  2172. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2173. };
  2174. /**
  2175. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  2176. * Returns the current Vector3.
  2177. */
  2178. Vector3.prototype.divideToRef = function (otherVector, result) {
  2179. result.x = this.x / otherVector.x;
  2180. result.y = this.y / otherVector.y;
  2181. result.z = this.z / otherVector.z;
  2182. return this;
  2183. };
  2184. /**
  2185. * Divides the current Vector3 coordinates by the passed ones.
  2186. * Returns the updated Vector3.
  2187. */
  2188. Vector3.prototype.divideInPlace = function (otherVector) {
  2189. return this.divideToRef(otherVector, this);
  2190. };
  2191. /**
  2192. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  2193. * Returns the updated Vector3.
  2194. */
  2195. Vector3.prototype.MinimizeInPlace = function (other) {
  2196. if (other.x < this.x)
  2197. this.x = other.x;
  2198. if (other.y < this.y)
  2199. this.y = other.y;
  2200. if (other.z < this.z)
  2201. this.z = other.z;
  2202. return this;
  2203. };
  2204. /**
  2205. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2206. * Returns the updated Vector3.
  2207. */
  2208. Vector3.prototype.MaximizeInPlace = function (other) {
  2209. if (other.x > this.x)
  2210. this.x = other.x;
  2211. if (other.y > this.y)
  2212. this.y = other.y;
  2213. if (other.z > this.z)
  2214. this.z = other.z;
  2215. return this;
  2216. };
  2217. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2218. /**
  2219. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  2220. */
  2221. get: function () {
  2222. var absX = Math.abs(this.x);
  2223. var absY = Math.abs(this.y);
  2224. if (absX !== absY) {
  2225. return true;
  2226. }
  2227. var absZ = Math.abs(this.z);
  2228. if (absX !== absZ) {
  2229. return true;
  2230. }
  2231. if (absY !== absZ) {
  2232. return true;
  2233. }
  2234. return false;
  2235. },
  2236. enumerable: true,
  2237. configurable: true
  2238. });
  2239. // Properties
  2240. /**
  2241. * Returns the length of the Vector3 (float).
  2242. */
  2243. Vector3.prototype.length = function () {
  2244. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2245. };
  2246. /**
  2247. * Returns the squared length of the Vector3 (float).
  2248. */
  2249. Vector3.prototype.lengthSquared = function () {
  2250. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2251. };
  2252. /**
  2253. * Normalize the current Vector3.
  2254. * Returns the updated Vector3.
  2255. * /!\ In place operation.
  2256. */
  2257. Vector3.prototype.normalize = function () {
  2258. var len = this.length();
  2259. if (len === 0 || len === 1.0)
  2260. return this;
  2261. var num = 1.0 / len;
  2262. this.x *= num;
  2263. this.y *= num;
  2264. this.z *= num;
  2265. return this;
  2266. };
  2267. /**
  2268. * Normalize the current Vector3 to a new vector.
  2269. * @returns the new Vector3.
  2270. */
  2271. Vector3.prototype.normalizeToNew = function () {
  2272. var normalized = new Vector3(0, 0, 0);
  2273. this.normalizeToRef(normalized);
  2274. return normalized;
  2275. };
  2276. /**
  2277. * Normalize the current Vector3 to the reference.
  2278. * @param the reference to update.
  2279. * @returns the updated Vector3.
  2280. */
  2281. Vector3.prototype.normalizeToRef = function (reference) {
  2282. var len = this.length();
  2283. if (len === 0 || len === 1.0) {
  2284. reference.set(this.x, this.y, this.z);
  2285. return reference;
  2286. }
  2287. var scale = 1.0 / len;
  2288. this.scaleToRef(scale, reference);
  2289. return reference;
  2290. };
  2291. /**
  2292. * Returns a new Vector3 copied from the current Vector3.
  2293. */
  2294. Vector3.prototype.clone = function () {
  2295. return new Vector3(this.x, this.y, this.z);
  2296. };
  2297. /**
  2298. * Copies the passed vector coordinates to the current Vector3 ones.
  2299. * Returns the updated Vector3.
  2300. */
  2301. Vector3.prototype.copyFrom = function (source) {
  2302. this.x = source.x;
  2303. this.y = source.y;
  2304. this.z = source.z;
  2305. return this;
  2306. };
  2307. /**
  2308. * Copies the passed floats to the current Vector3 coordinates.
  2309. * Returns the updated Vector3.
  2310. */
  2311. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2312. this.x = x;
  2313. this.y = y;
  2314. this.z = z;
  2315. return this;
  2316. };
  2317. /**
  2318. * Copies the passed floats to the current Vector3 coordinates.
  2319. * Returns the updated Vector3.
  2320. */
  2321. Vector3.prototype.set = function (x, y, z) {
  2322. return this.copyFromFloats(x, y, z);
  2323. };
  2324. // Statics
  2325. /**
  2326. *
  2327. */
  2328. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  2329. var d0 = Vector3.Dot(vector0, axis) - size;
  2330. var d1 = Vector3.Dot(vector1, axis) - size;
  2331. var s = d0 / (d0 - d1);
  2332. return s;
  2333. };
  2334. /**
  2335. * Returns a new Vector3 set from the index "offset" of the passed array.
  2336. */
  2337. Vector3.FromArray = function (array, offset) {
  2338. if (!offset) {
  2339. offset = 0;
  2340. }
  2341. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  2342. };
  2343. /**
  2344. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  2345. * This function is deprecated. Use FromArray instead.
  2346. */
  2347. Vector3.FromFloatArray = function (array, offset) {
  2348. return Vector3.FromArray(array, offset);
  2349. };
  2350. /**
  2351. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  2352. */
  2353. Vector3.FromArrayToRef = function (array, offset, result) {
  2354. result.x = array[offset];
  2355. result.y = array[offset + 1];
  2356. result.z = array[offset + 2];
  2357. };
  2358. /**
  2359. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  2360. * This function is deprecated. Use FromArrayToRef instead.
  2361. */
  2362. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  2363. return Vector3.FromArrayToRef(array, offset, result);
  2364. };
  2365. /**
  2366. * Sets the passed vector "result" with the passed floats.
  2367. */
  2368. Vector3.FromFloatsToRef = function (x, y, z, result) {
  2369. result.x = x;
  2370. result.y = y;
  2371. result.z = z;
  2372. };
  2373. /**
  2374. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  2375. */
  2376. Vector3.Zero = function () {
  2377. return new Vector3(0.0, 0.0, 0.0);
  2378. };
  2379. /**
  2380. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  2381. */
  2382. Vector3.One = function () {
  2383. return new Vector3(1.0, 1.0, 1.0);
  2384. };
  2385. /**
  2386. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  2387. */
  2388. Vector3.Up = function () {
  2389. return new Vector3(0.0, 1.0, 0.0);
  2390. };
  2391. /**
  2392. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  2393. */
  2394. Vector3.Forward = function () {
  2395. return new Vector3(0.0, 0.0, 1.0);
  2396. };
  2397. /**
  2398. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  2399. */
  2400. Vector3.Right = function () {
  2401. return new Vector3(1.0, 0.0, 0.0);
  2402. };
  2403. /**
  2404. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  2405. */
  2406. Vector3.Left = function () {
  2407. return new Vector3(-1.0, 0.0, 0.0);
  2408. };
  2409. /**
  2410. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  2411. * This method computes tranformed coordinates only, not transformed direction vectors.
  2412. */
  2413. Vector3.TransformCoordinates = function (vector, transformation) {
  2414. var result = Vector3.Zero();
  2415. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  2416. return result;
  2417. };
  2418. /**
  2419. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  2420. * This method computes tranformed coordinates only, not transformed direction vectors.
  2421. */
  2422. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  2423. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  2424. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  2425. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  2426. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  2427. result.x = x / w;
  2428. result.y = y / w;
  2429. result.z = z / w;
  2430. };
  2431. /**
  2432. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  2433. * This method computes tranformed coordinates only, not transformed direction vectors.
  2434. */
  2435. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  2436. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  2437. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  2438. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  2439. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  2440. result.x = rx / rw;
  2441. result.y = ry / rw;
  2442. result.z = rz / rw;
  2443. };
  2444. /**
  2445. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  2446. * This methods computes transformed normalized direction vectors only.
  2447. */
  2448. Vector3.TransformNormal = function (vector, transformation) {
  2449. var result = Vector3.Zero();
  2450. Vector3.TransformNormalToRef(vector, transformation, result);
  2451. return result;
  2452. };
  2453. /**
  2454. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2455. * This methods computes transformed normalized direction vectors only.
  2456. */
  2457. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  2458. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2459. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2460. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2461. result.x = x;
  2462. result.y = y;
  2463. result.z = z;
  2464. };
  2465. /**
  2466. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  2467. * This methods computes transformed normalized direction vectors only.
  2468. */
  2469. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  2470. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2471. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2472. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2473. };
  2474. /**
  2475. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  2476. */
  2477. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  2478. var squared = amount * amount;
  2479. var cubed = amount * squared;
  2480. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2481. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2482. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2483. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2484. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2485. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2486. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  2487. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  2488. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  2489. return new Vector3(x, y, z);
  2490. };
  2491. /**
  2492. * 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".
  2493. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  2494. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  2495. */
  2496. Vector3.Clamp = function (value, min, max) {
  2497. var x = value.x;
  2498. x = (x > max.x) ? max.x : x;
  2499. x = (x < min.x) ? min.x : x;
  2500. var y = value.y;
  2501. y = (y > max.y) ? max.y : y;
  2502. y = (y < min.y) ? min.y : y;
  2503. var z = value.z;
  2504. z = (z > max.z) ? max.z : z;
  2505. z = (z < min.z) ? min.z : z;
  2506. return new Vector3(x, y, z);
  2507. };
  2508. /**
  2509. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2510. */
  2511. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2512. var squared = amount * amount;
  2513. var cubed = amount * squared;
  2514. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2515. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2516. var part3 = (cubed - (2.0 * squared)) + amount;
  2517. var part4 = cubed - squared;
  2518. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2519. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2520. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2521. return new Vector3(x, y, z);
  2522. };
  2523. /**
  2524. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  2525. */
  2526. Vector3.Lerp = function (start, end, amount) {
  2527. var result = new Vector3(0, 0, 0);
  2528. Vector3.LerpToRef(start, end, amount, result);
  2529. return result;
  2530. };
  2531. /**
  2532. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  2533. */
  2534. Vector3.LerpToRef = function (start, end, amount, result) {
  2535. result.x = start.x + ((end.x - start.x) * amount);
  2536. result.y = start.y + ((end.y - start.y) * amount);
  2537. result.z = start.z + ((end.z - start.z) * amount);
  2538. };
  2539. /**
  2540. * Returns the dot product (float) between the vectors "left" and "right".
  2541. */
  2542. Vector3.Dot = function (left, right) {
  2543. return (left.x * right.x + left.y * right.y + left.z * right.z);
  2544. };
  2545. /**
  2546. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  2547. * The cross product is then orthogonal to both "left" and "right".
  2548. */
  2549. Vector3.Cross = function (left, right) {
  2550. var result = Vector3.Zero();
  2551. Vector3.CrossToRef(left, right, result);
  2552. return result;
  2553. };
  2554. /**
  2555. * Sets the passed vector "result" with the cross product of "left" and "right".
  2556. * The cross product is then orthogonal to both "left" and "right".
  2557. */
  2558. Vector3.CrossToRef = function (left, right, result) {
  2559. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  2560. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  2561. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  2562. result.copyFrom(MathTmp.Vector3[0]);
  2563. };
  2564. /**
  2565. * Returns a new Vector3 as the normalization of the passed vector.
  2566. */
  2567. Vector3.Normalize = function (vector) {
  2568. var result = Vector3.Zero();
  2569. Vector3.NormalizeToRef(vector, result);
  2570. return result;
  2571. };
  2572. /**
  2573. * Sets the passed vector "result" with the normalization of the passed first vector.
  2574. */
  2575. Vector3.NormalizeToRef = function (vector, result) {
  2576. result.copyFrom(vector);
  2577. result.normalize();
  2578. };
  2579. Vector3.Project = function (vector, world, transform, viewport) {
  2580. var cw = viewport.width;
  2581. var ch = viewport.height;
  2582. var cx = viewport.x;
  2583. var cy = viewport.y;
  2584. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  2585. 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);
  2586. var matrix = MathTmp.Matrix[0];
  2587. world.multiplyToRef(transform, matrix);
  2588. matrix.multiplyToRef(viewportMatrix, matrix);
  2589. return Vector3.TransformCoordinates(vector, matrix);
  2590. };
  2591. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  2592. var matrix = MathTmp.Matrix[0];
  2593. world.multiplyToRef(transform, matrix);
  2594. matrix.invert();
  2595. source.x = source.x / viewportWidth * 2 - 1;
  2596. source.y = -(source.y / viewportHeight * 2 - 1);
  2597. var vector = Vector3.TransformCoordinates(source, matrix);
  2598. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  2599. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2600. vector = vector.scale(1.0 / num);
  2601. }
  2602. return vector;
  2603. };
  2604. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  2605. var result = Vector3.Zero();
  2606. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  2607. return result;
  2608. };
  2609. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  2610. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  2611. };
  2612. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  2613. var matrix = MathTmp.Matrix[0];
  2614. world.multiplyToRef(view, matrix);
  2615. matrix.multiplyToRef(projection, matrix);
  2616. matrix.invert();
  2617. var screenSource = MathTmp.Vector3[0];
  2618. screenSource.x = sourceX / viewportWidth * 2 - 1;
  2619. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  2620. screenSource.z = 2 * sourceZ - 1.0;
  2621. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  2622. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  2623. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  2624. result.scaleInPlace(1.0 / num);
  2625. }
  2626. };
  2627. Vector3.Minimize = function (left, right) {
  2628. var min = left.clone();
  2629. min.MinimizeInPlace(right);
  2630. return min;
  2631. };
  2632. Vector3.Maximize = function (left, right) {
  2633. var max = left.clone();
  2634. max.MaximizeInPlace(right);
  2635. return max;
  2636. };
  2637. /**
  2638. * Returns the distance (float) between the vectors "value1" and "value2".
  2639. */
  2640. Vector3.Distance = function (value1, value2) {
  2641. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  2642. };
  2643. /**
  2644. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2645. */
  2646. Vector3.DistanceSquared = function (value1, value2) {
  2647. var x = value1.x - value2.x;
  2648. var y = value1.y - value2.y;
  2649. var z = value1.z - value2.z;
  2650. return (x * x) + (y * y) + (z * z);
  2651. };
  2652. /**
  2653. * Returns a new Vector3 located at the center between "value1" and "value2".
  2654. */
  2655. Vector3.Center = function (value1, value2) {
  2656. var center = value1.add(value2);
  2657. center.scaleInPlace(0.5);
  2658. return center;
  2659. };
  2660. /**
  2661. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  2662. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  2663. * to something in order to rotate it from its local system to the given target system.
  2664. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2665. * Returns a new Vector3.
  2666. */
  2667. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  2668. var rotation = Vector3.Zero();
  2669. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  2670. return rotation;
  2671. };
  2672. /**
  2673. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  2674. */
  2675. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2676. var quat = MathTmp.Quaternion[0];
  2677. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2678. quat.toEulerAnglesToRef(ref);
  2679. };
  2680. return Vector3;
  2681. }());
  2682. BABYLON.Vector3 = Vector3;
  2683. //Vector4 class created for EulerAngle class conversion to Quaternion
  2684. var Vector4 = /** @class */ (function () {
  2685. /**
  2686. * Creates a Vector4 object from the passed floats.
  2687. */
  2688. function Vector4(x, y, z, w) {
  2689. this.x = x;
  2690. this.y = y;
  2691. this.z = z;
  2692. this.w = w;
  2693. }
  2694. /**
  2695. * Returns the string with the Vector4 coordinates.
  2696. */
  2697. Vector4.prototype.toString = function () {
  2698. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2699. };
  2700. /**
  2701. * Returns the string "Vector4".
  2702. */
  2703. Vector4.prototype.getClassName = function () {
  2704. return "Vector4";
  2705. };
  2706. /**
  2707. * Returns the Vector4 hash code.
  2708. */
  2709. Vector4.prototype.getHashCode = function () {
  2710. var hash = this.x || 0;
  2711. hash = (hash * 397) ^ (this.y || 0);
  2712. hash = (hash * 397) ^ (this.z || 0);
  2713. hash = (hash * 397) ^ (this.w || 0);
  2714. return hash;
  2715. };
  2716. // Operators
  2717. /**
  2718. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  2719. */
  2720. Vector4.prototype.asArray = function () {
  2721. var result = new Array();
  2722. this.toArray(result, 0);
  2723. return result;
  2724. };
  2725. /**
  2726. * Populates the passed array from the passed index with the Vector4 coordinates.
  2727. * Returns the Vector4.
  2728. */
  2729. Vector4.prototype.toArray = function (array, index) {
  2730. if (index === undefined) {
  2731. index = 0;
  2732. }
  2733. array[index] = this.x;
  2734. array[index + 1] = this.y;
  2735. array[index + 2] = this.z;
  2736. array[index + 3] = this.w;
  2737. return this;
  2738. };
  2739. /**
  2740. * Adds the passed vector to the current Vector4.
  2741. * Returns the updated Vector4.
  2742. */
  2743. Vector4.prototype.addInPlace = function (otherVector) {
  2744. this.x += otherVector.x;
  2745. this.y += otherVector.y;
  2746. this.z += otherVector.z;
  2747. this.w += otherVector.w;
  2748. return this;
  2749. };
  2750. /**
  2751. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  2752. */
  2753. Vector4.prototype.add = function (otherVector) {
  2754. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  2755. };
  2756. /**
  2757. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  2758. * Returns the current Vector4.
  2759. */
  2760. Vector4.prototype.addToRef = function (otherVector, result) {
  2761. result.x = this.x + otherVector.x;
  2762. result.y = this.y + otherVector.y;
  2763. result.z = this.z + otherVector.z;
  2764. result.w = this.w + otherVector.w;
  2765. return this;
  2766. };
  2767. /**
  2768. * Subtract in place the passed vector from the current Vector4.
  2769. * Returns the updated Vector4.
  2770. */
  2771. Vector4.prototype.subtractInPlace = function (otherVector) {
  2772. this.x -= otherVector.x;
  2773. this.y -= otherVector.y;
  2774. this.z -= otherVector.z;
  2775. this.w -= otherVector.w;
  2776. return this;
  2777. };
  2778. /**
  2779. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  2780. */
  2781. Vector4.prototype.subtract = function (otherVector) {
  2782. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  2783. };
  2784. /**
  2785. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  2786. * Returns the current Vector4.
  2787. */
  2788. Vector4.prototype.subtractToRef = function (otherVector, result) {
  2789. result.x = this.x - otherVector.x;
  2790. result.y = this.y - otherVector.y;
  2791. result.z = this.z - otherVector.z;
  2792. result.w = this.w - otherVector.w;
  2793. return this;
  2794. };
  2795. /**
  2796. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2797. */
  2798. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  2799. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  2800. };
  2801. /**
  2802. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  2803. * Returns the current Vector4.
  2804. */
  2805. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  2806. result.x = this.x - x;
  2807. result.y = this.y - y;
  2808. result.z = this.z - z;
  2809. result.w = this.w - w;
  2810. return this;
  2811. };
  2812. /**
  2813. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  2814. */
  2815. Vector4.prototype.negate = function () {
  2816. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  2817. };
  2818. /**
  2819. * Multiplies the current Vector4 coordinates by scale (float).
  2820. * Returns the updated Vector4.
  2821. */
  2822. Vector4.prototype.scaleInPlace = function (scale) {
  2823. this.x *= scale;
  2824. this.y *= scale;
  2825. this.z *= scale;
  2826. this.w *= scale;
  2827. return this;
  2828. };
  2829. /**
  2830. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2831. */
  2832. Vector4.prototype.scale = function (scale) {
  2833. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2834. };
  2835. /**
  2836. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2837. * Returns the current Vector4.
  2838. */
  2839. Vector4.prototype.scaleToRef = function (scale, result) {
  2840. result.x = this.x * scale;
  2841. result.y = this.y * scale;
  2842. result.z = this.z * scale;
  2843. result.w = this.w * scale;
  2844. return this;
  2845. };
  2846. /**
  2847. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2848. */
  2849. Vector4.prototype.equals = function (otherVector) {
  2850. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2851. };
  2852. /**
  2853. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2854. */
  2855. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2856. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2857. return otherVector
  2858. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2859. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2860. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2861. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2862. };
  2863. /**
  2864. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2865. */
  2866. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2867. return this.x === x && this.y === y && this.z === z && this.w === w;
  2868. };
  2869. /**
  2870. * Multiplies in place the current Vector4 by the passed one.
  2871. * Returns the updated Vector4.
  2872. */
  2873. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2874. this.x *= otherVector.x;
  2875. this.y *= otherVector.y;
  2876. this.z *= otherVector.z;
  2877. this.w *= otherVector.w;
  2878. return this;
  2879. };
  2880. /**
  2881. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2882. */
  2883. Vector4.prototype.multiply = function (otherVector) {
  2884. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2885. };
  2886. /**
  2887. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2888. * Returns the current Vector4.
  2889. */
  2890. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2891. result.x = this.x * otherVector.x;
  2892. result.y = this.y * otherVector.y;
  2893. result.z = this.z * otherVector.z;
  2894. result.w = this.w * otherVector.w;
  2895. return this;
  2896. };
  2897. /**
  2898. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2899. */
  2900. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2901. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2902. };
  2903. /**
  2904. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2905. */
  2906. Vector4.prototype.divide = function (otherVector) {
  2907. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2908. };
  2909. /**
  2910. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2911. * Returns the current Vector4.
  2912. */
  2913. Vector4.prototype.divideToRef = function (otherVector, result) {
  2914. result.x = this.x / otherVector.x;
  2915. result.y = this.y / otherVector.y;
  2916. result.z = this.z / otherVector.z;
  2917. result.w = this.w / otherVector.w;
  2918. return this;
  2919. };
  2920. /**
  2921. * Divides the current Vector3 coordinates by the passed ones.
  2922. * Returns the updated Vector3.
  2923. */
  2924. Vector4.prototype.divideInPlace = function (otherVector) {
  2925. return this.divideToRef(otherVector, this);
  2926. };
  2927. /**
  2928. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2929. */
  2930. Vector4.prototype.MinimizeInPlace = function (other) {
  2931. if (other.x < this.x)
  2932. this.x = other.x;
  2933. if (other.y < this.y)
  2934. this.y = other.y;
  2935. if (other.z < this.z)
  2936. this.z = other.z;
  2937. if (other.w < this.w)
  2938. this.w = other.w;
  2939. return this;
  2940. };
  2941. /**
  2942. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2943. */
  2944. Vector4.prototype.MaximizeInPlace = function (other) {
  2945. if (other.x > this.x)
  2946. this.x = other.x;
  2947. if (other.y > this.y)
  2948. this.y = other.y;
  2949. if (other.z > this.z)
  2950. this.z = other.z;
  2951. if (other.w > this.w)
  2952. this.w = other.w;
  2953. return this;
  2954. };
  2955. // Properties
  2956. /**
  2957. * Returns the Vector4 length (float).
  2958. */
  2959. Vector4.prototype.length = function () {
  2960. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2961. };
  2962. /**
  2963. * Returns the Vector4 squared length (float).
  2964. */
  2965. Vector4.prototype.lengthSquared = function () {
  2966. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2967. };
  2968. // Methods
  2969. /**
  2970. * Normalizes in place the Vector4.
  2971. * Returns the updated Vector4.
  2972. */
  2973. Vector4.prototype.normalize = function () {
  2974. var len = this.length();
  2975. if (len === 0)
  2976. return this;
  2977. var num = 1.0 / len;
  2978. this.x *= num;
  2979. this.y *= num;
  2980. this.z *= num;
  2981. this.w *= num;
  2982. return this;
  2983. };
  2984. /**
  2985. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2986. */
  2987. Vector4.prototype.toVector3 = function () {
  2988. return new Vector3(this.x, this.y, this.z);
  2989. };
  2990. /**
  2991. * Returns a new Vector4 copied from the current one.
  2992. */
  2993. Vector4.prototype.clone = function () {
  2994. return new Vector4(this.x, this.y, this.z, this.w);
  2995. };
  2996. /**
  2997. * Updates the current Vector4 with the passed one coordinates.
  2998. * Returns the updated Vector4.
  2999. */
  3000. Vector4.prototype.copyFrom = function (source) {
  3001. this.x = source.x;
  3002. this.y = source.y;
  3003. this.z = source.z;
  3004. this.w = source.w;
  3005. return this;
  3006. };
  3007. /**
  3008. * Updates the current Vector4 coordinates with the passed floats.
  3009. * Returns the updated Vector4.
  3010. */
  3011. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3012. this.x = x;
  3013. this.y = y;
  3014. this.z = z;
  3015. this.w = w;
  3016. return this;
  3017. };
  3018. /**
  3019. * Updates the current Vector4 coordinates with the passed floats.
  3020. * Returns the updated Vector4.
  3021. */
  3022. Vector4.prototype.set = function (x, y, z, w) {
  3023. return this.copyFromFloats(x, y, z, w);
  3024. };
  3025. // Statics
  3026. /**
  3027. * Returns a new Vector4 set from the starting index of the passed array.
  3028. */
  3029. Vector4.FromArray = function (array, offset) {
  3030. if (!offset) {
  3031. offset = 0;
  3032. }
  3033. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3034. };
  3035. /**
  3036. * Updates the passed vector "result" from the starting index of the passed array.
  3037. */
  3038. Vector4.FromArrayToRef = function (array, offset, result) {
  3039. result.x = array[offset];
  3040. result.y = array[offset + 1];
  3041. result.z = array[offset + 2];
  3042. result.w = array[offset + 3];
  3043. };
  3044. /**
  3045. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3046. */
  3047. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3048. Vector4.FromArrayToRef(array, offset, result);
  3049. };
  3050. /**
  3051. * Updates the passed vector "result" coordinates from the passed floats.
  3052. */
  3053. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3054. result.x = x;
  3055. result.y = y;
  3056. result.z = z;
  3057. result.w = w;
  3058. };
  3059. /**
  3060. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3061. */
  3062. Vector4.Zero = function () {
  3063. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3064. };
  3065. /**
  3066. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3067. */
  3068. Vector4.One = function () {
  3069. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3070. };
  3071. /**
  3072. * Returns a new normalized Vector4 from the passed one.
  3073. */
  3074. Vector4.Normalize = function (vector) {
  3075. var result = Vector4.Zero();
  3076. Vector4.NormalizeToRef(vector, result);
  3077. return result;
  3078. };
  3079. /**
  3080. * Updates the passed vector "result" from the normalization of the passed one.
  3081. */
  3082. Vector4.NormalizeToRef = function (vector, result) {
  3083. result.copyFrom(vector);
  3084. result.normalize();
  3085. };
  3086. Vector4.Minimize = function (left, right) {
  3087. var min = left.clone();
  3088. min.MinimizeInPlace(right);
  3089. return min;
  3090. };
  3091. Vector4.Maximize = function (left, right) {
  3092. var max = left.clone();
  3093. max.MaximizeInPlace(right);
  3094. return max;
  3095. };
  3096. /**
  3097. * Returns the distance (float) between the vectors "value1" and "value2".
  3098. */
  3099. Vector4.Distance = function (value1, value2) {
  3100. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3101. };
  3102. /**
  3103. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3104. */
  3105. Vector4.DistanceSquared = function (value1, value2) {
  3106. var x = value1.x - value2.x;
  3107. var y = value1.y - value2.y;
  3108. var z = value1.z - value2.z;
  3109. var w = value1.w - value2.w;
  3110. return (x * x) + (y * y) + (z * z) + (w * w);
  3111. };
  3112. /**
  3113. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3114. */
  3115. Vector4.Center = function (value1, value2) {
  3116. var center = value1.add(value2);
  3117. center.scaleInPlace(0.5);
  3118. return center;
  3119. };
  3120. /**
  3121. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3122. * This methods computes transformed normalized direction vectors only.
  3123. */
  3124. Vector4.TransformNormal = function (vector, transformation) {
  3125. var result = Vector4.Zero();
  3126. Vector4.TransformNormalToRef(vector, transformation, result);
  3127. return result;
  3128. };
  3129. /**
  3130. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3131. * This methods computes transformed normalized direction vectors only.
  3132. */
  3133. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3134. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3135. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3136. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3137. result.x = x;
  3138. result.y = y;
  3139. result.z = z;
  3140. result.w = vector.w;
  3141. };
  3142. /**
  3143. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  3144. * This methods computes transformed normalized direction vectors only.
  3145. */
  3146. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  3147. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3148. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3149. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3150. result.w = w;
  3151. };
  3152. return Vector4;
  3153. }());
  3154. BABYLON.Vector4 = Vector4;
  3155. var Size = /** @class */ (function () {
  3156. /**
  3157. * Creates a Size object from the passed width and height (floats).
  3158. */
  3159. function Size(width, height) {
  3160. this.width = width;
  3161. this.height = height;
  3162. }
  3163. // Returns a string with the Size width and height.
  3164. Size.prototype.toString = function () {
  3165. return "{W: " + this.width + ", H: " + this.height + "}";
  3166. };
  3167. /**
  3168. * Returns the string "Size"
  3169. */
  3170. Size.prototype.getClassName = function () {
  3171. return "Size";
  3172. };
  3173. /**
  3174. * Returns the Size hash code.
  3175. */
  3176. Size.prototype.getHashCode = function () {
  3177. var hash = this.width || 0;
  3178. hash = (hash * 397) ^ (this.height || 0);
  3179. return hash;
  3180. };
  3181. /**
  3182. * Updates the current size from the passed one.
  3183. * Returns the updated Size.
  3184. */
  3185. Size.prototype.copyFrom = function (src) {
  3186. this.width = src.width;
  3187. this.height = src.height;
  3188. };
  3189. /**
  3190. * Updates in place the current Size from the passed floats.
  3191. * Returns the updated Size.
  3192. */
  3193. Size.prototype.copyFromFloats = function (width, height) {
  3194. this.width = width;
  3195. this.height = height;
  3196. return this;
  3197. };
  3198. /**
  3199. * Updates in place the current Size from the passed floats.
  3200. * Returns the updated Size.
  3201. */
  3202. Size.prototype.set = function (width, height) {
  3203. return this.copyFromFloats(width, height);
  3204. };
  3205. /**
  3206. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  3207. */
  3208. Size.prototype.multiplyByFloats = function (w, h) {
  3209. return new Size(this.width * w, this.height * h);
  3210. };
  3211. /**
  3212. * Returns a new Size copied from the passed one.
  3213. */
  3214. Size.prototype.clone = function () {
  3215. return new Size(this.width, this.height);
  3216. };
  3217. /**
  3218. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  3219. */
  3220. Size.prototype.equals = function (other) {
  3221. if (!other) {
  3222. return false;
  3223. }
  3224. return (this.width === other.width) && (this.height === other.height);
  3225. };
  3226. Object.defineProperty(Size.prototype, "surface", {
  3227. /**
  3228. * Returns the surface of the Size : width * height (float).
  3229. */
  3230. get: function () {
  3231. return this.width * this.height;
  3232. },
  3233. enumerable: true,
  3234. configurable: true
  3235. });
  3236. /**
  3237. * Returns a new Size set to (0.0, 0.0)
  3238. */
  3239. Size.Zero = function () {
  3240. return new Size(0.0, 0.0);
  3241. };
  3242. /**
  3243. * Returns a new Size set as the addition result of the current Size and the passed one.
  3244. */
  3245. Size.prototype.add = function (otherSize) {
  3246. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  3247. return r;
  3248. };
  3249. /**
  3250. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  3251. */
  3252. Size.prototype.subtract = function (otherSize) {
  3253. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  3254. return r;
  3255. };
  3256. /**
  3257. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  3258. */
  3259. Size.Lerp = function (start, end, amount) {
  3260. var w = start.width + ((end.width - start.width) * amount);
  3261. var h = start.height + ((end.height - start.height) * amount);
  3262. return new Size(w, h);
  3263. };
  3264. return Size;
  3265. }());
  3266. BABYLON.Size = Size;
  3267. var Quaternion = /** @class */ (function () {
  3268. /**
  3269. * Creates a new Quaternion from the passed floats.
  3270. */
  3271. function Quaternion(x, y, z, w) {
  3272. if (x === void 0) { x = 0.0; }
  3273. if (y === void 0) { y = 0.0; }
  3274. if (z === void 0) { z = 0.0; }
  3275. if (w === void 0) { w = 1.0; }
  3276. this.x = x;
  3277. this.y = y;
  3278. this.z = z;
  3279. this.w = w;
  3280. }
  3281. /**
  3282. * Returns a string with the Quaternion coordinates.
  3283. */
  3284. Quaternion.prototype.toString = function () {
  3285. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3286. };
  3287. /**
  3288. * Returns the string "Quaternion".
  3289. */
  3290. Quaternion.prototype.getClassName = function () {
  3291. return "Quaternion";
  3292. };
  3293. /**
  3294. * Returns the Quaternion hash code.
  3295. */
  3296. Quaternion.prototype.getHashCode = function () {
  3297. var hash = this.x || 0;
  3298. hash = (hash * 397) ^ (this.y || 0);
  3299. hash = (hash * 397) ^ (this.z || 0);
  3300. hash = (hash * 397) ^ (this.w || 0);
  3301. return hash;
  3302. };
  3303. /**
  3304. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  3305. */
  3306. Quaternion.prototype.asArray = function () {
  3307. return [this.x, this.y, this.z, this.w];
  3308. };
  3309. /**
  3310. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  3311. */
  3312. Quaternion.prototype.equals = function (otherQuaternion) {
  3313. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  3314. };
  3315. /**
  3316. * Returns a new Quaternion copied from the current one.
  3317. */
  3318. Quaternion.prototype.clone = function () {
  3319. return new Quaternion(this.x, this.y, this.z, this.w);
  3320. };
  3321. /**
  3322. * Updates the current Quaternion from the passed one coordinates.
  3323. * Returns the updated Quaterion.
  3324. */
  3325. Quaternion.prototype.copyFrom = function (other) {
  3326. this.x = other.x;
  3327. this.y = other.y;
  3328. this.z = other.z;
  3329. this.w = other.w;
  3330. return this;
  3331. };
  3332. /**
  3333. * Updates the current Quaternion from the passed float coordinates.
  3334. * Returns the updated Quaterion.
  3335. */
  3336. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  3337. this.x = x;
  3338. this.y = y;
  3339. this.z = z;
  3340. this.w = w;
  3341. return this;
  3342. };
  3343. /**
  3344. * Updates the current Quaternion from the passed float coordinates.
  3345. * Returns the updated Quaterion.
  3346. */
  3347. Quaternion.prototype.set = function (x, y, z, w) {
  3348. return this.copyFromFloats(x, y, z, w);
  3349. };
  3350. /**
  3351. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  3352. */
  3353. Quaternion.prototype.add = function (other) {
  3354. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  3355. };
  3356. /**
  3357. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  3358. */
  3359. Quaternion.prototype.subtract = function (other) {
  3360. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  3361. };
  3362. /**
  3363. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  3364. */
  3365. Quaternion.prototype.scale = function (value) {
  3366. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  3367. };
  3368. /**
  3369. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  3370. */
  3371. Quaternion.prototype.multiply = function (q1) {
  3372. var result = new Quaternion(0, 0, 0, 1.0);
  3373. this.multiplyToRef(q1, result);
  3374. return result;
  3375. };
  3376. /**
  3377. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  3378. * Returns the current Quaternion.
  3379. */
  3380. Quaternion.prototype.multiplyToRef = function (q1, result) {
  3381. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  3382. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  3383. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  3384. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  3385. result.copyFromFloats(x, y, z, w);
  3386. return this;
  3387. };
  3388. /**
  3389. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  3390. * Returns the updated Quaternion.
  3391. */
  3392. Quaternion.prototype.multiplyInPlace = function (q1) {
  3393. this.multiplyToRef(q1, this);
  3394. return this;
  3395. };
  3396. /**
  3397. * Sets the passed "ref" with the conjugation of the current Quaternion.
  3398. * Returns the current Quaternion.
  3399. */
  3400. Quaternion.prototype.conjugateToRef = function (ref) {
  3401. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  3402. return this;
  3403. };
  3404. /**
  3405. * Conjugates in place the current Quaternion.
  3406. * Returns the updated Quaternion.
  3407. */
  3408. Quaternion.prototype.conjugateInPlace = function () {
  3409. this.x *= -1;
  3410. this.y *= -1;
  3411. this.z *= -1;
  3412. return this;
  3413. };
  3414. /**
  3415. * Returns a new Quaternion as the conjugate of the current Quaternion.
  3416. */
  3417. Quaternion.prototype.conjugate = function () {
  3418. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  3419. return result;
  3420. };
  3421. /**
  3422. * Returns the Quaternion length (float).
  3423. */
  3424. Quaternion.prototype.length = function () {
  3425. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  3426. };
  3427. /**
  3428. * Normalize in place the current Quaternion.
  3429. * Returns the updated Quaternion.
  3430. */
  3431. Quaternion.prototype.normalize = function () {
  3432. var length = 1.0 / this.length();
  3433. this.x *= length;
  3434. this.y *= length;
  3435. this.z *= length;
  3436. this.w *= length;
  3437. return this;
  3438. };
  3439. /**
  3440. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  3441. */
  3442. Quaternion.prototype.toEulerAngles = function (order) {
  3443. if (order === void 0) { order = "YZX"; }
  3444. var result = Vector3.Zero();
  3445. this.toEulerAnglesToRef(result, order);
  3446. return result;
  3447. };
  3448. /**
  3449. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  3450. * Returns the current Quaternion.
  3451. */
  3452. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  3453. if (order === void 0) { order = "YZX"; }
  3454. var qz = this.z;
  3455. var qx = this.x;
  3456. var qy = this.y;
  3457. var qw = this.w;
  3458. var sqw = qw * qw;
  3459. var sqz = qz * qz;
  3460. var sqx = qx * qx;
  3461. var sqy = qy * qy;
  3462. var zAxisY = qy * qz - qx * qw;
  3463. var limit = .4999999;
  3464. if (zAxisY < -limit) {
  3465. result.y = 2 * Math.atan2(qy, qw);
  3466. result.x = Math.PI / 2;
  3467. result.z = 0;
  3468. }
  3469. else if (zAxisY > limit) {
  3470. result.y = 2 * Math.atan2(qy, qw);
  3471. result.x = -Math.PI / 2;
  3472. result.z = 0;
  3473. }
  3474. else {
  3475. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  3476. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  3477. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  3478. }
  3479. return this;
  3480. };
  3481. /**
  3482. * Updates the passed rotation matrix with the current Quaternion values.
  3483. * Returns the current Quaternion.
  3484. */
  3485. Quaternion.prototype.toRotationMatrix = function (result) {
  3486. var xx = this.x * this.x;
  3487. var yy = this.y * this.y;
  3488. var zz = this.z * this.z;
  3489. var xy = this.x * this.y;
  3490. var zw = this.z * this.w;
  3491. var zx = this.z * this.x;
  3492. var yw = this.y * this.w;
  3493. var yz = this.y * this.z;
  3494. var xw = this.x * this.w;
  3495. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3496. result.m[1] = 2.0 * (xy + zw);
  3497. result.m[2] = 2.0 * (zx - yw);
  3498. result.m[3] = 0;
  3499. result.m[4] = 2.0 * (xy - zw);
  3500. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3501. result.m[6] = 2.0 * (yz + xw);
  3502. result.m[7] = 0;
  3503. result.m[8] = 2.0 * (zx + yw);
  3504. result.m[9] = 2.0 * (yz - xw);
  3505. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3506. result.m[11] = 0;
  3507. result.m[12] = 0;
  3508. result.m[13] = 0;
  3509. result.m[14] = 0;
  3510. result.m[15] = 1.0;
  3511. result._markAsUpdated();
  3512. return this;
  3513. };
  3514. /**
  3515. * Updates the current Quaternion from the passed rotation matrix values.
  3516. * Returns the updated Quaternion.
  3517. */
  3518. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  3519. Quaternion.FromRotationMatrixToRef(matrix, this);
  3520. return this;
  3521. };
  3522. // Statics
  3523. /**
  3524. * Returns a new Quaternion set from the passed rotation matrix values.
  3525. */
  3526. Quaternion.FromRotationMatrix = function (matrix) {
  3527. var result = new Quaternion();
  3528. Quaternion.FromRotationMatrixToRef(matrix, result);
  3529. return result;
  3530. };
  3531. /**
  3532. * Updates the passed quaternion "result" with the passed rotation matrix values.
  3533. */
  3534. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  3535. var data = matrix.m;
  3536. var m11 = data[0], m12 = data[4], m13 = data[8];
  3537. var m21 = data[1], m22 = data[5], m23 = data[9];
  3538. var m31 = data[2], m32 = data[6], m33 = data[10];
  3539. var trace = m11 + m22 + m33;
  3540. var s;
  3541. if (trace > 0) {
  3542. s = 0.5 / Math.sqrt(trace + 1.0);
  3543. result.w = 0.25 / s;
  3544. result.x = (m32 - m23) * s;
  3545. result.y = (m13 - m31) * s;
  3546. result.z = (m21 - m12) * s;
  3547. }
  3548. else if (m11 > m22 && m11 > m33) {
  3549. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  3550. result.w = (m32 - m23) / s;
  3551. result.x = 0.25 * s;
  3552. result.y = (m12 + m21) / s;
  3553. result.z = (m13 + m31) / s;
  3554. }
  3555. else if (m22 > m33) {
  3556. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  3557. result.w = (m13 - m31) / s;
  3558. result.x = (m12 + m21) / s;
  3559. result.y = 0.25 * s;
  3560. result.z = (m23 + m32) / s;
  3561. }
  3562. else {
  3563. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  3564. result.w = (m21 - m12) / s;
  3565. result.x = (m13 + m31) / s;
  3566. result.y = (m23 + m32) / s;
  3567. result.z = 0.25 * s;
  3568. }
  3569. };
  3570. /**
  3571. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  3572. */
  3573. Quaternion.Zero = function () {
  3574. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  3575. };
  3576. /**
  3577. * Returns a new Quaternion as the inverted current Quaternion.
  3578. */
  3579. Quaternion.Inverse = function (q) {
  3580. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  3581. };
  3582. /**
  3583. * Returns the identity Quaternion.
  3584. */
  3585. Quaternion.Identity = function () {
  3586. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  3587. };
  3588. Quaternion.IsIdentity = function (quaternion) {
  3589. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  3590. };
  3591. /**
  3592. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  3593. */
  3594. Quaternion.RotationAxis = function (axis, angle) {
  3595. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  3596. };
  3597. /**
  3598. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  3599. */
  3600. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  3601. var sin = Math.sin(angle / 2);
  3602. axis.normalize();
  3603. result.w = Math.cos(angle / 2);
  3604. result.x = axis.x * sin;
  3605. result.y = axis.y * sin;
  3606. result.z = axis.z * sin;
  3607. return result;
  3608. };
  3609. /**
  3610. * Retuns a new Quaternion set from the starting index of the passed array.
  3611. */
  3612. Quaternion.FromArray = function (array, offset) {
  3613. if (!offset) {
  3614. offset = 0;
  3615. }
  3616. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3617. };
  3618. /**
  3619. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  3620. */
  3621. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3622. var q = new Quaternion();
  3623. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  3624. return q;
  3625. };
  3626. /**
  3627. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  3628. */
  3629. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3630. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  3631. var halfRoll = roll * 0.5;
  3632. var halfPitch = pitch * 0.5;
  3633. var halfYaw = yaw * 0.5;
  3634. var sinRoll = Math.sin(halfRoll);
  3635. var cosRoll = Math.cos(halfRoll);
  3636. var sinPitch = Math.sin(halfPitch);
  3637. var cosPitch = Math.cos(halfPitch);
  3638. var sinYaw = Math.sin(halfYaw);
  3639. var cosYaw = Math.cos(halfYaw);
  3640. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  3641. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  3642. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  3643. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  3644. };
  3645. /**
  3646. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  3647. */
  3648. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  3649. var result = new Quaternion();
  3650. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  3651. return result;
  3652. };
  3653. /**
  3654. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  3655. */
  3656. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  3657. // Produces a quaternion from Euler angles in the z-x-z orientation
  3658. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  3659. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  3660. var halfBeta = beta * 0.5;
  3661. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3662. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  3663. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3664. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  3665. };
  3666. /**
  3667. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3668. * cf to Vector3.RotationFromAxis() documentation.
  3669. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3670. */
  3671. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  3672. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  3673. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3674. return quat;
  3675. };
  3676. /**
  3677. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  3678. * cf to Vector3.RotationFromAxis() documentation.
  3679. * Note : axis1, axis2 and axis3 are normalized during this operation.
  3680. */
  3681. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3682. var rotMat = MathTmp.Matrix[0];
  3683. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  3684. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  3685. };
  3686. Quaternion.Slerp = function (left, right, amount) {
  3687. var result = Quaternion.Identity();
  3688. Quaternion.SlerpToRef(left, right, amount, result);
  3689. return result;
  3690. };
  3691. Quaternion.SlerpToRef = function (left, right, amount, result) {
  3692. var num2;
  3693. var num3;
  3694. var num = amount;
  3695. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  3696. var flag = false;
  3697. if (num4 < 0) {
  3698. flag = true;
  3699. num4 = -num4;
  3700. }
  3701. if (num4 > 0.999999) {
  3702. num3 = 1 - num;
  3703. num2 = flag ? -num : num;
  3704. }
  3705. else {
  3706. var num5 = Math.acos(num4);
  3707. var num6 = (1.0 / Math.sin(num5));
  3708. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  3709. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  3710. }
  3711. result.x = (num3 * left.x) + (num2 * right.x);
  3712. result.y = (num3 * left.y) + (num2 * right.y);
  3713. result.z = (num3 * left.z) + (num2 * right.z);
  3714. result.w = (num3 * left.w) + (num2 * right.w);
  3715. };
  3716. /**
  3717. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  3718. */
  3719. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3720. var squared = amount * amount;
  3721. var cubed = amount * squared;
  3722. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3723. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3724. var part3 = (cubed - (2.0 * squared)) + amount;
  3725. var part4 = cubed - squared;
  3726. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3727. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3728. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3729. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  3730. return new Quaternion(x, y, z, w);
  3731. };
  3732. return Quaternion;
  3733. }());
  3734. BABYLON.Quaternion = Quaternion;
  3735. var Matrix = /** @class */ (function () {
  3736. function Matrix() {
  3737. this._isIdentity = false;
  3738. this._isIdentityDirty = true;
  3739. this.m = new Float32Array(16);
  3740. this._markAsUpdated();
  3741. }
  3742. Matrix.prototype._markAsUpdated = function () {
  3743. this.updateFlag = Matrix._updateFlagSeed++;
  3744. this._isIdentityDirty = true;
  3745. };
  3746. // Properties
  3747. /**
  3748. * Boolean : True is the matrix is the identity matrix
  3749. */
  3750. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  3751. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  3752. if (this._isIdentityDirty) {
  3753. this._isIdentityDirty = false;
  3754. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  3755. this._isIdentity = false;
  3756. }
  3757. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  3758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  3759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  3760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  3761. this._isIdentity = false;
  3762. }
  3763. else {
  3764. this._isIdentity = true;
  3765. }
  3766. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  3767. this._isIdentity = false;
  3768. }
  3769. }
  3770. return this._isIdentity;
  3771. };
  3772. /**
  3773. * Returns the matrix determinant (float).
  3774. */
  3775. Matrix.prototype.determinant = function () {
  3776. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  3777. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  3778. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  3779. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  3780. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  3781. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  3782. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  3783. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  3784. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  3785. };
  3786. // Methods
  3787. /**
  3788. * Returns the matrix underlying array.
  3789. */
  3790. Matrix.prototype.toArray = function () {
  3791. return this.m;
  3792. };
  3793. /**
  3794. * Returns the matrix underlying array.
  3795. */
  3796. Matrix.prototype.asArray = function () {
  3797. return this.toArray();
  3798. };
  3799. /**
  3800. * Inverts in place the Matrix.
  3801. * Returns the Matrix inverted.
  3802. */
  3803. Matrix.prototype.invert = function () {
  3804. this.invertToRef(this);
  3805. return this;
  3806. };
  3807. /**
  3808. * Sets all the matrix elements to zero.
  3809. * Returns the Matrix.
  3810. */
  3811. Matrix.prototype.reset = function () {
  3812. for (var index = 0; index < 16; index++) {
  3813. this.m[index] = 0.0;
  3814. }
  3815. this._markAsUpdated();
  3816. return this;
  3817. };
  3818. /**
  3819. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  3820. */
  3821. Matrix.prototype.add = function (other) {
  3822. var result = new Matrix();
  3823. this.addToRef(other, result);
  3824. return result;
  3825. };
  3826. /**
  3827. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3828. * Returns the Matrix.
  3829. */
  3830. Matrix.prototype.addToRef = function (other, result) {
  3831. for (var index = 0; index < 16; index++) {
  3832. result.m[index] = this.m[index] + other.m[index];
  3833. }
  3834. result._markAsUpdated();
  3835. return this;
  3836. };
  3837. /**
  3838. * Adds in place the passed matrix to the current Matrix.
  3839. * Returns the updated Matrix.
  3840. */
  3841. Matrix.prototype.addToSelf = function (other) {
  3842. for (var index = 0; index < 16; index++) {
  3843. this.m[index] += other.m[index];
  3844. }
  3845. this._markAsUpdated();
  3846. return this;
  3847. };
  3848. /**
  3849. * Sets the passed matrix with the current inverted Matrix.
  3850. * Returns the unmodified current Matrix.
  3851. */
  3852. Matrix.prototype.invertToRef = function (other) {
  3853. var l1 = this.m[0];
  3854. var l2 = this.m[1];
  3855. var l3 = this.m[2];
  3856. var l4 = this.m[3];
  3857. var l5 = this.m[4];
  3858. var l6 = this.m[5];
  3859. var l7 = this.m[6];
  3860. var l8 = this.m[7];
  3861. var l9 = this.m[8];
  3862. var l10 = this.m[9];
  3863. var l11 = this.m[10];
  3864. var l12 = this.m[11];
  3865. var l13 = this.m[12];
  3866. var l14 = this.m[13];
  3867. var l15 = this.m[14];
  3868. var l16 = this.m[15];
  3869. var l17 = (l11 * l16) - (l12 * l15);
  3870. var l18 = (l10 * l16) - (l12 * l14);
  3871. var l19 = (l10 * l15) - (l11 * l14);
  3872. var l20 = (l9 * l16) - (l12 * l13);
  3873. var l21 = (l9 * l15) - (l11 * l13);
  3874. var l22 = (l9 * l14) - (l10 * l13);
  3875. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3876. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3877. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3878. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3879. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3880. var l28 = (l7 * l16) - (l8 * l15);
  3881. var l29 = (l6 * l16) - (l8 * l14);
  3882. var l30 = (l6 * l15) - (l7 * l14);
  3883. var l31 = (l5 * l16) - (l8 * l13);
  3884. var l32 = (l5 * l15) - (l7 * l13);
  3885. var l33 = (l5 * l14) - (l6 * l13);
  3886. var l34 = (l7 * l12) - (l8 * l11);
  3887. var l35 = (l6 * l12) - (l8 * l10);
  3888. var l36 = (l6 * l11) - (l7 * l10);
  3889. var l37 = (l5 * l12) - (l8 * l9);
  3890. var l38 = (l5 * l11) - (l7 * l9);
  3891. var l39 = (l5 * l10) - (l6 * l9);
  3892. other.m[0] = l23 * l27;
  3893. other.m[4] = l24 * l27;
  3894. other.m[8] = l25 * l27;
  3895. other.m[12] = l26 * l27;
  3896. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3897. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3898. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3899. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3900. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3901. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3902. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3903. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3904. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3905. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3906. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3907. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3908. other._markAsUpdated();
  3909. return this;
  3910. };
  3911. /**
  3912. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3913. * Returns the updated Matrix.
  3914. */
  3915. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3916. this.m[12] = x;
  3917. this.m[13] = y;
  3918. this.m[14] = z;
  3919. this._markAsUpdated();
  3920. return this;
  3921. };
  3922. /**
  3923. * Inserts the translation vector in the current Matrix.
  3924. * Returns the updated Matrix.
  3925. */
  3926. Matrix.prototype.setTranslation = function (vector3) {
  3927. this.m[12] = vector3.x;
  3928. this.m[13] = vector3.y;
  3929. this.m[14] = vector3.z;
  3930. this._markAsUpdated();
  3931. return this;
  3932. };
  3933. /**
  3934. * Returns a new Vector3 as the extracted translation from the Matrix.
  3935. */
  3936. Matrix.prototype.getTranslation = function () {
  3937. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3938. };
  3939. /**
  3940. * Fill a Vector3 with the extracted translation from the Matrix.
  3941. */
  3942. Matrix.prototype.getTranslationToRef = function (result) {
  3943. result.x = this.m[12];
  3944. result.y = this.m[13];
  3945. result.z = this.m[14];
  3946. return this;
  3947. };
  3948. /**
  3949. * Remove rotation and scaling part from the Matrix.
  3950. * Returns the updated Matrix.
  3951. */
  3952. Matrix.prototype.removeRotationAndScaling = function () {
  3953. this.setRowFromFloats(0, 1, 0, 0, 0);
  3954. this.setRowFromFloats(1, 0, 1, 0, 0);
  3955. this.setRowFromFloats(2, 0, 0, 1, 0);
  3956. return this;
  3957. };
  3958. /**
  3959. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3960. */
  3961. Matrix.prototype.multiply = function (other) {
  3962. var result = new Matrix();
  3963. this.multiplyToRef(other, result);
  3964. return result;
  3965. };
  3966. /**
  3967. * Updates the current Matrix from the passed one values.
  3968. * Returns the updated Matrix.
  3969. */
  3970. Matrix.prototype.copyFrom = function (other) {
  3971. for (var index = 0; index < 16; index++) {
  3972. this.m[index] = other.m[index];
  3973. }
  3974. this._markAsUpdated();
  3975. return this;
  3976. };
  3977. /**
  3978. * Populates the passed array from the starting index with the Matrix values.
  3979. * Returns the Matrix.
  3980. */
  3981. Matrix.prototype.copyToArray = function (array, offset) {
  3982. if (offset === void 0) { offset = 0; }
  3983. for (var index = 0; index < 16; index++) {
  3984. array[offset + index] = this.m[index];
  3985. }
  3986. return this;
  3987. };
  3988. /**
  3989. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3990. */
  3991. Matrix.prototype.multiplyToRef = function (other, result) {
  3992. this.multiplyToArray(other, result.m, 0);
  3993. result._markAsUpdated();
  3994. return this;
  3995. };
  3996. /**
  3997. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3998. */
  3999. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4000. var tm0 = this.m[0];
  4001. var tm1 = this.m[1];
  4002. var tm2 = this.m[2];
  4003. var tm3 = this.m[3];
  4004. var tm4 = this.m[4];
  4005. var tm5 = this.m[5];
  4006. var tm6 = this.m[6];
  4007. var tm7 = this.m[7];
  4008. var tm8 = this.m[8];
  4009. var tm9 = this.m[9];
  4010. var tm10 = this.m[10];
  4011. var tm11 = this.m[11];
  4012. var tm12 = this.m[12];
  4013. var tm13 = this.m[13];
  4014. var tm14 = this.m[14];
  4015. var tm15 = this.m[15];
  4016. var om0 = other.m[0];
  4017. var om1 = other.m[1];
  4018. var om2 = other.m[2];
  4019. var om3 = other.m[3];
  4020. var om4 = other.m[4];
  4021. var om5 = other.m[5];
  4022. var om6 = other.m[6];
  4023. var om7 = other.m[7];
  4024. var om8 = other.m[8];
  4025. var om9 = other.m[9];
  4026. var om10 = other.m[10];
  4027. var om11 = other.m[11];
  4028. var om12 = other.m[12];
  4029. var om13 = other.m[13];
  4030. var om14 = other.m[14];
  4031. var om15 = other.m[15];
  4032. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4033. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4034. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4035. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4036. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4037. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4038. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4039. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4040. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4041. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4042. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4043. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4044. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4045. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4046. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4047. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4048. return this;
  4049. };
  4050. /**
  4051. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4052. */
  4053. Matrix.prototype.equals = function (value) {
  4054. return value &&
  4055. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4056. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4057. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4058. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4059. };
  4060. /**
  4061. * Returns a new Matrix from the current Matrix.
  4062. */
  4063. Matrix.prototype.clone = function () {
  4064. 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]);
  4065. };
  4066. /**
  4067. * Returns the string "Matrix"
  4068. */
  4069. Matrix.prototype.getClassName = function () {
  4070. return "Matrix";
  4071. };
  4072. /**
  4073. * Returns the Matrix hash code.
  4074. */
  4075. Matrix.prototype.getHashCode = function () {
  4076. var hash = this.m[0] || 0;
  4077. for (var i = 1; i < 16; i++) {
  4078. hash = (hash * 397) ^ (this.m[i] || 0);
  4079. }
  4080. return hash;
  4081. };
  4082. /**
  4083. * Decomposes the current Matrix into :
  4084. * - a scale vector3 passed as a reference to update,
  4085. * - a rotation quaternion passed as a reference to update,
  4086. * - a translation vector3 passed as a reference to update.
  4087. * Returns the boolean `true`.
  4088. */
  4089. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4090. translation.x = this.m[12];
  4091. translation.y = this.m[13];
  4092. translation.z = this.m[14];
  4093. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4094. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4095. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4096. if (this.determinant() <= 0) {
  4097. scale.y *= -1;
  4098. }
  4099. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4100. rotation.x = 0;
  4101. rotation.y = 0;
  4102. rotation.z = 0;
  4103. rotation.w = 1;
  4104. return false;
  4105. }
  4106. 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]);
  4107. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4108. return true;
  4109. };
  4110. /**
  4111. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4112. */
  4113. Matrix.prototype.getRotationMatrix = function () {
  4114. var result = Matrix.Identity();
  4115. this.getRotationMatrixToRef(result);
  4116. return result;
  4117. };
  4118. /**
  4119. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4120. * Returns the current Matrix.
  4121. */
  4122. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4123. var m = this.m;
  4124. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  4125. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  4126. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  4127. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  4128. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  4129. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  4130. 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);
  4131. return this;
  4132. };
  4133. // Statics
  4134. /**
  4135. * Returns a new Matrix set from the starting index of the passed array.
  4136. */
  4137. Matrix.FromArray = function (array, offset) {
  4138. var result = new Matrix();
  4139. if (!offset) {
  4140. offset = 0;
  4141. }
  4142. Matrix.FromArrayToRef(array, offset, result);
  4143. return result;
  4144. };
  4145. /**
  4146. * Sets the passed "result" matrix from the starting index of the passed array.
  4147. */
  4148. Matrix.FromArrayToRef = function (array, offset, result) {
  4149. for (var index = 0; index < 16; index++) {
  4150. result.m[index] = array[index + offset];
  4151. }
  4152. result._markAsUpdated();
  4153. };
  4154. /**
  4155. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  4156. */
  4157. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  4158. for (var index = 0; index < 16; index++) {
  4159. result.m[index] = array[index + offset] * scale;
  4160. }
  4161. result._markAsUpdated();
  4162. };
  4163. /**
  4164. * Sets the passed matrix "result" with the 16 passed floats.
  4165. */
  4166. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  4167. result.m[0] = initialM11;
  4168. result.m[1] = initialM12;
  4169. result.m[2] = initialM13;
  4170. result.m[3] = initialM14;
  4171. result.m[4] = initialM21;
  4172. result.m[5] = initialM22;
  4173. result.m[6] = initialM23;
  4174. result.m[7] = initialM24;
  4175. result.m[8] = initialM31;
  4176. result.m[9] = initialM32;
  4177. result.m[10] = initialM33;
  4178. result.m[11] = initialM34;
  4179. result.m[12] = initialM41;
  4180. result.m[13] = initialM42;
  4181. result.m[14] = initialM43;
  4182. result.m[15] = initialM44;
  4183. result._markAsUpdated();
  4184. };
  4185. /**
  4186. * Returns the index-th row of the current matrix as a new Vector4.
  4187. */
  4188. Matrix.prototype.getRow = function (index) {
  4189. if (index < 0 || index > 3) {
  4190. return null;
  4191. }
  4192. var i = index * 4;
  4193. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  4194. };
  4195. /**
  4196. * Sets the index-th row of the current matrix with the passed Vector4 values.
  4197. * Returns the updated Matrix.
  4198. */
  4199. Matrix.prototype.setRow = function (index, row) {
  4200. if (index < 0 || index > 3) {
  4201. return this;
  4202. }
  4203. var i = index * 4;
  4204. this.m[i + 0] = row.x;
  4205. this.m[i + 1] = row.y;
  4206. this.m[i + 2] = row.z;
  4207. this.m[i + 3] = row.w;
  4208. this._markAsUpdated();
  4209. return this;
  4210. };
  4211. /**
  4212. * Compute the transpose of the matrix.
  4213. * Returns a new Matrix.
  4214. */
  4215. Matrix.prototype.transpose = function () {
  4216. return Matrix.Transpose(this);
  4217. };
  4218. /**
  4219. * Compute the transpose of the matrix.
  4220. * Returns the current matrix.
  4221. */
  4222. Matrix.prototype.transposeToRef = function (result) {
  4223. Matrix.TransposeToRef(this, result);
  4224. return this;
  4225. };
  4226. /**
  4227. * Sets the index-th row of the current matrix with the passed 4 x float values.
  4228. * Returns the updated Matrix.
  4229. */
  4230. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  4231. if (index < 0 || index > 3) {
  4232. return this;
  4233. }
  4234. var i = index * 4;
  4235. this.m[i + 0] = x;
  4236. this.m[i + 1] = y;
  4237. this.m[i + 2] = z;
  4238. this.m[i + 3] = w;
  4239. this._markAsUpdated();
  4240. return this;
  4241. };
  4242. Object.defineProperty(Matrix, "IdentityReadOnly", {
  4243. /**
  4244. * Static identity matrix to be used as readonly matrix
  4245. * Must not be updated.
  4246. */
  4247. get: function () {
  4248. return Matrix._identityReadOnly;
  4249. },
  4250. enumerable: true,
  4251. configurable: true
  4252. });
  4253. /**
  4254. * Returns a new Matrix set from the 16 passed floats.
  4255. */
  4256. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  4257. var result = new Matrix();
  4258. result.m[0] = initialM11;
  4259. result.m[1] = initialM12;
  4260. result.m[2] = initialM13;
  4261. result.m[3] = initialM14;
  4262. result.m[4] = initialM21;
  4263. result.m[5] = initialM22;
  4264. result.m[6] = initialM23;
  4265. result.m[7] = initialM24;
  4266. result.m[8] = initialM31;
  4267. result.m[9] = initialM32;
  4268. result.m[10] = initialM33;
  4269. result.m[11] = initialM34;
  4270. result.m[12] = initialM41;
  4271. result.m[13] = initialM42;
  4272. result.m[14] = initialM43;
  4273. result.m[15] = initialM44;
  4274. return result;
  4275. };
  4276. /**
  4277. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4278. */
  4279. Matrix.Compose = function (scale, rotation, translation) {
  4280. var result = Matrix.Identity();
  4281. Matrix.ComposeToRef(scale, rotation, translation, result);
  4282. return result;
  4283. };
  4284. /**
  4285. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  4286. */
  4287. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  4288. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  4289. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  4290. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  4291. result.setTranslation(translation);
  4292. };
  4293. /**
  4294. * Returns a new indentity Matrix.
  4295. */
  4296. Matrix.Identity = function () {
  4297. 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);
  4298. };
  4299. /**
  4300. * Sets the passed "result" as an identity matrix.
  4301. */
  4302. Matrix.IdentityToRef = function (result) {
  4303. 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);
  4304. };
  4305. /**
  4306. * Returns a new zero Matrix.
  4307. */
  4308. Matrix.Zero = function () {
  4309. 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);
  4310. };
  4311. /**
  4312. * Returns a new rotation matrix for "angle" radians around the X axis.
  4313. */
  4314. Matrix.RotationX = function (angle) {
  4315. var result = new Matrix();
  4316. Matrix.RotationXToRef(angle, result);
  4317. return result;
  4318. };
  4319. /**
  4320. * Returns a new Matrix as the passed inverted one.
  4321. */
  4322. Matrix.Invert = function (source) {
  4323. var result = new Matrix();
  4324. source.invertToRef(result);
  4325. return result;
  4326. };
  4327. /**
  4328. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  4329. */
  4330. Matrix.RotationXToRef = function (angle, result) {
  4331. var s = Math.sin(angle);
  4332. var c = Math.cos(angle);
  4333. result.m[0] = 1.0;
  4334. result.m[15] = 1.0;
  4335. result.m[5] = c;
  4336. result.m[10] = c;
  4337. result.m[9] = -s;
  4338. result.m[6] = s;
  4339. result.m[1] = 0.0;
  4340. result.m[2] = 0.0;
  4341. result.m[3] = 0.0;
  4342. result.m[4] = 0.0;
  4343. result.m[7] = 0.0;
  4344. result.m[8] = 0.0;
  4345. result.m[11] = 0.0;
  4346. result.m[12] = 0.0;
  4347. result.m[13] = 0.0;
  4348. result.m[14] = 0.0;
  4349. result._markAsUpdated();
  4350. };
  4351. /**
  4352. * Returns a new rotation matrix for "angle" radians around the Y axis.
  4353. */
  4354. Matrix.RotationY = function (angle) {
  4355. var result = new Matrix();
  4356. Matrix.RotationYToRef(angle, result);
  4357. return result;
  4358. };
  4359. /**
  4360. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  4361. */
  4362. Matrix.RotationYToRef = function (angle, result) {
  4363. var s = Math.sin(angle);
  4364. var c = Math.cos(angle);
  4365. result.m[5] = 1.0;
  4366. result.m[15] = 1.0;
  4367. result.m[0] = c;
  4368. result.m[2] = -s;
  4369. result.m[8] = s;
  4370. result.m[10] = c;
  4371. result.m[1] = 0.0;
  4372. result.m[3] = 0.0;
  4373. result.m[4] = 0.0;
  4374. result.m[6] = 0.0;
  4375. result.m[7] = 0.0;
  4376. result.m[9] = 0.0;
  4377. result.m[11] = 0.0;
  4378. result.m[12] = 0.0;
  4379. result.m[13] = 0.0;
  4380. result.m[14] = 0.0;
  4381. result._markAsUpdated();
  4382. };
  4383. /**
  4384. * Returns a new rotation matrix for "angle" radians around the Z axis.
  4385. */
  4386. Matrix.RotationZ = function (angle) {
  4387. var result = new Matrix();
  4388. Matrix.RotationZToRef(angle, result);
  4389. return result;
  4390. };
  4391. /**
  4392. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  4393. */
  4394. Matrix.RotationZToRef = function (angle, result) {
  4395. var s = Math.sin(angle);
  4396. var c = Math.cos(angle);
  4397. result.m[10] = 1.0;
  4398. result.m[15] = 1.0;
  4399. result.m[0] = c;
  4400. result.m[1] = s;
  4401. result.m[4] = -s;
  4402. result.m[5] = c;
  4403. result.m[2] = 0.0;
  4404. result.m[3] = 0.0;
  4405. result.m[6] = 0.0;
  4406. result.m[7] = 0.0;
  4407. result.m[8] = 0.0;
  4408. result.m[9] = 0.0;
  4409. result.m[11] = 0.0;
  4410. result.m[12] = 0.0;
  4411. result.m[13] = 0.0;
  4412. result.m[14] = 0.0;
  4413. result._markAsUpdated();
  4414. };
  4415. /**
  4416. * Returns a new rotation matrix for "angle" radians around the passed axis.
  4417. */
  4418. Matrix.RotationAxis = function (axis, angle) {
  4419. var result = Matrix.Zero();
  4420. Matrix.RotationAxisToRef(axis, angle, result);
  4421. return result;
  4422. };
  4423. /**
  4424. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  4425. */
  4426. Matrix.RotationAxisToRef = function (axis, angle, result) {
  4427. var s = Math.sin(-angle);
  4428. var c = Math.cos(-angle);
  4429. var c1 = 1 - c;
  4430. axis.normalize();
  4431. result.m[0] = (axis.x * axis.x) * c1 + c;
  4432. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  4433. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  4434. result.m[3] = 0.0;
  4435. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  4436. result.m[5] = (axis.y * axis.y) * c1 + c;
  4437. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  4438. result.m[7] = 0.0;
  4439. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  4440. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  4441. result.m[10] = (axis.z * axis.z) * c1 + c;
  4442. result.m[11] = 0.0;
  4443. result.m[15] = 1.0;
  4444. result._markAsUpdated();
  4445. };
  4446. /**
  4447. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  4448. */
  4449. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4450. var result = new Matrix();
  4451. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  4452. return result;
  4453. };
  4454. /**
  4455. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  4456. */
  4457. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4458. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  4459. this._tempQuaternion.toRotationMatrix(result);
  4460. };
  4461. /**
  4462. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  4463. */
  4464. Matrix.Scaling = function (x, y, z) {
  4465. var result = Matrix.Zero();
  4466. Matrix.ScalingToRef(x, y, z, result);
  4467. return result;
  4468. };
  4469. /**
  4470. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  4471. */
  4472. Matrix.ScalingToRef = function (x, y, z, result) {
  4473. result.m[0] = x;
  4474. result.m[1] = 0.0;
  4475. result.m[2] = 0.0;
  4476. result.m[3] = 0.0;
  4477. result.m[4] = 0.0;
  4478. result.m[5] = y;
  4479. result.m[6] = 0.0;
  4480. result.m[7] = 0.0;
  4481. result.m[8] = 0.0;
  4482. result.m[9] = 0.0;
  4483. result.m[10] = z;
  4484. result.m[11] = 0.0;
  4485. result.m[12] = 0.0;
  4486. result.m[13] = 0.0;
  4487. result.m[14] = 0.0;
  4488. result.m[15] = 1.0;
  4489. result._markAsUpdated();
  4490. };
  4491. /**
  4492. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  4493. */
  4494. Matrix.Translation = function (x, y, z) {
  4495. var result = Matrix.Identity();
  4496. Matrix.TranslationToRef(x, y, z, result);
  4497. return result;
  4498. };
  4499. /**
  4500. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  4501. */
  4502. Matrix.TranslationToRef = function (x, y, z, result) {
  4503. 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);
  4504. };
  4505. /**
  4506. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  4507. */
  4508. Matrix.Lerp = function (startValue, endValue, gradient) {
  4509. var result = Matrix.Zero();
  4510. for (var index = 0; index < 16; index++) {
  4511. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  4512. }
  4513. result._markAsUpdated();
  4514. return result;
  4515. };
  4516. /**
  4517. * Returns a new Matrix whose values are computed by :
  4518. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  4519. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  4520. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  4521. */
  4522. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  4523. var startScale = new Vector3(0, 0, 0);
  4524. var startRotation = new Quaternion();
  4525. var startTranslation = new Vector3(0, 0, 0);
  4526. startValue.decompose(startScale, startRotation, startTranslation);
  4527. var endScale = new Vector3(0, 0, 0);
  4528. var endRotation = new Quaternion();
  4529. var endTranslation = new Vector3(0, 0, 0);
  4530. endValue.decompose(endScale, endRotation, endTranslation);
  4531. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  4532. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  4533. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  4534. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  4535. };
  4536. /**
  4537. * 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".
  4538. * This methods works for a Left-Handed system.
  4539. */
  4540. Matrix.LookAtLH = function (eye, target, up) {
  4541. var result = Matrix.Zero();
  4542. Matrix.LookAtLHToRef(eye, target, up, result);
  4543. return result;
  4544. };
  4545. /**
  4546. * 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".
  4547. * This methods works for a Left-Handed system.
  4548. */
  4549. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  4550. // Z axis
  4551. target.subtractToRef(eye, this._zAxis);
  4552. this._zAxis.normalize();
  4553. // X axis
  4554. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4555. if (this._xAxis.lengthSquared() === 0) {
  4556. this._xAxis.x = 1.0;
  4557. }
  4558. else {
  4559. this._xAxis.normalize();
  4560. }
  4561. // Y axis
  4562. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4563. this._yAxis.normalize();
  4564. // Eye angles
  4565. var ex = -Vector3.Dot(this._xAxis, eye);
  4566. var ey = -Vector3.Dot(this._yAxis, eye);
  4567. var ez = -Vector3.Dot(this._zAxis, eye);
  4568. 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);
  4569. };
  4570. /**
  4571. * 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".
  4572. * This methods works for a Right-Handed system.
  4573. */
  4574. Matrix.LookAtRH = function (eye, target, up) {
  4575. var result = Matrix.Zero();
  4576. Matrix.LookAtRHToRef(eye, target, up, result);
  4577. return result;
  4578. };
  4579. /**
  4580. * 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".
  4581. * This methods works for a Left-Handed system.
  4582. */
  4583. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  4584. // Z axis
  4585. eye.subtractToRef(target, this._zAxis);
  4586. this._zAxis.normalize();
  4587. // X axis
  4588. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  4589. if (this._xAxis.lengthSquared() === 0) {
  4590. this._xAxis.x = 1.0;
  4591. }
  4592. else {
  4593. this._xAxis.normalize();
  4594. }
  4595. // Y axis
  4596. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  4597. this._yAxis.normalize();
  4598. // Eye angles
  4599. var ex = -Vector3.Dot(this._xAxis, eye);
  4600. var ey = -Vector3.Dot(this._yAxis, eye);
  4601. var ez = -Vector3.Dot(this._zAxis, eye);
  4602. 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);
  4603. };
  4604. /**
  4605. * 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.
  4606. */
  4607. Matrix.OrthoLH = function (width, height, znear, zfar) {
  4608. var matrix = Matrix.Zero();
  4609. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  4610. return matrix;
  4611. };
  4612. /**
  4613. * 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.
  4614. */
  4615. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  4616. var n = znear;
  4617. var f = zfar;
  4618. var a = 2.0 / width;
  4619. var b = 2.0 / height;
  4620. var c = 2.0 / (f - n);
  4621. var d = -(f + n) / (f - n);
  4622. 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);
  4623. };
  4624. /**
  4625. * 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.
  4626. */
  4627. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  4628. var matrix = Matrix.Zero();
  4629. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  4630. return matrix;
  4631. };
  4632. /**
  4633. * 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.
  4634. */
  4635. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4636. var n = znear;
  4637. var f = zfar;
  4638. var a = 2.0 / (right - left);
  4639. var b = 2.0 / (top - bottom);
  4640. var c = 2.0 / (f - n);
  4641. var d = -(f + n) / (f - n);
  4642. var i0 = (left + right) / (left - right);
  4643. var i1 = (top + bottom) / (bottom - top);
  4644. 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);
  4645. };
  4646. /**
  4647. * 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.
  4648. */
  4649. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  4650. var matrix = Matrix.Zero();
  4651. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  4652. return matrix;
  4653. };
  4654. /**
  4655. * 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.
  4656. */
  4657. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  4658. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  4659. result.m[10] *= -1.0;
  4660. };
  4661. /**
  4662. * 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.
  4663. */
  4664. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  4665. var matrix = Matrix.Zero();
  4666. var n = znear;
  4667. var f = zfar;
  4668. var a = 2.0 * n / width;
  4669. var b = 2.0 * n / height;
  4670. var c = (f + n) / (f - n);
  4671. var d = -2.0 * f * n / (f - n);
  4672. 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);
  4673. return matrix;
  4674. };
  4675. /**
  4676. * 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.
  4677. */
  4678. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  4679. var matrix = Matrix.Zero();
  4680. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  4681. return matrix;
  4682. };
  4683. /**
  4684. * 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.
  4685. */
  4686. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4687. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4688. var n = znear;
  4689. var f = zfar;
  4690. var t = 1.0 / (Math.tan(fov * 0.5));
  4691. var a = isVerticalFovFixed ? (t / aspect) : t;
  4692. var b = isVerticalFovFixed ? t : (t * aspect);
  4693. var c = (f + n) / (f - n);
  4694. var d = -2.0 * f * n / (f - n);
  4695. 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);
  4696. };
  4697. /**
  4698. * 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.
  4699. */
  4700. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  4701. var matrix = Matrix.Zero();
  4702. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  4703. return matrix;
  4704. };
  4705. /**
  4706. * 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.
  4707. */
  4708. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  4709. //alternatively this could be expressed as:
  4710. // m = PerspectiveFovLHToRef
  4711. // m[10] *= -1.0;
  4712. // m[11] *= -1.0;
  4713. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  4714. var n = znear;
  4715. var f = zfar;
  4716. var t = 1.0 / (Math.tan(fov * 0.5));
  4717. var a = isVerticalFovFixed ? (t / aspect) : t;
  4718. var b = isVerticalFovFixed ? t : (t * aspect);
  4719. var c = -(f + n) / (f - n);
  4720. var d = -2 * f * n / (f - n);
  4721. 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);
  4722. };
  4723. /**
  4724. * 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.
  4725. */
  4726. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  4727. if (rightHanded === void 0) { rightHanded = false; }
  4728. var rightHandedFactor = rightHanded ? -1 : 1;
  4729. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  4730. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  4731. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  4732. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  4733. var xScale = 2.0 / (leftTan + rightTan);
  4734. var yScale = 2.0 / (upTan + downTan);
  4735. result.m[0] = xScale;
  4736. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  4737. result.m[5] = yScale;
  4738. result.m[6] = result.m[7] = 0.0;
  4739. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  4740. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  4741. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  4742. result.m[10] = -zfar / (znear - zfar);
  4743. result.m[11] = 1.0 * rightHandedFactor;
  4744. result.m[12] = result.m[13] = result.m[15] = 0.0;
  4745. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  4746. // result.m[14] = (znear * zfar) / (znear - zfar);
  4747. result._markAsUpdated();
  4748. };
  4749. /**
  4750. * Returns the final transformation matrix : world * view * projection * viewport
  4751. */
  4752. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  4753. var cw = viewport.width;
  4754. var ch = viewport.height;
  4755. var cx = viewport.x;
  4756. var cy = viewport.y;
  4757. 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);
  4758. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  4759. };
  4760. /**
  4761. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  4762. */
  4763. Matrix.GetAsMatrix2x2 = function (matrix) {
  4764. return new Float32Array([
  4765. matrix.m[0], matrix.m[1],
  4766. matrix.m[4], matrix.m[5]
  4767. ]);
  4768. };
  4769. /**
  4770. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  4771. */
  4772. Matrix.GetAsMatrix3x3 = function (matrix) {
  4773. return new Float32Array([
  4774. matrix.m[0], matrix.m[1], matrix.m[2],
  4775. matrix.m[4], matrix.m[5], matrix.m[6],
  4776. matrix.m[8], matrix.m[9], matrix.m[10]
  4777. ]);
  4778. };
  4779. /**
  4780. * Compute the transpose of the passed Matrix.
  4781. * Returns a new Matrix.
  4782. */
  4783. Matrix.Transpose = function (matrix) {
  4784. var result = new Matrix();
  4785. Matrix.TransposeToRef(matrix, result);
  4786. return result;
  4787. };
  4788. /**
  4789. * Compute the transpose of the passed Matrix and store it in the result matrix.
  4790. */
  4791. Matrix.TransposeToRef = function (matrix, result) {
  4792. result.m[0] = matrix.m[0];
  4793. result.m[1] = matrix.m[4];
  4794. result.m[2] = matrix.m[8];
  4795. result.m[3] = matrix.m[12];
  4796. result.m[4] = matrix.m[1];
  4797. result.m[5] = matrix.m[5];
  4798. result.m[6] = matrix.m[9];
  4799. result.m[7] = matrix.m[13];
  4800. result.m[8] = matrix.m[2];
  4801. result.m[9] = matrix.m[6];
  4802. result.m[10] = matrix.m[10];
  4803. result.m[11] = matrix.m[14];
  4804. result.m[12] = matrix.m[3];
  4805. result.m[13] = matrix.m[7];
  4806. result.m[14] = matrix.m[11];
  4807. result.m[15] = matrix.m[15];
  4808. };
  4809. /**
  4810. * Returns a new Matrix as the reflection matrix across the passed plane.
  4811. */
  4812. Matrix.Reflection = function (plane) {
  4813. var matrix = new Matrix();
  4814. Matrix.ReflectionToRef(plane, matrix);
  4815. return matrix;
  4816. };
  4817. /**
  4818. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  4819. */
  4820. Matrix.ReflectionToRef = function (plane, result) {
  4821. plane.normalize();
  4822. var x = plane.normal.x;
  4823. var y = plane.normal.y;
  4824. var z = plane.normal.z;
  4825. var temp = -2 * x;
  4826. var temp2 = -2 * y;
  4827. var temp3 = -2 * z;
  4828. result.m[0] = (temp * x) + 1;
  4829. result.m[1] = temp2 * x;
  4830. result.m[2] = temp3 * x;
  4831. result.m[3] = 0.0;
  4832. result.m[4] = temp * y;
  4833. result.m[5] = (temp2 * y) + 1;
  4834. result.m[6] = temp3 * y;
  4835. result.m[7] = 0.0;
  4836. result.m[8] = temp * z;
  4837. result.m[9] = temp2 * z;
  4838. result.m[10] = (temp3 * z) + 1;
  4839. result.m[11] = 0.0;
  4840. result.m[12] = temp * plane.d;
  4841. result.m[13] = temp2 * plane.d;
  4842. result.m[14] = temp3 * plane.d;
  4843. result.m[15] = 1.0;
  4844. result._markAsUpdated();
  4845. };
  4846. /**
  4847. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4848. */
  4849. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4850. result.m[0] = xaxis.x;
  4851. result.m[1] = xaxis.y;
  4852. result.m[2] = xaxis.z;
  4853. result.m[3] = 0.0;
  4854. result.m[4] = yaxis.x;
  4855. result.m[5] = yaxis.y;
  4856. result.m[6] = yaxis.z;
  4857. result.m[7] = 0.0;
  4858. result.m[8] = zaxis.x;
  4859. result.m[9] = zaxis.y;
  4860. result.m[10] = zaxis.z;
  4861. result.m[11] = 0.0;
  4862. result.m[12] = 0.0;
  4863. result.m[13] = 0.0;
  4864. result.m[14] = 0.0;
  4865. result.m[15] = 1.0;
  4866. result._markAsUpdated();
  4867. };
  4868. /**
  4869. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4870. */
  4871. Matrix.FromQuaternionToRef = function (quat, result) {
  4872. var xx = quat.x * quat.x;
  4873. var yy = quat.y * quat.y;
  4874. var zz = quat.z * quat.z;
  4875. var xy = quat.x * quat.y;
  4876. var zw = quat.z * quat.w;
  4877. var zx = quat.z * quat.x;
  4878. var yw = quat.y * quat.w;
  4879. var yz = quat.y * quat.z;
  4880. var xw = quat.x * quat.w;
  4881. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4882. result.m[1] = 2.0 * (xy + zw);
  4883. result.m[2] = 2.0 * (zx - yw);
  4884. result.m[3] = 0.0;
  4885. result.m[4] = 2.0 * (xy - zw);
  4886. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4887. result.m[6] = 2.0 * (yz + xw);
  4888. result.m[7] = 0.0;
  4889. result.m[8] = 2.0 * (zx + yw);
  4890. result.m[9] = 2.0 * (yz - xw);
  4891. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4892. result.m[11] = 0.0;
  4893. result.m[12] = 0.0;
  4894. result.m[13] = 0.0;
  4895. result.m[14] = 0.0;
  4896. result.m[15] = 1.0;
  4897. result._markAsUpdated();
  4898. };
  4899. Matrix._tempQuaternion = new Quaternion();
  4900. Matrix._xAxis = Vector3.Zero();
  4901. Matrix._yAxis = Vector3.Zero();
  4902. Matrix._zAxis = Vector3.Zero();
  4903. Matrix._updateFlagSeed = 0;
  4904. Matrix._identityReadOnly = Matrix.Identity();
  4905. return Matrix;
  4906. }());
  4907. BABYLON.Matrix = Matrix;
  4908. var Plane = /** @class */ (function () {
  4909. /**
  4910. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4911. */
  4912. function Plane(a, b, c, d) {
  4913. this.normal = new Vector3(a, b, c);
  4914. this.d = d;
  4915. }
  4916. /**
  4917. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4918. */
  4919. Plane.prototype.asArray = function () {
  4920. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4921. };
  4922. // Methods
  4923. /**
  4924. * Returns a new plane copied from the current Plane.
  4925. */
  4926. Plane.prototype.clone = function () {
  4927. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4928. };
  4929. /**
  4930. * Returns the string "Plane".
  4931. */
  4932. Plane.prototype.getClassName = function () {
  4933. return "Plane";
  4934. };
  4935. /**
  4936. * Returns the Plane hash code.
  4937. */
  4938. Plane.prototype.getHashCode = function () {
  4939. var hash = this.normal.getHashCode();
  4940. hash = (hash * 397) ^ (this.d || 0);
  4941. return hash;
  4942. };
  4943. /**
  4944. * Normalize the current Plane in place.
  4945. * Returns the updated Plane.
  4946. */
  4947. Plane.prototype.normalize = function () {
  4948. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4949. var magnitude = 0.0;
  4950. if (norm !== 0) {
  4951. magnitude = 1.0 / norm;
  4952. }
  4953. this.normal.x *= magnitude;
  4954. this.normal.y *= magnitude;
  4955. this.normal.z *= magnitude;
  4956. this.d *= magnitude;
  4957. return this;
  4958. };
  4959. /**
  4960. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4961. */
  4962. Plane.prototype.transform = function (transformation) {
  4963. var transposedMatrix = Matrix.Transpose(transformation);
  4964. var x = this.normal.x;
  4965. var y = this.normal.y;
  4966. var z = this.normal.z;
  4967. var d = this.d;
  4968. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4969. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4970. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4971. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4972. return new Plane(normalX, normalY, normalZ, finalD);
  4973. };
  4974. /**
  4975. * Returns the dot product (float) of the point coordinates and the plane normal.
  4976. */
  4977. Plane.prototype.dotCoordinate = function (point) {
  4978. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4979. };
  4980. /**
  4981. * Updates the current Plane from the plane defined by the three passed points.
  4982. * Returns the updated Plane.
  4983. */
  4984. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4985. var x1 = point2.x - point1.x;
  4986. var y1 = point2.y - point1.y;
  4987. var z1 = point2.z - point1.z;
  4988. var x2 = point3.x - point1.x;
  4989. var y2 = point3.y - point1.y;
  4990. var z2 = point3.z - point1.z;
  4991. var yz = (y1 * z2) - (z1 * y2);
  4992. var xz = (z1 * x2) - (x1 * z2);
  4993. var xy = (x1 * y2) - (y1 * x2);
  4994. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4995. var invPyth;
  4996. if (pyth !== 0) {
  4997. invPyth = 1.0 / pyth;
  4998. }
  4999. else {
  5000. invPyth = 0.0;
  5001. }
  5002. this.normal.x = yz * invPyth;
  5003. this.normal.y = xz * invPyth;
  5004. this.normal.z = xy * invPyth;
  5005. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5006. return this;
  5007. };
  5008. /**
  5009. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5010. */
  5011. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5012. var dot = Vector3.Dot(this.normal, direction);
  5013. return (dot <= epsilon);
  5014. };
  5015. /**
  5016. * Returns the signed distance (float) from the passed point to the Plane.
  5017. */
  5018. Plane.prototype.signedDistanceTo = function (point) {
  5019. return Vector3.Dot(point, this.normal) + this.d;
  5020. };
  5021. // Statics
  5022. /**
  5023. * Returns a new Plane from the passed array.
  5024. */
  5025. Plane.FromArray = function (array) {
  5026. return new Plane(array[0], array[1], array[2], array[3]);
  5027. };
  5028. /**
  5029. * Returns a new Plane defined by the three passed points.
  5030. */
  5031. Plane.FromPoints = function (point1, point2, point3) {
  5032. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5033. result.copyFromPoints(point1, point2, point3);
  5034. return result;
  5035. };
  5036. /**
  5037. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5038. * Note : the vector "normal" is updated because normalized.
  5039. */
  5040. Plane.FromPositionAndNormal = function (origin, normal) {
  5041. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5042. normal.normalize();
  5043. result.normal = normal;
  5044. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5045. return result;
  5046. };
  5047. /**
  5048. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5049. */
  5050. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5051. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5052. return Vector3.Dot(point, normal) + d;
  5053. };
  5054. return Plane;
  5055. }());
  5056. BABYLON.Plane = Plane;
  5057. var Viewport = /** @class */ (function () {
  5058. /**
  5059. * Creates a Viewport object located at (x, y) and sized (width, height).
  5060. */
  5061. function Viewport(x, y, width, height) {
  5062. this.x = x;
  5063. this.y = y;
  5064. this.width = width;
  5065. this.height = height;
  5066. }
  5067. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5068. if (renderWidthOrEngine.getRenderWidth) {
  5069. var engine = renderWidthOrEngine;
  5070. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5071. }
  5072. var renderWidth = renderWidthOrEngine;
  5073. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5074. };
  5075. /**
  5076. * Returns a new Viewport copied from the current one.
  5077. */
  5078. Viewport.prototype.clone = function () {
  5079. return new Viewport(this.x, this.y, this.width, this.height);
  5080. };
  5081. return Viewport;
  5082. }());
  5083. BABYLON.Viewport = Viewport;
  5084. var Frustum = /** @class */ (function () {
  5085. function Frustum() {
  5086. }
  5087. /**
  5088. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5089. */
  5090. Frustum.GetPlanes = function (transform) {
  5091. var frustumPlanes = [];
  5092. for (var index = 0; index < 6; index++) {
  5093. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5094. }
  5095. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5096. return frustumPlanes;
  5097. };
  5098. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5099. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5100. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5101. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5102. frustumPlane.d = transform.m[15] + transform.m[14];
  5103. frustumPlane.normalize();
  5104. };
  5105. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5106. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5107. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5108. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5109. frustumPlane.d = transform.m[15] - transform.m[14];
  5110. frustumPlane.normalize();
  5111. };
  5112. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5113. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5114. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5115. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5116. frustumPlane.d = transform.m[15] + transform.m[12];
  5117. frustumPlane.normalize();
  5118. };
  5119. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5120. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5121. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5122. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5123. frustumPlane.d = transform.m[15] - transform.m[12];
  5124. frustumPlane.normalize();
  5125. };
  5126. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  5127. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  5128. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  5129. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  5130. frustumPlane.d = transform.m[15] - transform.m[13];
  5131. frustumPlane.normalize();
  5132. };
  5133. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  5134. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  5135. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  5136. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  5137. frustumPlane.d = transform.m[15] + transform.m[13];
  5138. frustumPlane.normalize();
  5139. };
  5140. /**
  5141. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  5142. */
  5143. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  5144. // Near
  5145. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  5146. // Far
  5147. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  5148. // Left
  5149. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  5150. // Right
  5151. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  5152. // Top
  5153. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  5154. // Bottom
  5155. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  5156. };
  5157. return Frustum;
  5158. }());
  5159. BABYLON.Frustum = Frustum;
  5160. var Space;
  5161. (function (Space) {
  5162. Space[Space["LOCAL"] = 0] = "LOCAL";
  5163. Space[Space["WORLD"] = 1] = "WORLD";
  5164. Space[Space["BONE"] = 2] = "BONE";
  5165. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  5166. var Axis = /** @class */ (function () {
  5167. function Axis() {
  5168. }
  5169. Axis.X = new Vector3(1.0, 0.0, 0.0);
  5170. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  5171. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  5172. return Axis;
  5173. }());
  5174. BABYLON.Axis = Axis;
  5175. ;
  5176. var BezierCurve = /** @class */ (function () {
  5177. function BezierCurve() {
  5178. }
  5179. /**
  5180. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  5181. */
  5182. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  5183. // Extract X (which is equal to time here)
  5184. var f0 = 1 - 3 * x2 + 3 * x1;
  5185. var f1 = 3 * x2 - 6 * x1;
  5186. var f2 = 3 * x1;
  5187. var refinedT = t;
  5188. for (var i = 0; i < 5; i++) {
  5189. var refinedT2 = refinedT * refinedT;
  5190. var refinedT3 = refinedT2 * refinedT;
  5191. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  5192. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  5193. refinedT -= (x - t) * slope;
  5194. refinedT = Math.min(1, Math.max(0, refinedT));
  5195. }
  5196. // Resolve cubic bezier for the given x
  5197. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  5198. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  5199. Math.pow(refinedT, 3);
  5200. };
  5201. return BezierCurve;
  5202. }());
  5203. BABYLON.BezierCurve = BezierCurve;
  5204. var Orientation;
  5205. (function (Orientation) {
  5206. Orientation[Orientation["CW"] = 0] = "CW";
  5207. Orientation[Orientation["CCW"] = 1] = "CCW";
  5208. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  5209. var Angle = /** @class */ (function () {
  5210. /**
  5211. * Creates an Angle object of "radians" radians (float).
  5212. */
  5213. function Angle(radians) {
  5214. var _this = this;
  5215. /**
  5216. * Returns the Angle value in degrees (float).
  5217. */
  5218. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  5219. /**
  5220. * Returns the Angle value in radians (float).
  5221. */
  5222. this.radians = function () { return _this._radians; };
  5223. this._radians = radians;
  5224. if (this._radians < 0.0)
  5225. this._radians += (2.0 * Math.PI);
  5226. }
  5227. /**
  5228. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  5229. */
  5230. Angle.BetweenTwoPoints = function (a, b) {
  5231. var delta = b.subtract(a);
  5232. var theta = Math.atan2(delta.y, delta.x);
  5233. return new Angle(theta);
  5234. };
  5235. /**
  5236. * Returns a new Angle object from the passed float in radians.
  5237. */
  5238. Angle.FromRadians = function (radians) {
  5239. return new Angle(radians);
  5240. };
  5241. /**
  5242. * Returns a new Angle object from the passed float in degrees.
  5243. */
  5244. Angle.FromDegrees = function (degrees) {
  5245. return new Angle(degrees * Math.PI / 180.0);
  5246. };
  5247. return Angle;
  5248. }());
  5249. BABYLON.Angle = Angle;
  5250. var Arc2 = /** @class */ (function () {
  5251. /**
  5252. * Creates an Arc object from the three passed points : start, middle and end.
  5253. */
  5254. function Arc2(startPoint, midPoint, endPoint) {
  5255. this.startPoint = startPoint;
  5256. this.midPoint = midPoint;
  5257. this.endPoint = endPoint;
  5258. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  5259. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  5260. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  5261. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  5262. 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);
  5263. this.radius = this.centerPoint.subtract(this.startPoint).length();
  5264. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  5265. var a1 = this.startAngle.degrees();
  5266. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  5267. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  5268. // angles correction
  5269. if (a2 - a1 > +180.0)
  5270. a2 -= 360.0;
  5271. if (a2 - a1 < -180.0)
  5272. a2 += 360.0;
  5273. if (a3 - a2 > +180.0)
  5274. a3 -= 360.0;
  5275. if (a3 - a2 < -180.0)
  5276. a3 += 360.0;
  5277. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  5278. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  5279. }
  5280. return Arc2;
  5281. }());
  5282. BABYLON.Arc2 = Arc2;
  5283. var Path2 = /** @class */ (function () {
  5284. /**
  5285. * Creates a Path2 object from the starting 2D coordinates x and y.
  5286. */
  5287. function Path2(x, y) {
  5288. this._points = new Array();
  5289. this._length = 0.0;
  5290. this.closed = false;
  5291. this._points.push(new Vector2(x, y));
  5292. }
  5293. /**
  5294. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  5295. * Returns the updated Path2.
  5296. */
  5297. Path2.prototype.addLineTo = function (x, y) {
  5298. if (this.closed) {
  5299. //Tools.Error("cannot add lines to closed paths");
  5300. return this;
  5301. }
  5302. var newPoint = new Vector2(x, y);
  5303. var previousPoint = this._points[this._points.length - 1];
  5304. this._points.push(newPoint);
  5305. this._length += newPoint.subtract(previousPoint).length();
  5306. return this;
  5307. };
  5308. /**
  5309. * 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.
  5310. * Returns the updated Path2.
  5311. */
  5312. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  5313. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  5314. if (this.closed) {
  5315. //Tools.Error("cannot add arcs to closed paths");
  5316. return this;
  5317. }
  5318. var startPoint = this._points[this._points.length - 1];
  5319. var midPoint = new Vector2(midX, midY);
  5320. var endPoint = new Vector2(endX, endY);
  5321. var arc = new Arc2(startPoint, midPoint, endPoint);
  5322. var increment = arc.angle.radians() / numberOfSegments;
  5323. if (arc.orientation === Orientation.CW)
  5324. increment *= -1;
  5325. var currentAngle = arc.startAngle.radians() + increment;
  5326. for (var i = 0; i < numberOfSegments; i++) {
  5327. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  5328. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  5329. this.addLineTo(x, y);
  5330. currentAngle += increment;
  5331. }
  5332. return this;
  5333. };
  5334. /**
  5335. * Closes the Path2.
  5336. * Returns the Path2.
  5337. */
  5338. Path2.prototype.close = function () {
  5339. this.closed = true;
  5340. return this;
  5341. };
  5342. /**
  5343. * Returns the Path2 total length (float).
  5344. */
  5345. Path2.prototype.length = function () {
  5346. var result = this._length;
  5347. if (!this.closed) {
  5348. var lastPoint = this._points[this._points.length - 1];
  5349. var firstPoint = this._points[0];
  5350. result += (firstPoint.subtract(lastPoint).length());
  5351. }
  5352. return result;
  5353. };
  5354. /**
  5355. * Returns the Path2 internal array of points.
  5356. */
  5357. Path2.prototype.getPoints = function () {
  5358. return this._points;
  5359. };
  5360. /**
  5361. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  5362. */
  5363. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  5364. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  5365. //Tools.Error("normalized length position should be between 0 and 1.");
  5366. return Vector2.Zero();
  5367. }
  5368. var lengthPosition = normalizedLengthPosition * this.length();
  5369. var previousOffset = 0;
  5370. for (var i = 0; i < this._points.length; i++) {
  5371. var j = (i + 1) % this._points.length;
  5372. var a = this._points[i];
  5373. var b = this._points[j];
  5374. var bToA = b.subtract(a);
  5375. var nextOffset = (bToA.length() + previousOffset);
  5376. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  5377. var dir = bToA.normalize();
  5378. var localOffset = lengthPosition - previousOffset;
  5379. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  5380. }
  5381. previousOffset = nextOffset;
  5382. }
  5383. //Tools.Error("internal error");
  5384. return Vector2.Zero();
  5385. };
  5386. /**
  5387. * Returns a new Path2 starting at the coordinates (x, y).
  5388. */
  5389. Path2.StartingAt = function (x, y) {
  5390. return new Path2(x, y);
  5391. };
  5392. return Path2;
  5393. }());
  5394. BABYLON.Path2 = Path2;
  5395. var Path3D = /** @class */ (function () {
  5396. /**
  5397. * new Path3D(path, normal, raw)
  5398. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  5399. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  5400. * path : an array of Vector3, the curve axis of the Path3D
  5401. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  5402. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  5403. */
  5404. function Path3D(path, firstNormal, raw) {
  5405. if (firstNormal === void 0) { firstNormal = null; }
  5406. this.path = path;
  5407. this._curve = new Array();
  5408. this._distances = new Array();
  5409. this._tangents = new Array();
  5410. this._normals = new Array();
  5411. this._binormals = new Array();
  5412. for (var p = 0; p < path.length; p++) {
  5413. this._curve[p] = path[p].clone(); // hard copy
  5414. }
  5415. this._raw = raw || false;
  5416. this._compute(firstNormal);
  5417. }
  5418. /**
  5419. * Returns the Path3D array of successive Vector3 designing its curve.
  5420. */
  5421. Path3D.prototype.getCurve = function () {
  5422. return this._curve;
  5423. };
  5424. /**
  5425. * Returns an array populated with tangent vectors on each Path3D curve point.
  5426. */
  5427. Path3D.prototype.getTangents = function () {
  5428. return this._tangents;
  5429. };
  5430. /**
  5431. * Returns an array populated with normal vectors on each Path3D curve point.
  5432. */
  5433. Path3D.prototype.getNormals = function () {
  5434. return this._normals;
  5435. };
  5436. /**
  5437. * Returns an array populated with binormal vectors on each Path3D curve point.
  5438. */
  5439. Path3D.prototype.getBinormals = function () {
  5440. return this._binormals;
  5441. };
  5442. /**
  5443. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  5444. */
  5445. Path3D.prototype.getDistances = function () {
  5446. return this._distances;
  5447. };
  5448. /**
  5449. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  5450. * Returns the same object updated.
  5451. */
  5452. Path3D.prototype.update = function (path, firstNormal) {
  5453. if (firstNormal === void 0) { firstNormal = null; }
  5454. for (var p = 0; p < path.length; p++) {
  5455. this._curve[p].x = path[p].x;
  5456. this._curve[p].y = path[p].y;
  5457. this._curve[p].z = path[p].z;
  5458. }
  5459. this._compute(firstNormal);
  5460. return this;
  5461. };
  5462. // private function compute() : computes tangents, normals and binormals
  5463. Path3D.prototype._compute = function (firstNormal) {
  5464. var l = this._curve.length;
  5465. // first and last tangents
  5466. this._tangents[0] = this._getFirstNonNullVector(0);
  5467. if (!this._raw) {
  5468. this._tangents[0].normalize();
  5469. }
  5470. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  5471. if (!this._raw) {
  5472. this._tangents[l - 1].normalize();
  5473. }
  5474. // normals and binormals at first point : arbitrary vector with _normalVector()
  5475. var tg0 = this._tangents[0];
  5476. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  5477. this._normals[0] = pp0;
  5478. if (!this._raw) {
  5479. this._normals[0].normalize();
  5480. }
  5481. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  5482. if (!this._raw) {
  5483. this._binormals[0].normalize();
  5484. }
  5485. this._distances[0] = 0.0;
  5486. // normals and binormals : next points
  5487. var prev; // previous vector (segment)
  5488. var cur; // current vector (segment)
  5489. var curTang; // current tangent
  5490. // previous normal
  5491. var prevBinor; // previous binormal
  5492. for (var i = 1; i < l; i++) {
  5493. // tangents
  5494. prev = this._getLastNonNullVector(i);
  5495. if (i < l - 1) {
  5496. cur = this._getFirstNonNullVector(i);
  5497. this._tangents[i] = prev.add(cur);
  5498. this._tangents[i].normalize();
  5499. }
  5500. this._distances[i] = this._distances[i - 1] + prev.length();
  5501. // normals and binormals
  5502. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  5503. curTang = this._tangents[i];
  5504. prevBinor = this._binormals[i - 1];
  5505. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  5506. if (!this._raw) {
  5507. this._normals[i].normalize();
  5508. }
  5509. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  5510. if (!this._raw) {
  5511. this._binormals[i].normalize();
  5512. }
  5513. }
  5514. };
  5515. // private function getFirstNonNullVector(index)
  5516. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  5517. Path3D.prototype._getFirstNonNullVector = function (index) {
  5518. var i = 1;
  5519. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  5520. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  5521. i++;
  5522. nNVector = this._curve[index + i].subtract(this._curve[index]);
  5523. }
  5524. return nNVector;
  5525. };
  5526. // private function getLastNonNullVector(index)
  5527. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  5528. Path3D.prototype._getLastNonNullVector = function (index) {
  5529. var i = 1;
  5530. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  5531. while (nLVector.length() === 0 && index > i + 1) {
  5532. i++;
  5533. nLVector = this._curve[index].subtract(this._curve[index - i]);
  5534. }
  5535. return nLVector;
  5536. };
  5537. // private function normalVector(v0, vt, va) :
  5538. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  5539. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  5540. Path3D.prototype._normalVector = function (v0, vt, va) {
  5541. var normal0;
  5542. var tgl = vt.length();
  5543. if (tgl === 0.0) {
  5544. tgl = 1.0;
  5545. }
  5546. if (va === undefined || va === null) {
  5547. var point;
  5548. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  5549. point = new Vector3(0.0, -1.0, 0.0);
  5550. }
  5551. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  5552. point = new Vector3(1.0, 0.0, 0.0);
  5553. }
  5554. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  5555. point = new Vector3(0.0, 0.0, 1.0);
  5556. }
  5557. else {
  5558. point = Vector3.Zero();
  5559. }
  5560. normal0 = Vector3.Cross(vt, point);
  5561. }
  5562. else {
  5563. normal0 = Vector3.Cross(vt, va);
  5564. Vector3.CrossToRef(normal0, vt, normal0);
  5565. }
  5566. normal0.normalize();
  5567. return normal0;
  5568. };
  5569. return Path3D;
  5570. }());
  5571. BABYLON.Path3D = Path3D;
  5572. var Curve3 = /** @class */ (function () {
  5573. /**
  5574. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  5575. * A Curve3 is designed from a series of successive Vector3.
  5576. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  5577. */
  5578. function Curve3(points) {
  5579. this._length = 0.0;
  5580. this._points = points;
  5581. this._length = this._computeLength(points);
  5582. }
  5583. /**
  5584. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  5585. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  5586. * @param v1 (Vector3) the control point
  5587. * @param v2 (Vector3) the end point of the Quadratic Bezier
  5588. * @param nbPoints (integer) the wanted number of points in the curve
  5589. */
  5590. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  5591. nbPoints = nbPoints > 2 ? nbPoints : 3;
  5592. var bez = new Array();
  5593. var equation = function (t, val0, val1, val2) {
  5594. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  5595. return res;
  5596. };
  5597. for (var i = 0; i <= nbPoints; i++) {
  5598. 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)));
  5599. }
  5600. return new Curve3(bez);
  5601. };
  5602. /**
  5603. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  5604. * @param v0 (Vector3) the origin point of the Cubic Bezier
  5605. * @param v1 (Vector3) the first control point
  5606. * @param v2 (Vector3) the second control point
  5607. * @param v3 (Vector3) the end point of the Cubic Bezier
  5608. * @param nbPoints (integer) the wanted number of points in the curve
  5609. */
  5610. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  5611. nbPoints = nbPoints > 3 ? nbPoints : 4;
  5612. var bez = new Array();
  5613. var equation = function (t, val0, val1, val2, val3) {
  5614. 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;
  5615. return res;
  5616. };
  5617. for (var i = 0; i <= nbPoints; i++) {
  5618. 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)));
  5619. }
  5620. return new Curve3(bez);
  5621. };
  5622. /**
  5623. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  5624. * @param p1 (Vector3) the origin point of the Hermite Spline
  5625. * @param t1 (Vector3) the tangent vector at the origin point
  5626. * @param p2 (Vector3) the end point of the Hermite Spline
  5627. * @param t2 (Vector3) the tangent vector at the end point
  5628. * @param nbPoints (integer) the wanted number of points in the curve
  5629. */
  5630. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  5631. var hermite = new Array();
  5632. var step = 1.0 / nbPoints;
  5633. for (var i = 0; i <= nbPoints; i++) {
  5634. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  5635. }
  5636. return new Curve3(hermite);
  5637. };
  5638. /**
  5639. * Returns a Curve3 object along a CatmullRom Spline curve :
  5640. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  5641. * @param nbPoints (integer) the wanted number of points between each curve control points.
  5642. */
  5643. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  5644. var totalPoints = new Array();
  5645. totalPoints.push(points[0].clone());
  5646. Array.prototype.push.apply(totalPoints, points);
  5647. totalPoints.push(points[points.length - 1].clone());
  5648. var catmullRom = new Array();
  5649. var step = 1.0 / nbPoints;
  5650. var amount = 0.0;
  5651. for (var i = 0; i < totalPoints.length - 3; i++) {
  5652. amount = 0;
  5653. for (var c = 0; c < nbPoints; c++) {
  5654. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5655. amount += step;
  5656. }
  5657. }
  5658. i--;
  5659. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  5660. return new Curve3(catmullRom);
  5661. };
  5662. /**
  5663. * Returns the Curve3 stored array of successive Vector3
  5664. */
  5665. Curve3.prototype.getPoints = function () {
  5666. return this._points;
  5667. };
  5668. /**
  5669. * Returns the computed length (float) of the curve.
  5670. */
  5671. Curve3.prototype.length = function () {
  5672. return this._length;
  5673. };
  5674. /**
  5675. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  5676. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  5677. * curveA and curveB keep unchanged.
  5678. */
  5679. Curve3.prototype.continue = function (curve) {
  5680. var lastPoint = this._points[this._points.length - 1];
  5681. var continuedPoints = this._points.slice();
  5682. var curvePoints = curve.getPoints();
  5683. for (var i = 1; i < curvePoints.length; i++) {
  5684. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  5685. }
  5686. var continuedCurve = new Curve3(continuedPoints);
  5687. return continuedCurve;
  5688. };
  5689. Curve3.prototype._computeLength = function (path) {
  5690. var l = 0;
  5691. for (var i = 1; i < path.length; i++) {
  5692. l += (path[i].subtract(path[i - 1])).length();
  5693. }
  5694. return l;
  5695. };
  5696. return Curve3;
  5697. }());
  5698. BABYLON.Curve3 = Curve3;
  5699. // Vertex formats
  5700. var PositionNormalVertex = /** @class */ (function () {
  5701. function PositionNormalVertex(position, normal) {
  5702. if (position === void 0) { position = Vector3.Zero(); }
  5703. if (normal === void 0) { normal = Vector3.Up(); }
  5704. this.position = position;
  5705. this.normal = normal;
  5706. }
  5707. PositionNormalVertex.prototype.clone = function () {
  5708. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  5709. };
  5710. return PositionNormalVertex;
  5711. }());
  5712. BABYLON.PositionNormalVertex = PositionNormalVertex;
  5713. var PositionNormalTextureVertex = /** @class */ (function () {
  5714. function PositionNormalTextureVertex(position, normal, uv) {
  5715. if (position === void 0) { position = Vector3.Zero(); }
  5716. if (normal === void 0) { normal = Vector3.Up(); }
  5717. if (uv === void 0) { uv = Vector2.Zero(); }
  5718. this.position = position;
  5719. this.normal = normal;
  5720. this.uv = uv;
  5721. }
  5722. PositionNormalTextureVertex.prototype.clone = function () {
  5723. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  5724. };
  5725. return PositionNormalTextureVertex;
  5726. }());
  5727. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  5728. // Temporary pre-allocated objects for engine internal use
  5729. // usage in any internal function :
  5730. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  5731. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  5732. var Tmp = /** @class */ (function () {
  5733. function Tmp() {
  5734. }
  5735. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  5736. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  5737. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  5738. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  5739. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  5740. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  5741. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  5742. Matrix.Zero(), Matrix.Zero(),
  5743. Matrix.Zero(), Matrix.Zero(),
  5744. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  5745. return Tmp;
  5746. }());
  5747. BABYLON.Tmp = Tmp;
  5748. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  5749. var MathTmp = /** @class */ (function () {
  5750. function MathTmp() {
  5751. }
  5752. MathTmp.Vector3 = [Vector3.Zero()];
  5753. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  5754. MathTmp.Quaternion = [Quaternion.Zero()];
  5755. return MathTmp;
  5756. }());
  5757. })(BABYLON || (BABYLON = {}));
  5758. //# sourceMappingURL=babylon.math.js.map
  5759. var BABYLON;
  5760. (function (BABYLON) {
  5761. var Scalar = /** @class */ (function () {
  5762. function Scalar() {
  5763. }
  5764. /**
  5765. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  5766. */
  5767. Scalar.WithinEpsilon = function (a, b, epsilon) {
  5768. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  5769. var num = a - b;
  5770. return -epsilon <= num && num <= epsilon;
  5771. };
  5772. /**
  5773. * Returns a string : the upper case translation of the number i to hexadecimal.
  5774. */
  5775. Scalar.ToHex = function (i) {
  5776. var str = i.toString(16);
  5777. if (i <= 15) {
  5778. return ("0" + str).toUpperCase();
  5779. }
  5780. return str.toUpperCase();
  5781. };
  5782. /**
  5783. * Returns -1 if value is negative and +1 is value is positive.
  5784. * Returns the value itself if it's equal to zero.
  5785. */
  5786. Scalar.Sign = function (value) {
  5787. value = +value; // convert to a number
  5788. if (value === 0 || isNaN(value))
  5789. return value;
  5790. return value > 0 ? 1 : -1;
  5791. };
  5792. /**
  5793. * Returns the value itself if it's between min and max.
  5794. * Returns min if the value is lower than min.
  5795. * Returns max if the value is greater than max.
  5796. */
  5797. Scalar.Clamp = function (value, min, max) {
  5798. if (min === void 0) { min = 0; }
  5799. if (max === void 0) { max = 1; }
  5800. return Math.min(max, Math.max(min, value));
  5801. };
  5802. /**
  5803. * Returns the log2 of value.
  5804. */
  5805. Scalar.Log2 = function (value) {
  5806. return Math.log(value) * Math.LOG2E;
  5807. };
  5808. /**
  5809. * Loops the value, so that it is never larger than length and never smaller than 0.
  5810. *
  5811. * This is similar to the modulo operator but it works with floating point numbers.
  5812. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  5813. * With t = 5 and length = 2.5, the result would be 0.0.
  5814. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  5815. */
  5816. Scalar.Repeat = function (value, length) {
  5817. return value - Math.floor(value / length) * length;
  5818. };
  5819. /**
  5820. * Normalize the value between 0.0 and 1.0 using min and max values
  5821. */
  5822. Scalar.Normalize = function (value, min, max) {
  5823. return (value - min) / (max - min);
  5824. };
  5825. /**
  5826. * Denormalize the value from 0.0 and 1.0 using min and max values
  5827. */
  5828. Scalar.Denormalize = function (normalized, min, max) {
  5829. return (normalized * (max - min) + min);
  5830. };
  5831. /**
  5832. * Calculates the shortest difference between two given angles given in degrees.
  5833. */
  5834. Scalar.DeltaAngle = function (current, target) {
  5835. var num = Scalar.Repeat(target - current, 360.0);
  5836. if (num > 180.0) {
  5837. num -= 360.0;
  5838. }
  5839. return num;
  5840. };
  5841. /**
  5842. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5843. *
  5844. * The returned value will move back and forth between 0 and length
  5845. */
  5846. Scalar.PingPong = function (tx, length) {
  5847. var t = Scalar.Repeat(tx, length * 2.0);
  5848. return length - Math.abs(t - length);
  5849. };
  5850. /**
  5851. * Interpolates between min and max with smoothing at the limits.
  5852. *
  5853. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5854. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5855. */
  5856. Scalar.SmoothStep = function (from, to, tx) {
  5857. var t = Scalar.Clamp(tx);
  5858. t = -2.0 * t * t * t + 3.0 * t * t;
  5859. return to * t + from * (1.0 - t);
  5860. };
  5861. /**
  5862. * Moves a value current towards target.
  5863. *
  5864. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5865. * Negative values of maxDelta pushes the value away from target.
  5866. */
  5867. Scalar.MoveTowards = function (current, target, maxDelta) {
  5868. var result = 0;
  5869. if (Math.abs(target - current) <= maxDelta) {
  5870. result = target;
  5871. }
  5872. else {
  5873. result = current + Scalar.Sign(target - current) * maxDelta;
  5874. }
  5875. return result;
  5876. };
  5877. /**
  5878. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5879. *
  5880. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5881. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5882. */
  5883. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5884. var num = Scalar.DeltaAngle(current, target);
  5885. var result = 0;
  5886. if (-maxDelta < num && num < maxDelta) {
  5887. result = target;
  5888. }
  5889. else {
  5890. target = current + num;
  5891. result = Scalar.MoveTowards(current, target, maxDelta);
  5892. }
  5893. return result;
  5894. };
  5895. /**
  5896. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5897. */
  5898. Scalar.Lerp = function (start, end, amount) {
  5899. return start + ((end - start) * amount);
  5900. };
  5901. /**
  5902. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5903. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5904. */
  5905. Scalar.LerpAngle = function (start, end, amount) {
  5906. var num = Scalar.Repeat(end - start, 360.0);
  5907. if (num > 180.0) {
  5908. num -= 360.0;
  5909. }
  5910. return start + num * Scalar.Clamp(amount);
  5911. };
  5912. /**
  5913. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5914. */
  5915. Scalar.InverseLerp = function (a, b, value) {
  5916. var result = 0;
  5917. if (a != b) {
  5918. result = Scalar.Clamp((value - a) / (b - a));
  5919. }
  5920. else {
  5921. result = 0.0;
  5922. }
  5923. return result;
  5924. };
  5925. /**
  5926. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5927. */
  5928. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5929. var squared = amount * amount;
  5930. var cubed = amount * squared;
  5931. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5932. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5933. var part3 = (cubed - (2.0 * squared)) + amount;
  5934. var part4 = cubed - squared;
  5935. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5936. };
  5937. /**
  5938. * Returns a random float number between and min and max values
  5939. */
  5940. Scalar.RandomRange = function (min, max) {
  5941. if (min === max)
  5942. return min;
  5943. return ((Math.random() * (max - min)) + min);
  5944. };
  5945. /**
  5946. * This function returns percentage of a number in a given range.
  5947. *
  5948. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5949. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5950. */
  5951. Scalar.RangeToPercent = function (number, min, max) {
  5952. return ((number - min) / (max - min));
  5953. };
  5954. /**
  5955. * This function returns number that corresponds to the percentage in a given range.
  5956. *
  5957. * PercentToRange(0.34,0,100) will return 34.
  5958. */
  5959. Scalar.PercentToRange = function (percent, min, max) {
  5960. return ((max - min) * percent + min);
  5961. };
  5962. /**
  5963. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5964. * @param angle The angle to normalize in radian.
  5965. * @return The converted angle.
  5966. */
  5967. Scalar.NormalizeRadians = function (angle) {
  5968. // More precise but slower version kept for reference.
  5969. // angle = angle % Tools.TwoPi;
  5970. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5971. //if (angle > Math.PI) {
  5972. // angle -= Tools.TwoPi;
  5973. //}
  5974. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5975. return angle;
  5976. };
  5977. /**
  5978. * Two pi constants convenient for computation.
  5979. */
  5980. Scalar.TwoPi = Math.PI * 2;
  5981. return Scalar;
  5982. }());
  5983. BABYLON.Scalar = Scalar;
  5984. })(BABYLON || (BABYLON = {}));
  5985. //# sourceMappingURL=babylon.math.scalar.js.map
  5986. //# sourceMappingURL=babylon.mixins.js.map
  5987. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  5988. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  5989. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  5990. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  5991. //# sourceMappingURL=babylon.webgl2.js.map
  5992. var BABYLON;
  5993. (function (BABYLON) {
  5994. var __decoratorInitialStore = {};
  5995. var __mergedStore = {};
  5996. var _copySource = function (creationFunction, source, instanciate) {
  5997. var destination = creationFunction();
  5998. // Tags
  5999. if (BABYLON.Tags) {
  6000. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6001. }
  6002. var classStore = getMergedStore(destination);
  6003. // Properties
  6004. for (var property in classStore) {
  6005. var propertyDescriptor = classStore[property];
  6006. var sourceProperty = source[property];
  6007. var propertyType = propertyDescriptor.type;
  6008. if (sourceProperty !== undefined && sourceProperty !== null) {
  6009. switch (propertyType) {
  6010. case 0: // Value
  6011. case 6:// Mesh reference
  6012. destination[property] = sourceProperty;
  6013. break;
  6014. case 1:// Texture
  6015. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6016. break;
  6017. case 2: // Color3
  6018. case 3: // FresnelParameters
  6019. case 4: // Vector2
  6020. case 5: // Vector3
  6021. case 7: // Color Curves
  6022. case 10:// Quaternion
  6023. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6024. break;
  6025. }
  6026. }
  6027. }
  6028. return destination;
  6029. };
  6030. function getDirectStore(target) {
  6031. var classKey = target.getClassName();
  6032. if (!__decoratorInitialStore[classKey]) {
  6033. __decoratorInitialStore[classKey] = {};
  6034. }
  6035. return __decoratorInitialStore[classKey];
  6036. }
  6037. /**
  6038. * Return the list of properties flagged as serializable
  6039. * @param target: host object
  6040. */
  6041. function getMergedStore(target) {
  6042. var classKey = target.getClassName();
  6043. if (__mergedStore[classKey]) {
  6044. return __mergedStore[classKey];
  6045. }
  6046. __mergedStore[classKey] = {};
  6047. var store = __mergedStore[classKey];
  6048. var currentTarget = target;
  6049. var currentKey = classKey;
  6050. while (currentKey) {
  6051. var initialStore = __decoratorInitialStore[currentKey];
  6052. for (var property in initialStore) {
  6053. store[property] = initialStore[property];
  6054. }
  6055. var parent_1 = void 0;
  6056. var done = false;
  6057. do {
  6058. parent_1 = Object.getPrototypeOf(currentTarget);
  6059. if (!parent_1.getClassName) {
  6060. done = true;
  6061. break;
  6062. }
  6063. if (parent_1.getClassName() !== currentKey) {
  6064. break;
  6065. }
  6066. currentTarget = parent_1;
  6067. } while (parent_1);
  6068. if (done) {
  6069. break;
  6070. }
  6071. currentKey = parent_1.getClassName();
  6072. currentTarget = parent_1;
  6073. }
  6074. return store;
  6075. }
  6076. function generateSerializableMember(type, sourceName) {
  6077. return function (target, propertyKey) {
  6078. var classStore = getDirectStore(target);
  6079. if (!classStore[propertyKey]) {
  6080. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6081. }
  6082. };
  6083. }
  6084. function generateExpandMember(setCallback, targetKey) {
  6085. if (targetKey === void 0) { targetKey = null; }
  6086. return function (target, propertyKey) {
  6087. var key = targetKey || ("_" + propertyKey);
  6088. Object.defineProperty(target, propertyKey, {
  6089. get: function () {
  6090. return this[key];
  6091. },
  6092. set: function (value) {
  6093. if (this[key] === value) {
  6094. return;
  6095. }
  6096. this[key] = value;
  6097. target[setCallback].apply(this);
  6098. },
  6099. enumerable: true,
  6100. configurable: true
  6101. });
  6102. };
  6103. }
  6104. function expandToProperty(callback, targetKey) {
  6105. if (targetKey === void 0) { targetKey = null; }
  6106. return generateExpandMember(callback, targetKey);
  6107. }
  6108. BABYLON.expandToProperty = expandToProperty;
  6109. function serialize(sourceName) {
  6110. return generateSerializableMember(0, sourceName); // value member
  6111. }
  6112. BABYLON.serialize = serialize;
  6113. function serializeAsTexture(sourceName) {
  6114. return generateSerializableMember(1, sourceName); // texture member
  6115. }
  6116. BABYLON.serializeAsTexture = serializeAsTexture;
  6117. function serializeAsColor3(sourceName) {
  6118. return generateSerializableMember(2, sourceName); // color3 member
  6119. }
  6120. BABYLON.serializeAsColor3 = serializeAsColor3;
  6121. function serializeAsFresnelParameters(sourceName) {
  6122. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6123. }
  6124. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6125. function serializeAsVector2(sourceName) {
  6126. return generateSerializableMember(4, sourceName); // vector2 member
  6127. }
  6128. BABYLON.serializeAsVector2 = serializeAsVector2;
  6129. function serializeAsVector3(sourceName) {
  6130. return generateSerializableMember(5, sourceName); // vector3 member
  6131. }
  6132. BABYLON.serializeAsVector3 = serializeAsVector3;
  6133. function serializeAsMeshReference(sourceName) {
  6134. return generateSerializableMember(6, sourceName); // mesh reference member
  6135. }
  6136. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  6137. function serializeAsColorCurves(sourceName) {
  6138. return generateSerializableMember(7, sourceName); // color curves
  6139. }
  6140. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  6141. function serializeAsColor4(sourceName) {
  6142. return generateSerializableMember(8, sourceName); // color 4
  6143. }
  6144. BABYLON.serializeAsColor4 = serializeAsColor4;
  6145. function serializeAsImageProcessingConfiguration(sourceName) {
  6146. return generateSerializableMember(9, sourceName); // image processing
  6147. }
  6148. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  6149. function serializeAsQuaternion(sourceName) {
  6150. return generateSerializableMember(10, sourceName); // quaternion member
  6151. }
  6152. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  6153. var SerializationHelper = /** @class */ (function () {
  6154. function SerializationHelper() {
  6155. }
  6156. SerializationHelper.Serialize = function (entity, serializationObject) {
  6157. if (!serializationObject) {
  6158. serializationObject = {};
  6159. }
  6160. // Tags
  6161. if (BABYLON.Tags) {
  6162. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  6163. }
  6164. var serializedProperties = getMergedStore(entity);
  6165. // Properties
  6166. for (var property in serializedProperties) {
  6167. var propertyDescriptor = serializedProperties[property];
  6168. var targetPropertyName = propertyDescriptor.sourceName || property;
  6169. var propertyType = propertyDescriptor.type;
  6170. var sourceProperty = entity[property];
  6171. if (sourceProperty !== undefined && sourceProperty !== null) {
  6172. switch (propertyType) {
  6173. case 0:// Value
  6174. serializationObject[targetPropertyName] = sourceProperty;
  6175. break;
  6176. case 1:// Texture
  6177. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6178. break;
  6179. case 2:// Color3
  6180. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6181. break;
  6182. case 3:// FresnelParameters
  6183. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6184. break;
  6185. case 4:// Vector2
  6186. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6187. break;
  6188. case 5:// Vector3
  6189. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6190. break;
  6191. case 6:// Mesh reference
  6192. serializationObject[targetPropertyName] = sourceProperty.id;
  6193. break;
  6194. case 7:// Color Curves
  6195. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6196. break;
  6197. case 8:// Color 4
  6198. serializationObject[targetPropertyName] = sourceProperty.asArray();
  6199. break;
  6200. case 9:// Image Processing
  6201. serializationObject[targetPropertyName] = sourceProperty.serialize();
  6202. break;
  6203. }
  6204. }
  6205. }
  6206. return serializationObject;
  6207. };
  6208. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  6209. if (rootUrl === void 0) { rootUrl = null; }
  6210. var destination = creationFunction();
  6211. if (!rootUrl) {
  6212. rootUrl = "";
  6213. }
  6214. // Tags
  6215. if (BABYLON.Tags) {
  6216. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6217. }
  6218. var classStore = getMergedStore(destination);
  6219. // Properties
  6220. for (var property in classStore) {
  6221. var propertyDescriptor = classStore[property];
  6222. var sourceProperty = source[propertyDescriptor.sourceName || property];
  6223. var propertyType = propertyDescriptor.type;
  6224. if (sourceProperty !== undefined && sourceProperty !== null) {
  6225. var dest = destination;
  6226. switch (propertyType) {
  6227. case 0:// Value
  6228. dest[property] = sourceProperty;
  6229. break;
  6230. case 1:// Texture
  6231. if (scene) {
  6232. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  6233. }
  6234. break;
  6235. case 2:// Color3
  6236. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  6237. break;
  6238. case 3:// FresnelParameters
  6239. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  6240. break;
  6241. case 4:// Vector2
  6242. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  6243. break;
  6244. case 5:// Vector3
  6245. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  6246. break;
  6247. case 6:// Mesh reference
  6248. if (scene) {
  6249. dest[property] = scene.getLastMeshByID(sourceProperty);
  6250. }
  6251. break;
  6252. case 7:// Color Curves
  6253. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  6254. break;
  6255. case 8:// Color 4
  6256. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  6257. break;
  6258. case 9:// Image Processing
  6259. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  6260. break;
  6261. }
  6262. }
  6263. }
  6264. return destination;
  6265. };
  6266. SerializationHelper.Clone = function (creationFunction, source) {
  6267. return _copySource(creationFunction, source, false);
  6268. };
  6269. SerializationHelper.Instanciate = function (creationFunction, source) {
  6270. return _copySource(creationFunction, source, true);
  6271. };
  6272. return SerializationHelper;
  6273. }());
  6274. BABYLON.SerializationHelper = SerializationHelper;
  6275. })(BABYLON || (BABYLON = {}));
  6276. //# sourceMappingURL=babylon.decorators.js.map
  6277. var BABYLON;
  6278. (function (BABYLON) {
  6279. /**
  6280. * A class serves as a medium between the observable and its observers
  6281. */
  6282. var EventState = /** @class */ (function () {
  6283. /**
  6284. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  6285. */
  6286. function EventState(mask, skipNextObservers, target, currentTarget) {
  6287. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6288. this.initalize(mask, skipNextObservers, target, currentTarget);
  6289. }
  6290. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  6291. if (skipNextObservers === void 0) { skipNextObservers = false; }
  6292. this.mask = mask;
  6293. this.skipNextObservers = skipNextObservers;
  6294. this.target = target;
  6295. this.currentTarget = currentTarget;
  6296. return this;
  6297. };
  6298. return EventState;
  6299. }());
  6300. BABYLON.EventState = EventState;
  6301. /**
  6302. * Represent an Observer registered to a given Observable object.
  6303. */
  6304. var Observer = /** @class */ (function () {
  6305. function Observer(callback, mask, scope) {
  6306. if (scope === void 0) { scope = null; }
  6307. this.callback = callback;
  6308. this.mask = mask;
  6309. this.scope = scope;
  6310. }
  6311. return Observer;
  6312. }());
  6313. BABYLON.Observer = Observer;
  6314. /**
  6315. * Represent a list of observers registered to multiple Observables object.
  6316. */
  6317. var MultiObserver = /** @class */ (function () {
  6318. function MultiObserver() {
  6319. }
  6320. MultiObserver.prototype.dispose = function () {
  6321. if (this._observers && this._observables) {
  6322. for (var index = 0; index < this._observers.length; index++) {
  6323. this._observables[index].remove(this._observers[index]);
  6324. }
  6325. }
  6326. this._observers = null;
  6327. this._observables = null;
  6328. };
  6329. MultiObserver.Watch = function (observables, callback, mask, scope) {
  6330. if (mask === void 0) { mask = -1; }
  6331. if (scope === void 0) { scope = null; }
  6332. var result = new MultiObserver();
  6333. result._observers = new Array();
  6334. result._observables = observables;
  6335. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  6336. var observable = observables_1[_i];
  6337. var observer = observable.add(callback, mask, false, scope);
  6338. if (observer) {
  6339. result._observers.push(observer);
  6340. }
  6341. }
  6342. return result;
  6343. };
  6344. return MultiObserver;
  6345. }());
  6346. BABYLON.MultiObserver = MultiObserver;
  6347. /**
  6348. * The Observable class is a simple implementation of the Observable pattern.
  6349. * 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.
  6350. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  6351. * 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).
  6352. * 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.
  6353. */
  6354. var Observable = /** @class */ (function () {
  6355. function Observable(onObserverAdded) {
  6356. this._observers = new Array();
  6357. this._eventState = new EventState(0);
  6358. if (onObserverAdded) {
  6359. this._onObserverAdded = onObserverAdded;
  6360. }
  6361. }
  6362. /**
  6363. * Create a new Observer with the specified callback
  6364. * @param callback the callback that will be executed for that Observer
  6365. * @param mask the mask used to filter observers
  6366. * @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.
  6367. * @param scope optional scope for the callback to be called from
  6368. */
  6369. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  6370. if (mask === void 0) { mask = -1; }
  6371. if (insertFirst === void 0) { insertFirst = false; }
  6372. if (scope === void 0) { scope = null; }
  6373. if (!callback) {
  6374. return null;
  6375. }
  6376. var observer = new Observer(callback, mask, scope);
  6377. if (insertFirst) {
  6378. this._observers.unshift(observer);
  6379. }
  6380. else {
  6381. this._observers.push(observer);
  6382. }
  6383. if (this._onObserverAdded) {
  6384. this._onObserverAdded(observer);
  6385. }
  6386. return observer;
  6387. };
  6388. /**
  6389. * Remove an Observer from the Observable object
  6390. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  6391. */
  6392. Observable.prototype.remove = function (observer) {
  6393. if (!observer) {
  6394. return false;
  6395. }
  6396. var index = this._observers.indexOf(observer);
  6397. if (index !== -1) {
  6398. this._observers.splice(index, 1);
  6399. return true;
  6400. }
  6401. return false;
  6402. };
  6403. /**
  6404. * Remove a callback from the Observable object
  6405. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  6406. * @param scope optional scope. If used only the callbacks with this scope will be removed.
  6407. */
  6408. Observable.prototype.removeCallback = function (callback, scope) {
  6409. for (var index = 0; index < this._observers.length; index++) {
  6410. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  6411. this._observers.splice(index, 1);
  6412. return true;
  6413. }
  6414. }
  6415. return false;
  6416. };
  6417. /**
  6418. * Notify all Observers by calling their respective callback with the given data
  6419. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  6420. * @param eventData
  6421. * @param mask
  6422. */
  6423. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  6424. if (mask === void 0) { mask = -1; }
  6425. if (!this._observers.length) {
  6426. return true;
  6427. }
  6428. var state = this._eventState;
  6429. state.mask = mask;
  6430. state.target = target;
  6431. state.currentTarget = currentTarget;
  6432. state.skipNextObservers = false;
  6433. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6434. var obs = _a[_i];
  6435. if (obs.mask & mask) {
  6436. if (obs.scope) {
  6437. obs.callback.apply(obs.scope, [eventData, state]);
  6438. }
  6439. else {
  6440. obs.callback(eventData, state);
  6441. }
  6442. }
  6443. if (state.skipNextObservers) {
  6444. return false;
  6445. }
  6446. }
  6447. return true;
  6448. };
  6449. /**
  6450. * Notify a specific observer
  6451. * @param eventData
  6452. * @param mask
  6453. */
  6454. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  6455. if (mask === void 0) { mask = -1; }
  6456. var state = this._eventState;
  6457. state.mask = mask;
  6458. state.skipNextObservers = false;
  6459. observer.callback(eventData, state);
  6460. };
  6461. /**
  6462. * return true is the Observable has at least one Observer registered
  6463. */
  6464. Observable.prototype.hasObservers = function () {
  6465. return this._observers.length > 0;
  6466. };
  6467. /**
  6468. * Clear the list of observers
  6469. */
  6470. Observable.prototype.clear = function () {
  6471. this._observers = new Array();
  6472. this._onObserverAdded = null;
  6473. };
  6474. /**
  6475. * Clone the current observable
  6476. */
  6477. Observable.prototype.clone = function () {
  6478. var result = new Observable();
  6479. result._observers = this._observers.slice(0);
  6480. return result;
  6481. };
  6482. /**
  6483. * Does this observable handles observer registered with a given mask
  6484. * @param {number} trigger - the mask to be tested
  6485. * @return {boolean} whether or not one observer registered with the given mask is handeled
  6486. **/
  6487. Observable.prototype.hasSpecificMask = function (mask) {
  6488. if (mask === void 0) { mask = -1; }
  6489. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  6490. var obs = _a[_i];
  6491. if (obs.mask & mask || obs.mask === mask) {
  6492. return true;
  6493. }
  6494. }
  6495. return false;
  6496. };
  6497. return Observable;
  6498. }());
  6499. BABYLON.Observable = Observable;
  6500. })(BABYLON || (BABYLON = {}));
  6501. //# sourceMappingURL=babylon.observable.js.map
  6502. var BABYLON;
  6503. (function (BABYLON) {
  6504. var SmartArray = /** @class */ (function () {
  6505. function SmartArray(capacity) {
  6506. this.length = 0;
  6507. this.data = new Array(capacity);
  6508. this._id = SmartArray._GlobalId++;
  6509. }
  6510. SmartArray.prototype.push = function (value) {
  6511. this.data[this.length++] = value;
  6512. if (this.length > this.data.length) {
  6513. this.data.length *= 2;
  6514. }
  6515. };
  6516. SmartArray.prototype.forEach = function (func) {
  6517. for (var index = 0; index < this.length; index++) {
  6518. func(this.data[index]);
  6519. }
  6520. };
  6521. SmartArray.prototype.sort = function (compareFn) {
  6522. this.data.sort(compareFn);
  6523. };
  6524. SmartArray.prototype.reset = function () {
  6525. this.length = 0;
  6526. };
  6527. SmartArray.prototype.dispose = function () {
  6528. this.reset();
  6529. if (this.data) {
  6530. this.data.length = 0;
  6531. this.data = [];
  6532. }
  6533. };
  6534. SmartArray.prototype.concat = function (array) {
  6535. if (array.length === 0) {
  6536. return;
  6537. }
  6538. if (this.length + array.length > this.data.length) {
  6539. this.data.length = (this.length + array.length) * 2;
  6540. }
  6541. for (var index = 0; index < array.length; index++) {
  6542. this.data[this.length++] = (array.data || array)[index];
  6543. }
  6544. };
  6545. SmartArray.prototype.indexOf = function (value) {
  6546. var position = this.data.indexOf(value);
  6547. if (position >= this.length) {
  6548. return -1;
  6549. }
  6550. return position;
  6551. };
  6552. SmartArray.prototype.contains = function (value) {
  6553. return this.data.indexOf(value) !== -1;
  6554. };
  6555. // Statics
  6556. SmartArray._GlobalId = 0;
  6557. return SmartArray;
  6558. }());
  6559. BABYLON.SmartArray = SmartArray;
  6560. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  6561. __extends(SmartArrayNoDuplicate, _super);
  6562. function SmartArrayNoDuplicate() {
  6563. var _this = _super !== null && _super.apply(this, arguments) || this;
  6564. _this._duplicateId = 0;
  6565. return _this;
  6566. }
  6567. SmartArrayNoDuplicate.prototype.push = function (value) {
  6568. _super.prototype.push.call(this, value);
  6569. if (!value.__smartArrayFlags) {
  6570. value.__smartArrayFlags = {};
  6571. }
  6572. value.__smartArrayFlags[this._id] = this._duplicateId;
  6573. };
  6574. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  6575. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  6576. return false;
  6577. }
  6578. this.push(value);
  6579. return true;
  6580. };
  6581. SmartArrayNoDuplicate.prototype.reset = function () {
  6582. _super.prototype.reset.call(this);
  6583. this._duplicateId++;
  6584. };
  6585. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  6586. if (array.length === 0) {
  6587. return;
  6588. }
  6589. if (this.length + array.length > this.data.length) {
  6590. this.data.length = (this.length + array.length) * 2;
  6591. }
  6592. for (var index = 0; index < array.length; index++) {
  6593. var item = (array.data || array)[index];
  6594. this.pushNoDuplicate(item);
  6595. }
  6596. };
  6597. return SmartArrayNoDuplicate;
  6598. }(SmartArray));
  6599. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  6600. })(BABYLON || (BABYLON = {}));
  6601. //# sourceMappingURL=babylon.smartArray.js.map
  6602. var BABYLON;
  6603. (function (BABYLON) {
  6604. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  6605. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  6606. var LoadFileError = /** @class */ (function (_super) {
  6607. __extends(LoadFileError, _super);
  6608. function LoadFileError(message, request) {
  6609. var _this = _super.call(this, message) || this;
  6610. _this.request = request;
  6611. _this.name = "LoadFileError";
  6612. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  6613. return _this;
  6614. }
  6615. // Polyfill for Object.setPrototypeOf if necessary.
  6616. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  6617. return LoadFileError;
  6618. }(Error));
  6619. BABYLON.LoadFileError = LoadFileError;
  6620. var RetryStrategy = /** @class */ (function () {
  6621. function RetryStrategy() {
  6622. }
  6623. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  6624. if (maxRetries === void 0) { maxRetries = 3; }
  6625. if (baseInterval === void 0) { baseInterval = 500; }
  6626. return function (url, request, retryIndex) {
  6627. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  6628. return -1;
  6629. }
  6630. return Math.pow(2, retryIndex) * baseInterval;
  6631. };
  6632. };
  6633. return RetryStrategy;
  6634. }());
  6635. BABYLON.RetryStrategy = RetryStrategy;
  6636. // Screenshots
  6637. var screenshotCanvas;
  6638. var cloneValue = function (source, destinationObject) {
  6639. if (!source)
  6640. return null;
  6641. if (source instanceof BABYLON.Mesh) {
  6642. return null;
  6643. }
  6644. if (source instanceof BABYLON.SubMesh) {
  6645. return source.clone(destinationObject);
  6646. }
  6647. else if (source.clone) {
  6648. return source.clone();
  6649. }
  6650. return null;
  6651. };
  6652. var Tools = /** @class */ (function () {
  6653. function Tools() {
  6654. }
  6655. /**
  6656. * Interpolates between a and b via alpha
  6657. * @param a The lower value (returned when alpha = 0)
  6658. * @param b The upper value (returned when alpha = 1)
  6659. * @param alpha The interpolation-factor
  6660. * @return The mixed value
  6661. */
  6662. Tools.Mix = function (a, b, alpha) {
  6663. return a * (1 - alpha) + b * alpha;
  6664. };
  6665. Tools.Instantiate = function (className) {
  6666. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  6667. return Tools.RegisteredExternalClasses[className];
  6668. }
  6669. var arr = className.split(".");
  6670. var fn = (window || this);
  6671. for (var i = 0, len = arr.length; i < len; i++) {
  6672. fn = fn[arr[i]];
  6673. }
  6674. if (typeof fn !== "function") {
  6675. return null;
  6676. }
  6677. return fn;
  6678. };
  6679. Tools.SetImmediate = function (action) {
  6680. if (window.setImmediate) {
  6681. window.setImmediate(action);
  6682. }
  6683. else {
  6684. setTimeout(action, 1);
  6685. }
  6686. };
  6687. Tools.IsExponentOfTwo = function (value) {
  6688. var count = 1;
  6689. do {
  6690. count *= 2;
  6691. } while (count < value);
  6692. return count === value;
  6693. };
  6694. /**
  6695. * Find the next highest power of two.
  6696. * @param x Number to start search from.
  6697. * @return Next highest power of two.
  6698. */
  6699. Tools.CeilingPOT = function (x) {
  6700. x--;
  6701. x |= x >> 1;
  6702. x |= x >> 2;
  6703. x |= x >> 4;
  6704. x |= x >> 8;
  6705. x |= x >> 16;
  6706. x++;
  6707. return x;
  6708. };
  6709. /**
  6710. * Find the next lowest power of two.
  6711. * @param x Number to start search from.
  6712. * @return Next lowest power of two.
  6713. */
  6714. Tools.FloorPOT = function (x) {
  6715. x = x | (x >> 1);
  6716. x = x | (x >> 2);
  6717. x = x | (x >> 4);
  6718. x = x | (x >> 8);
  6719. x = x | (x >> 16);
  6720. return x - (x >> 1);
  6721. };
  6722. /**
  6723. * Find the nearest power of two.
  6724. * @param x Number to start search from.
  6725. * @return Next nearest power of two.
  6726. */
  6727. Tools.NearestPOT = function (x) {
  6728. var c = Tools.CeilingPOT(x);
  6729. var f = Tools.FloorPOT(x);
  6730. return (c - x) > (x - f) ? f : c;
  6731. };
  6732. Tools.GetExponentOfTwo = function (value, max, mode) {
  6733. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  6734. var pot;
  6735. switch (mode) {
  6736. case BABYLON.Engine.SCALEMODE_FLOOR:
  6737. pot = Tools.FloorPOT(value);
  6738. break;
  6739. case BABYLON.Engine.SCALEMODE_NEAREST:
  6740. pot = Tools.NearestPOT(value);
  6741. break;
  6742. case BABYLON.Engine.SCALEMODE_CEILING:
  6743. default:
  6744. pot = Tools.CeilingPOT(value);
  6745. break;
  6746. }
  6747. return Math.min(pot, max);
  6748. };
  6749. Tools.GetFilename = function (path) {
  6750. var index = path.lastIndexOf("/");
  6751. if (index < 0)
  6752. return path;
  6753. return path.substring(index + 1);
  6754. };
  6755. Tools.GetFolderPath = function (uri) {
  6756. var index = uri.lastIndexOf("/");
  6757. if (index < 0)
  6758. return "";
  6759. return uri.substring(0, index + 1);
  6760. };
  6761. Tools.GetDOMTextContent = function (element) {
  6762. var result = "";
  6763. var child = element.firstChild;
  6764. while (child) {
  6765. if (child.nodeType === 3) {
  6766. result += child.textContent;
  6767. }
  6768. child = child.nextSibling;
  6769. }
  6770. return result;
  6771. };
  6772. Tools.ToDegrees = function (angle) {
  6773. return angle * 180 / Math.PI;
  6774. };
  6775. Tools.ToRadians = function (angle) {
  6776. return angle * Math.PI / 180;
  6777. };
  6778. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  6779. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  6780. var output = "";
  6781. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  6782. var i = 0;
  6783. var bytes = new Uint8Array(buffer);
  6784. while (i < bytes.length) {
  6785. chr1 = bytes[i++];
  6786. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  6787. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  6788. enc1 = chr1 >> 2;
  6789. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  6790. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  6791. enc4 = chr3 & 63;
  6792. if (isNaN(chr2)) {
  6793. enc3 = enc4 = 64;
  6794. }
  6795. else if (isNaN(chr3)) {
  6796. enc4 = 64;
  6797. }
  6798. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  6799. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  6800. }
  6801. return "data:image/png;base64," + output;
  6802. };
  6803. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  6804. if (bias === void 0) { bias = null; }
  6805. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6806. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6807. for (var index = indexStart; index < indexStart + indexCount; index++) {
  6808. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  6809. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6810. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6811. }
  6812. if (bias) {
  6813. minimum.x -= minimum.x * bias.x + bias.y;
  6814. minimum.y -= minimum.y * bias.x + bias.y;
  6815. minimum.z -= minimum.z * bias.x + bias.y;
  6816. maximum.x += maximum.x * bias.x + bias.y;
  6817. maximum.y += maximum.y * bias.x + bias.y;
  6818. maximum.z += maximum.z * bias.x + bias.y;
  6819. }
  6820. return {
  6821. minimum: minimum,
  6822. maximum: maximum
  6823. };
  6824. };
  6825. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  6826. if (bias === void 0) { bias = null; }
  6827. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6828. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  6829. if (!stride) {
  6830. stride = 3;
  6831. }
  6832. for (var index = start; index < start + count; index++) {
  6833. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6834. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6835. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6836. }
  6837. if (bias) {
  6838. minimum.x -= minimum.x * bias.x + bias.y;
  6839. minimum.y -= minimum.y * bias.x + bias.y;
  6840. minimum.z -= minimum.z * bias.x + bias.y;
  6841. maximum.x += maximum.x * bias.x + bias.y;
  6842. maximum.y += maximum.y * bias.x + bias.y;
  6843. maximum.z += maximum.z * bias.x + bias.y;
  6844. }
  6845. return {
  6846. minimum: minimum,
  6847. maximum: maximum
  6848. };
  6849. };
  6850. Tools.Vector2ArrayFeeder = function (array) {
  6851. return function (index) {
  6852. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6853. var length = isFloatArray ? array.length / 2 : array.length;
  6854. if (index >= length) {
  6855. return null;
  6856. }
  6857. if (isFloatArray) {
  6858. var fa = array;
  6859. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6860. }
  6861. var a = array;
  6862. return a[index];
  6863. };
  6864. };
  6865. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6866. if (bias === void 0) { bias = null; }
  6867. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6868. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6869. var i = 0;
  6870. var cur = feeder(i++);
  6871. while (cur) {
  6872. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6873. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6874. cur = feeder(i++);
  6875. }
  6876. if (bias) {
  6877. minimum.x -= minimum.x * bias.x + bias.y;
  6878. minimum.y -= minimum.y * bias.x + bias.y;
  6879. maximum.x += maximum.x * bias.x + bias.y;
  6880. maximum.y += maximum.y * bias.x + bias.y;
  6881. }
  6882. return {
  6883. minimum: minimum,
  6884. maximum: maximum
  6885. };
  6886. };
  6887. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6888. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6889. return null;
  6890. return Array.isArray(obj) ? obj : [obj];
  6891. };
  6892. // Misc.
  6893. Tools.GetPointerPrefix = function () {
  6894. var eventPrefix = "pointer";
  6895. // Check if pointer events are supported
  6896. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6897. eventPrefix = "mouse";
  6898. }
  6899. return eventPrefix;
  6900. };
  6901. /**
  6902. * @param func - the function to be called
  6903. * @param requester - the object that will request the next frame. Falls back to window.
  6904. */
  6905. Tools.QueueNewFrame = function (func, requester) {
  6906. if (!Tools.IsWindowObjectExist()) {
  6907. return setTimeout(func, 16);
  6908. }
  6909. if (!requester) {
  6910. requester = window;
  6911. }
  6912. if (requester.requestAnimationFrame) {
  6913. return requester.requestAnimationFrame(func);
  6914. }
  6915. else if (requester.msRequestAnimationFrame) {
  6916. return requester.msRequestAnimationFrame(func);
  6917. }
  6918. else if (requester.webkitRequestAnimationFrame) {
  6919. return requester.webkitRequestAnimationFrame(func);
  6920. }
  6921. else if (requester.mozRequestAnimationFrame) {
  6922. return requester.mozRequestAnimationFrame(func);
  6923. }
  6924. else if (requester.oRequestAnimationFrame) {
  6925. return requester.oRequestAnimationFrame(func);
  6926. }
  6927. else {
  6928. return window.setTimeout(func, 16);
  6929. }
  6930. };
  6931. Tools.RequestFullscreen = function (element) {
  6932. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6933. if (!requestFunction)
  6934. return;
  6935. requestFunction.call(element);
  6936. };
  6937. Tools.ExitFullscreen = function () {
  6938. if (document.exitFullscreen) {
  6939. document.exitFullscreen();
  6940. }
  6941. else if (document.mozCancelFullScreen) {
  6942. document.mozCancelFullScreen();
  6943. }
  6944. else if (document.webkitCancelFullScreen) {
  6945. document.webkitCancelFullScreen();
  6946. }
  6947. else if (document.msCancelFullScreen) {
  6948. document.msCancelFullScreen();
  6949. }
  6950. };
  6951. Tools.SetCorsBehavior = function (url, element) {
  6952. if (url && url.indexOf("data:") === 0) {
  6953. return;
  6954. }
  6955. if (Tools.CorsBehavior) {
  6956. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6957. element.crossOrigin = Tools.CorsBehavior;
  6958. }
  6959. else {
  6960. var result = Tools.CorsBehavior(url);
  6961. if (result) {
  6962. element.crossOrigin = result;
  6963. }
  6964. }
  6965. }
  6966. };
  6967. // External files
  6968. Tools.CleanUrl = function (url) {
  6969. url = url.replace(/#/mg, "%23");
  6970. return url;
  6971. };
  6972. Tools.LoadImage = function (url, onLoad, onError, database) {
  6973. if (url instanceof ArrayBuffer) {
  6974. url = Tools.EncodeArrayBufferTobase64(url);
  6975. }
  6976. url = Tools.CleanUrl(url);
  6977. url = Tools.PreprocessUrl(url);
  6978. var img = new Image();
  6979. Tools.SetCorsBehavior(url, img);
  6980. img.onload = function () {
  6981. onLoad(img);
  6982. };
  6983. img.onerror = function (err) {
  6984. Tools.Error("Error while trying to load image: " + url);
  6985. if (onError) {
  6986. onError("Error while trying to load image: " + url, err);
  6987. }
  6988. };
  6989. var noIndexedDB = function () {
  6990. img.src = url;
  6991. };
  6992. var loadFromIndexedDB = function () {
  6993. if (database) {
  6994. database.loadImageFromDB(url, img);
  6995. }
  6996. };
  6997. //ANY database to do!
  6998. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6999. database.openAsync(loadFromIndexedDB, noIndexedDB);
  7000. }
  7001. else {
  7002. if (url.indexOf("file:") !== -1) {
  7003. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  7004. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  7005. try {
  7006. var blobURL;
  7007. try {
  7008. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  7009. }
  7010. catch (ex) {
  7011. // Chrome doesn't support oneTimeOnly parameter
  7012. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  7013. }
  7014. img.src = blobURL;
  7015. }
  7016. catch (e) {
  7017. img.src = "";
  7018. }
  7019. return img;
  7020. }
  7021. }
  7022. noIndexedDB();
  7023. }
  7024. return img;
  7025. };
  7026. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  7027. url = Tools.CleanUrl(url);
  7028. url = Tools.PreprocessUrl(url);
  7029. // If file and file input are set
  7030. if (url.indexOf("file:") !== -1) {
  7031. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  7032. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  7033. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  7034. }
  7035. }
  7036. var loadUrl = Tools.BaseUrl + url;
  7037. var aborted = false;
  7038. var fileRequest = {
  7039. onCompleteObservable: new BABYLON.Observable(),
  7040. abort: function () { return aborted = true; },
  7041. };
  7042. var requestFile = function () {
  7043. var request = new XMLHttpRequest();
  7044. var retryHandle = null;
  7045. fileRequest.abort = function () {
  7046. aborted = true;
  7047. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  7048. request.abort();
  7049. }
  7050. if (retryHandle !== null) {
  7051. clearTimeout(retryHandle);
  7052. retryHandle = null;
  7053. }
  7054. };
  7055. var retryLoop = function (retryIndex) {
  7056. request.open('GET', loadUrl, true);
  7057. if (useArrayBuffer) {
  7058. request.responseType = "arraybuffer";
  7059. }
  7060. if (onProgress) {
  7061. request.addEventListener("progress", onProgress);
  7062. }
  7063. var onLoadEnd = function () {
  7064. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7065. };
  7066. request.addEventListener("loadend", onLoadEnd);
  7067. var onReadyStateChange = function () {
  7068. if (aborted) {
  7069. return;
  7070. }
  7071. // In case of undefined state in some browsers.
  7072. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  7073. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  7074. request.removeEventListener("readystatechange", onReadyStateChange);
  7075. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  7076. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  7077. return;
  7078. }
  7079. var retryStrategy = Tools.DefaultRetryStrategy;
  7080. if (retryStrategy) {
  7081. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  7082. if (waitTime !== -1) {
  7083. // Prevent the request from completing for retry.
  7084. request.removeEventListener("loadend", onLoadEnd);
  7085. request = new XMLHttpRequest();
  7086. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  7087. return;
  7088. }
  7089. }
  7090. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  7091. if (onError) {
  7092. onError(request, e);
  7093. }
  7094. else {
  7095. throw e;
  7096. }
  7097. }
  7098. };
  7099. request.addEventListener("readystatechange", onReadyStateChange);
  7100. request.send();
  7101. };
  7102. retryLoop(0);
  7103. };
  7104. // Caching all files
  7105. if (database && database.enableSceneOffline) {
  7106. var noIndexedDB_1 = function () {
  7107. if (!aborted) {
  7108. requestFile();
  7109. }
  7110. };
  7111. var loadFromIndexedDB = function () {
  7112. // TODO: database needs to support aborting and should return a IFileRequest
  7113. if (aborted) {
  7114. return;
  7115. }
  7116. if (database) {
  7117. database.loadFileFromDB(url, function (data) {
  7118. if (!aborted) {
  7119. onSuccess(data);
  7120. }
  7121. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  7122. }, onProgress ? function (event) {
  7123. if (!aborted) {
  7124. onProgress(event);
  7125. }
  7126. } : undefined, noIndexedDB_1, useArrayBuffer);
  7127. }
  7128. };
  7129. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  7130. }
  7131. else {
  7132. requestFile();
  7133. }
  7134. return fileRequest;
  7135. };
  7136. /**
  7137. * Load a script (identified by an url). When the url returns, the
  7138. * content of this file is added into a new script element, attached to the DOM (body element)
  7139. */
  7140. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  7141. var head = document.getElementsByTagName('head')[0];
  7142. var script = document.createElement('script');
  7143. script.type = 'text/javascript';
  7144. script.src = scriptUrl;
  7145. script.onload = function () {
  7146. if (onSuccess) {
  7147. onSuccess();
  7148. }
  7149. };
  7150. script.onerror = function (e) {
  7151. if (onError) {
  7152. onError("Unable to load script", e);
  7153. }
  7154. };
  7155. head.appendChild(script);
  7156. };
  7157. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  7158. var reader = new FileReader();
  7159. var request = {
  7160. onCompleteObservable: new BABYLON.Observable(),
  7161. abort: function () { return reader.abort(); },
  7162. };
  7163. reader.onloadend = function (e) {
  7164. request.onCompleteObservable.notifyObservers(request);
  7165. };
  7166. reader.onload = function (e) {
  7167. //target doesn't have result from ts 1.3
  7168. callback(e.target['result']);
  7169. };
  7170. reader.onprogress = progressCallback;
  7171. reader.readAsDataURL(fileToLoad);
  7172. return request;
  7173. };
  7174. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  7175. var reader = new FileReader();
  7176. var request = {
  7177. onCompleteObservable: new BABYLON.Observable(),
  7178. abort: function () { return reader.abort(); },
  7179. };
  7180. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  7181. reader.onerror = function (e) {
  7182. Tools.Log("Error while reading file: " + fileToLoad.name);
  7183. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  7184. };
  7185. reader.onload = function (e) {
  7186. //target doesn't have result from ts 1.3
  7187. callback(e.target['result']);
  7188. };
  7189. if (progressCallBack) {
  7190. reader.onprogress = progressCallBack;
  7191. }
  7192. if (!useArrayBuffer) {
  7193. // Asynchronous read
  7194. reader.readAsText(fileToLoad);
  7195. }
  7196. else {
  7197. reader.readAsArrayBuffer(fileToLoad);
  7198. }
  7199. return request;
  7200. };
  7201. //returns a downloadable url to a file content.
  7202. Tools.FileAsURL = function (content) {
  7203. var fileBlob = new Blob([content]);
  7204. var url = window.URL || window.webkitURL;
  7205. var link = url.createObjectURL(fileBlob);
  7206. return link;
  7207. };
  7208. // Misc.
  7209. Tools.Format = function (value, decimals) {
  7210. if (decimals === void 0) { decimals = 2; }
  7211. return value.toFixed(decimals);
  7212. };
  7213. Tools.CheckExtends = function (v, min, max) {
  7214. if (v.x < min.x)
  7215. min.x = v.x;
  7216. if (v.y < min.y)
  7217. min.y = v.y;
  7218. if (v.z < min.z)
  7219. min.z = v.z;
  7220. if (v.x > max.x)
  7221. max.x = v.x;
  7222. if (v.y > max.y)
  7223. max.y = v.y;
  7224. if (v.z > max.z)
  7225. max.z = v.z;
  7226. };
  7227. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  7228. for (var prop in source) {
  7229. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  7230. continue;
  7231. }
  7232. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  7233. continue;
  7234. }
  7235. var sourceValue = source[prop];
  7236. var typeOfSourceValue = typeof sourceValue;
  7237. if (typeOfSourceValue === "function") {
  7238. continue;
  7239. }
  7240. if (typeOfSourceValue === "object") {
  7241. if (sourceValue instanceof Array) {
  7242. destination[prop] = [];
  7243. if (sourceValue.length > 0) {
  7244. if (typeof sourceValue[0] == "object") {
  7245. for (var index = 0; index < sourceValue.length; index++) {
  7246. var clonedValue = cloneValue(sourceValue[index], destination);
  7247. if (destination[prop].indexOf(clonedValue) === -1) {
  7248. destination[prop].push(clonedValue);
  7249. }
  7250. }
  7251. }
  7252. else {
  7253. destination[prop] = sourceValue.slice(0);
  7254. }
  7255. }
  7256. }
  7257. else {
  7258. destination[prop] = cloneValue(sourceValue, destination);
  7259. }
  7260. }
  7261. else {
  7262. destination[prop] = sourceValue;
  7263. }
  7264. }
  7265. };
  7266. Tools.IsEmpty = function (obj) {
  7267. for (var i in obj) {
  7268. if (obj.hasOwnProperty(i)) {
  7269. return false;
  7270. }
  7271. }
  7272. return true;
  7273. };
  7274. Tools.RegisterTopRootEvents = function (events) {
  7275. for (var index = 0; index < events.length; index++) {
  7276. var event = events[index];
  7277. window.addEventListener(event.name, event.handler, false);
  7278. try {
  7279. if (window.parent) {
  7280. window.parent.addEventListener(event.name, event.handler, false);
  7281. }
  7282. }
  7283. catch (e) {
  7284. // Silently fails...
  7285. }
  7286. }
  7287. };
  7288. Tools.UnregisterTopRootEvents = function (events) {
  7289. for (var index = 0; index < events.length; index++) {
  7290. var event = events[index];
  7291. window.removeEventListener(event.name, event.handler);
  7292. try {
  7293. if (window.parent) {
  7294. window.parent.removeEventListener(event.name, event.handler);
  7295. }
  7296. }
  7297. catch (e) {
  7298. // Silently fails...
  7299. }
  7300. }
  7301. };
  7302. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  7303. if (mimeType === void 0) { mimeType = "image/png"; }
  7304. // Read the contents of the framebuffer
  7305. var numberOfChannelsByLine = width * 4;
  7306. var halfHeight = height / 2;
  7307. //Reading datas from WebGL
  7308. var data = engine.readPixels(0, 0, width, height);
  7309. //To flip image on Y axis.
  7310. for (var i = 0; i < halfHeight; i++) {
  7311. for (var j = 0; j < numberOfChannelsByLine; j++) {
  7312. var currentCell = j + i * numberOfChannelsByLine;
  7313. var targetLine = height - i - 1;
  7314. var targetCell = j + targetLine * numberOfChannelsByLine;
  7315. var temp = data[currentCell];
  7316. data[currentCell] = data[targetCell];
  7317. data[targetCell] = temp;
  7318. }
  7319. }
  7320. // Create a 2D canvas to store the result
  7321. if (!screenshotCanvas) {
  7322. screenshotCanvas = document.createElement('canvas');
  7323. }
  7324. screenshotCanvas.width = width;
  7325. screenshotCanvas.height = height;
  7326. var context = screenshotCanvas.getContext('2d');
  7327. if (context) {
  7328. // Copy the pixels to a 2D canvas
  7329. var imageData = context.createImageData(width, height);
  7330. var castData = (imageData.data);
  7331. castData.set(data);
  7332. context.putImageData(imageData, 0, 0);
  7333. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  7334. }
  7335. };
  7336. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  7337. if (mimeType === void 0) { mimeType = "image/png"; }
  7338. var base64Image = screenshotCanvas.toDataURL(mimeType);
  7339. if (successCallback) {
  7340. successCallback(base64Image);
  7341. }
  7342. else {
  7343. // We need HTMLCanvasElement.toBlob for HD screenshots
  7344. if (!screenshotCanvas.toBlob) {
  7345. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  7346. screenshotCanvas.toBlob = function (callback, type, quality) {
  7347. var _this = this;
  7348. setTimeout(function () {
  7349. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  7350. for (var i = 0; i < len; i++) {
  7351. arr[i] = binStr.charCodeAt(i);
  7352. }
  7353. callback(new Blob([arr], { type: type || 'image/png' }));
  7354. });
  7355. };
  7356. }
  7357. screenshotCanvas.toBlob(function (blob) {
  7358. var url = URL.createObjectURL(blob);
  7359. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  7360. if (("download" in document.createElement("a"))) {
  7361. var a = window.document.createElement("a");
  7362. a.href = url;
  7363. if (fileName) {
  7364. a.setAttribute("download", fileName);
  7365. }
  7366. else {
  7367. var date = new Date();
  7368. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  7369. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  7370. }
  7371. window.document.body.appendChild(a);
  7372. a.addEventListener("click", function () {
  7373. if (a.parentElement) {
  7374. a.parentElement.removeChild(a);
  7375. }
  7376. });
  7377. a.click();
  7378. }
  7379. else {
  7380. var newWindow = window.open("");
  7381. if (!newWindow)
  7382. return;
  7383. var img = newWindow.document.createElement("img");
  7384. img.onload = function () {
  7385. // no longer need to read the blob so it's revoked
  7386. URL.revokeObjectURL(url);
  7387. };
  7388. img.src = url;
  7389. newWindow.document.body.appendChild(img);
  7390. }
  7391. });
  7392. }
  7393. };
  7394. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  7395. if (mimeType === void 0) { mimeType = "image/png"; }
  7396. var width;
  7397. var height;
  7398. // If a precision value is specified
  7399. if (size.precision) {
  7400. width = Math.round(engine.getRenderWidth() * size.precision);
  7401. height = Math.round(width / engine.getAspectRatio(camera));
  7402. }
  7403. else if (size.width && size.height) {
  7404. width = size.width;
  7405. height = size.height;
  7406. }
  7407. else if (size.width && !size.height) {
  7408. width = size.width;
  7409. height = Math.round(width / engine.getAspectRatio(camera));
  7410. }
  7411. else if (size.height && !size.width) {
  7412. height = size.height;
  7413. width = Math.round(height * engine.getAspectRatio(camera));
  7414. }
  7415. else if (!isNaN(size)) {
  7416. height = size;
  7417. width = size;
  7418. }
  7419. else {
  7420. Tools.Error("Invalid 'size' parameter !");
  7421. return;
  7422. }
  7423. if (!screenshotCanvas) {
  7424. screenshotCanvas = document.createElement('canvas');
  7425. }
  7426. screenshotCanvas.width = width;
  7427. screenshotCanvas.height = height;
  7428. var renderContext = screenshotCanvas.getContext("2d");
  7429. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  7430. var newWidth = width;
  7431. var newHeight = newWidth / ratio;
  7432. if (newHeight > height) {
  7433. newHeight = height;
  7434. newWidth = newHeight * ratio;
  7435. }
  7436. var offsetX = Math.max(0, width - newWidth) / 2;
  7437. var offsetY = Math.max(0, height - newHeight) / 2;
  7438. var renderingCanvas = engine.getRenderingCanvas();
  7439. if (renderContext && renderingCanvas) {
  7440. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  7441. }
  7442. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  7443. };
  7444. /**
  7445. * Generates an image screenshot from the specified camera.
  7446. *
  7447. * @param engine The engine to use for rendering
  7448. * @param camera The camera to use for rendering
  7449. * @param size This parameter can be set to a single number or to an object with the
  7450. * following (optional) properties: precision, width, height. If a single number is passed,
  7451. * it will be used for both width and height. If an object is passed, the screenshot size
  7452. * will be derived from the parameters. The precision property is a multiplier allowing
  7453. * rendering at a higher or lower resolution.
  7454. * @param successCallback The callback receives a single parameter which contains the
  7455. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  7456. * src parameter of an <img> to display it.
  7457. * @param mimeType The MIME type of the screenshot image (default: image/png).
  7458. * Check your browser for supported MIME types.
  7459. * @param samples Texture samples (default: 1)
  7460. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  7461. * @param fileName A name for for the downloaded file.
  7462. * @constructor
  7463. */
  7464. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  7465. if (mimeType === void 0) { mimeType = "image/png"; }
  7466. if (samples === void 0) { samples = 1; }
  7467. if (antialiasing === void 0) { antialiasing = false; }
  7468. var width;
  7469. var height;
  7470. //If a precision value is specified
  7471. if (size.precision) {
  7472. width = Math.round(engine.getRenderWidth() * size.precision);
  7473. height = Math.round(width / engine.getAspectRatio(camera));
  7474. size = { width: width, height: height };
  7475. }
  7476. else if (size.width && size.height) {
  7477. width = size.width;
  7478. height = size.height;
  7479. }
  7480. else if (size.width && !size.height) {
  7481. width = size.width;
  7482. height = Math.round(width / engine.getAspectRatio(camera));
  7483. size = { width: width, height: height };
  7484. }
  7485. else if (size.height && !size.width) {
  7486. height = size.height;
  7487. width = Math.round(height * engine.getAspectRatio(camera));
  7488. size = { width: width, height: height };
  7489. }
  7490. else if (!isNaN(size)) {
  7491. height = size;
  7492. width = size;
  7493. }
  7494. else {
  7495. Tools.Error("Invalid 'size' parameter !");
  7496. return;
  7497. }
  7498. var scene = camera.getScene();
  7499. var previousCamera = null;
  7500. if (scene.activeCamera !== camera) {
  7501. previousCamera = scene.activeCamera;
  7502. scene.activeCamera = camera;
  7503. }
  7504. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  7505. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  7506. texture.renderList = null;
  7507. texture.samples = samples;
  7508. if (antialiasing) {
  7509. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  7510. }
  7511. texture.onAfterRenderObservable.add(function () {
  7512. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  7513. });
  7514. scene.incrementRenderId();
  7515. scene.resetCachedMaterial();
  7516. texture.render(true);
  7517. texture.dispose();
  7518. if (previousCamera) {
  7519. scene.activeCamera = previousCamera;
  7520. }
  7521. camera.getProjectionMatrix(true); // Force cache refresh;
  7522. };
  7523. // XHR response validator for local file scenario
  7524. Tools.ValidateXHRData = function (xhr, dataType) {
  7525. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  7526. if (dataType === void 0) { dataType = 7; }
  7527. try {
  7528. if (dataType & 1) {
  7529. if (xhr.responseText && xhr.responseText.length > 0) {
  7530. return true;
  7531. }
  7532. else if (dataType === 1) {
  7533. return false;
  7534. }
  7535. }
  7536. if (dataType & 2) {
  7537. // Check header width and height since there is no "TGA" magic number
  7538. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  7539. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  7540. return true;
  7541. }
  7542. else if (dataType === 2) {
  7543. return false;
  7544. }
  7545. }
  7546. if (dataType & 4) {
  7547. // Check for the "DDS" magic number
  7548. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  7549. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  7550. return true;
  7551. }
  7552. else {
  7553. return false;
  7554. }
  7555. }
  7556. }
  7557. catch (e) {
  7558. // Global protection
  7559. }
  7560. return false;
  7561. };
  7562. /**
  7563. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  7564. * Be aware Math.random() could cause collisions, but:
  7565. * "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"
  7566. */
  7567. Tools.RandomId = function () {
  7568. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  7569. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  7570. return v.toString(16);
  7571. });
  7572. };
  7573. Object.defineProperty(Tools, "NoneLogLevel", {
  7574. get: function () {
  7575. return Tools._NoneLogLevel;
  7576. },
  7577. enumerable: true,
  7578. configurable: true
  7579. });
  7580. Object.defineProperty(Tools, "MessageLogLevel", {
  7581. get: function () {
  7582. return Tools._MessageLogLevel;
  7583. },
  7584. enumerable: true,
  7585. configurable: true
  7586. });
  7587. Object.defineProperty(Tools, "WarningLogLevel", {
  7588. get: function () {
  7589. return Tools._WarningLogLevel;
  7590. },
  7591. enumerable: true,
  7592. configurable: true
  7593. });
  7594. Object.defineProperty(Tools, "ErrorLogLevel", {
  7595. get: function () {
  7596. return Tools._ErrorLogLevel;
  7597. },
  7598. enumerable: true,
  7599. configurable: true
  7600. });
  7601. Object.defineProperty(Tools, "AllLogLevel", {
  7602. get: function () {
  7603. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  7604. },
  7605. enumerable: true,
  7606. configurable: true
  7607. });
  7608. Tools._AddLogEntry = function (entry) {
  7609. Tools._LogCache = entry + Tools._LogCache;
  7610. if (Tools.OnNewCacheEntry) {
  7611. Tools.OnNewCacheEntry(entry);
  7612. }
  7613. };
  7614. Tools._FormatMessage = function (message) {
  7615. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  7616. var date = new Date();
  7617. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  7618. };
  7619. Tools._LogDisabled = function (message) {
  7620. // nothing to do
  7621. };
  7622. Tools._LogEnabled = function (message) {
  7623. var formattedMessage = Tools._FormatMessage(message);
  7624. console.log("BJS - " + formattedMessage);
  7625. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  7626. Tools._AddLogEntry(entry);
  7627. };
  7628. Tools._WarnDisabled = function (message) {
  7629. // nothing to do
  7630. };
  7631. Tools._WarnEnabled = function (message) {
  7632. var formattedMessage = Tools._FormatMessage(message);
  7633. console.warn("BJS - " + formattedMessage);
  7634. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  7635. Tools._AddLogEntry(entry);
  7636. };
  7637. Tools._ErrorDisabled = function (message) {
  7638. // nothing to do
  7639. };
  7640. Tools._ErrorEnabled = function (message) {
  7641. Tools.errorsCount++;
  7642. var formattedMessage = Tools._FormatMessage(message);
  7643. console.error("BJS - " + formattedMessage);
  7644. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  7645. Tools._AddLogEntry(entry);
  7646. };
  7647. Object.defineProperty(Tools, "LogCache", {
  7648. get: function () {
  7649. return Tools._LogCache;
  7650. },
  7651. enumerable: true,
  7652. configurable: true
  7653. });
  7654. Tools.ClearLogCache = function () {
  7655. Tools._LogCache = "";
  7656. Tools.errorsCount = 0;
  7657. };
  7658. Object.defineProperty(Tools, "LogLevels", {
  7659. set: function (level) {
  7660. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  7661. Tools.Log = Tools._LogEnabled;
  7662. }
  7663. else {
  7664. Tools.Log = Tools._LogDisabled;
  7665. }
  7666. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  7667. Tools.Warn = Tools._WarnEnabled;
  7668. }
  7669. else {
  7670. Tools.Warn = Tools._WarnDisabled;
  7671. }
  7672. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  7673. Tools.Error = Tools._ErrorEnabled;
  7674. }
  7675. else {
  7676. Tools.Error = Tools._ErrorDisabled;
  7677. }
  7678. },
  7679. enumerable: true,
  7680. configurable: true
  7681. });
  7682. Tools.IsWindowObjectExist = function () {
  7683. return (typeof window) !== "undefined";
  7684. };
  7685. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  7686. get: function () {
  7687. return Tools._PerformanceNoneLogLevel;
  7688. },
  7689. enumerable: true,
  7690. configurable: true
  7691. });
  7692. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  7693. get: function () {
  7694. return Tools._PerformanceUserMarkLogLevel;
  7695. },
  7696. enumerable: true,
  7697. configurable: true
  7698. });
  7699. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  7700. get: function () {
  7701. return Tools._PerformanceConsoleLogLevel;
  7702. },
  7703. enumerable: true,
  7704. configurable: true
  7705. });
  7706. Object.defineProperty(Tools, "PerformanceLogLevel", {
  7707. set: function (level) {
  7708. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  7709. Tools.StartPerformanceCounter = Tools._StartUserMark;
  7710. Tools.EndPerformanceCounter = Tools._EndUserMark;
  7711. return;
  7712. }
  7713. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  7714. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  7715. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  7716. return;
  7717. }
  7718. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7719. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7720. },
  7721. enumerable: true,
  7722. configurable: true
  7723. });
  7724. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  7725. };
  7726. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  7727. };
  7728. Tools._StartUserMark = function (counterName, condition) {
  7729. if (condition === void 0) { condition = true; }
  7730. if (!Tools._performance) {
  7731. if (!Tools.IsWindowObjectExist()) {
  7732. return;
  7733. }
  7734. Tools._performance = window.performance;
  7735. }
  7736. if (!condition || !Tools._performance.mark) {
  7737. return;
  7738. }
  7739. Tools._performance.mark(counterName + "-Begin");
  7740. };
  7741. Tools._EndUserMark = function (counterName, condition) {
  7742. if (condition === void 0) { condition = true; }
  7743. if (!condition || !Tools._performance.mark) {
  7744. return;
  7745. }
  7746. Tools._performance.mark(counterName + "-End");
  7747. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  7748. };
  7749. Tools._StartPerformanceConsole = function (counterName, condition) {
  7750. if (condition === void 0) { condition = true; }
  7751. if (!condition) {
  7752. return;
  7753. }
  7754. Tools._StartUserMark(counterName, condition);
  7755. if (console.time) {
  7756. console.time(counterName);
  7757. }
  7758. };
  7759. Tools._EndPerformanceConsole = function (counterName, condition) {
  7760. if (condition === void 0) { condition = true; }
  7761. if (!condition) {
  7762. return;
  7763. }
  7764. Tools._EndUserMark(counterName, condition);
  7765. if (console.time) {
  7766. console.timeEnd(counterName);
  7767. }
  7768. };
  7769. Object.defineProperty(Tools, "Now", {
  7770. get: function () {
  7771. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  7772. return window.performance.now();
  7773. }
  7774. return new Date().getTime();
  7775. },
  7776. enumerable: true,
  7777. configurable: true
  7778. });
  7779. /**
  7780. * This method will return the name of the class used to create the instance of the given object.
  7781. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  7782. * @param object the object to get the class name from
  7783. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  7784. */
  7785. Tools.GetClassName = function (object, isType) {
  7786. if (isType === void 0) { isType = false; }
  7787. var name = null;
  7788. if (!isType && object.getClassName) {
  7789. name = object.getClassName();
  7790. }
  7791. else {
  7792. if (object instanceof Object) {
  7793. var classObj = isType ? object : Object.getPrototypeOf(object);
  7794. name = classObj.constructor["__bjsclassName__"];
  7795. }
  7796. if (!name) {
  7797. name = typeof object;
  7798. }
  7799. }
  7800. return name;
  7801. };
  7802. Tools.First = function (array, predicate) {
  7803. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  7804. var el = array_1[_i];
  7805. if (predicate(el)) {
  7806. return el;
  7807. }
  7808. }
  7809. return null;
  7810. };
  7811. /**
  7812. * This method will return the name of the full name of the class, including its owning module (if any).
  7813. * 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).
  7814. * @param object the object to get the class name from
  7815. * @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.
  7816. */
  7817. Tools.getFullClassName = function (object, isType) {
  7818. if (isType === void 0) { isType = false; }
  7819. var className = null;
  7820. var moduleName = null;
  7821. if (!isType && object.getClassName) {
  7822. className = object.getClassName();
  7823. }
  7824. else {
  7825. if (object instanceof Object) {
  7826. var classObj = isType ? object : Object.getPrototypeOf(object);
  7827. className = classObj.constructor["__bjsclassName__"];
  7828. moduleName = classObj.constructor["__bjsmoduleName__"];
  7829. }
  7830. if (!className) {
  7831. className = typeof object;
  7832. }
  7833. }
  7834. if (!className) {
  7835. return null;
  7836. }
  7837. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  7838. };
  7839. /**
  7840. * 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.
  7841. * @param array
  7842. */
  7843. Tools.arrayOrStringFeeder = function (array) {
  7844. return function (index) {
  7845. if (index >= array.length) {
  7846. return null;
  7847. }
  7848. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  7849. if (val && val.getHashCode) {
  7850. val = val.getHashCode();
  7851. }
  7852. if (typeof val === "string") {
  7853. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7854. }
  7855. return val;
  7856. };
  7857. };
  7858. /**
  7859. * Compute the hashCode of a stream of number
  7860. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7861. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7862. * @return the hash code computed
  7863. */
  7864. Tools.hashCodeFromStream = function (feeder) {
  7865. // Based from here: http://stackoverflow.com/a/7616484/802124
  7866. var hash = 0;
  7867. var index = 0;
  7868. var chr = feeder(index++);
  7869. while (chr != null) {
  7870. hash = ((hash << 5) - hash) + chr;
  7871. hash |= 0; // Convert to 32bit integer
  7872. chr = feeder(index++);
  7873. }
  7874. return hash;
  7875. };
  7876. Tools.BaseUrl = "";
  7877. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7878. /**
  7879. * Default behaviour for cors in the application.
  7880. * It can be a string if the expected behavior is identical in the entire app.
  7881. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7882. */
  7883. Tools.CorsBehavior = "anonymous";
  7884. Tools.UseFallbackTexture = true;
  7885. /**
  7886. * Use this object to register external classes like custom textures or material
  7887. * to allow the laoders to instantiate them
  7888. */
  7889. Tools.RegisteredExternalClasses = {};
  7890. // Used in case of a texture loading problem
  7891. 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";
  7892. Tools.PreprocessUrl = function (url) {
  7893. return url;
  7894. };
  7895. // Logs
  7896. Tools._NoneLogLevel = 0;
  7897. Tools._MessageLogLevel = 1;
  7898. Tools._WarningLogLevel = 2;
  7899. Tools._ErrorLogLevel = 4;
  7900. Tools._LogCache = "";
  7901. Tools.errorsCount = 0;
  7902. Tools.Log = Tools._LogEnabled;
  7903. Tools.Warn = Tools._WarnEnabled;
  7904. Tools.Error = Tools._ErrorEnabled;
  7905. // Performances
  7906. Tools._PerformanceNoneLogLevel = 0;
  7907. Tools._PerformanceUserMarkLogLevel = 1;
  7908. Tools._PerformanceConsoleLogLevel = 2;
  7909. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7910. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7911. return Tools;
  7912. }());
  7913. BABYLON.Tools = Tools;
  7914. /**
  7915. * This class is used to track a performance counter which is number based.
  7916. * The user has access to many properties which give statistics of different nature
  7917. *
  7918. * The implementer can track two kinds of Performance Counter: time and count
  7919. * 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.
  7920. * 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.
  7921. */
  7922. var PerfCounter = /** @class */ (function () {
  7923. function PerfCounter() {
  7924. this._startMonitoringTime = 0;
  7925. this._min = 0;
  7926. this._max = 0;
  7927. this._average = 0;
  7928. this._lastSecAverage = 0;
  7929. this._current = 0;
  7930. this._totalValueCount = 0;
  7931. this._totalAccumulated = 0;
  7932. this._lastSecAccumulated = 0;
  7933. this._lastSecTime = 0;
  7934. this._lastSecValueCount = 0;
  7935. }
  7936. Object.defineProperty(PerfCounter.prototype, "min", {
  7937. /**
  7938. * Returns the smallest value ever
  7939. */
  7940. get: function () {
  7941. return this._min;
  7942. },
  7943. enumerable: true,
  7944. configurable: true
  7945. });
  7946. Object.defineProperty(PerfCounter.prototype, "max", {
  7947. /**
  7948. * Returns the biggest value ever
  7949. */
  7950. get: function () {
  7951. return this._max;
  7952. },
  7953. enumerable: true,
  7954. configurable: true
  7955. });
  7956. Object.defineProperty(PerfCounter.prototype, "average", {
  7957. /**
  7958. * Returns the average value since the performance counter is running
  7959. */
  7960. get: function () {
  7961. return this._average;
  7962. },
  7963. enumerable: true,
  7964. configurable: true
  7965. });
  7966. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7967. /**
  7968. * Returns the average value of the last second the counter was monitored
  7969. */
  7970. get: function () {
  7971. return this._lastSecAverage;
  7972. },
  7973. enumerable: true,
  7974. configurable: true
  7975. });
  7976. Object.defineProperty(PerfCounter.prototype, "current", {
  7977. /**
  7978. * Returns the current value
  7979. */
  7980. get: function () {
  7981. return this._current;
  7982. },
  7983. enumerable: true,
  7984. configurable: true
  7985. });
  7986. Object.defineProperty(PerfCounter.prototype, "total", {
  7987. get: function () {
  7988. return this._totalAccumulated;
  7989. },
  7990. enumerable: true,
  7991. configurable: true
  7992. });
  7993. Object.defineProperty(PerfCounter.prototype, "count", {
  7994. get: function () {
  7995. return this._totalValueCount;
  7996. },
  7997. enumerable: true,
  7998. configurable: true
  7999. });
  8000. /**
  8001. * Call this method to start monitoring a new frame.
  8002. * 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.
  8003. */
  8004. PerfCounter.prototype.fetchNewFrame = function () {
  8005. this._totalValueCount++;
  8006. this._current = 0;
  8007. this._lastSecValueCount++;
  8008. };
  8009. /**
  8010. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  8011. * @param newCount the count value to add to the monitored count
  8012. * @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.
  8013. */
  8014. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  8015. if (!PerfCounter.Enabled) {
  8016. return;
  8017. }
  8018. this._current += newCount;
  8019. if (fetchResult) {
  8020. this._fetchResult();
  8021. }
  8022. };
  8023. /**
  8024. * Start monitoring this performance counter
  8025. */
  8026. PerfCounter.prototype.beginMonitoring = function () {
  8027. if (!PerfCounter.Enabled) {
  8028. return;
  8029. }
  8030. this._startMonitoringTime = Tools.Now;
  8031. };
  8032. /**
  8033. * Compute the time lapsed since the previous beginMonitoring() call.
  8034. * @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
  8035. */
  8036. PerfCounter.prototype.endMonitoring = function (newFrame) {
  8037. if (newFrame === void 0) { newFrame = true; }
  8038. if (!PerfCounter.Enabled) {
  8039. return;
  8040. }
  8041. if (newFrame) {
  8042. this.fetchNewFrame();
  8043. }
  8044. var currentTime = Tools.Now;
  8045. this._current = currentTime - this._startMonitoringTime;
  8046. if (newFrame) {
  8047. this._fetchResult();
  8048. }
  8049. };
  8050. PerfCounter.prototype._fetchResult = function () {
  8051. this._totalAccumulated += this._current;
  8052. this._lastSecAccumulated += this._current;
  8053. // Min/Max update
  8054. this._min = Math.min(this._min, this._current);
  8055. this._max = Math.max(this._max, this._current);
  8056. this._average = this._totalAccumulated / this._totalValueCount;
  8057. // Reset last sec?
  8058. var now = Tools.Now;
  8059. if ((now - this._lastSecTime) > 1000) {
  8060. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  8061. this._lastSecTime = now;
  8062. this._lastSecAccumulated = 0;
  8063. this._lastSecValueCount = 0;
  8064. }
  8065. };
  8066. PerfCounter.Enabled = true;
  8067. return PerfCounter;
  8068. }());
  8069. BABYLON.PerfCounter = PerfCounter;
  8070. /**
  8071. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  8072. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  8073. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  8074. * @param name The name of the class, case should be preserved
  8075. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  8076. */
  8077. function className(name, module) {
  8078. return function (target) {
  8079. target["__bjsclassName__"] = name;
  8080. target["__bjsmoduleName__"] = (module != null) ? module : null;
  8081. };
  8082. }
  8083. BABYLON.className = className;
  8084. /**
  8085. * An implementation of a loop for asynchronous functions.
  8086. */
  8087. var AsyncLoop = /** @class */ (function () {
  8088. /**
  8089. * Constroctor.
  8090. * @param iterations the number of iterations.
  8091. * @param _fn the function to run each iteration
  8092. * @param _successCallback the callback that will be called upon succesful execution
  8093. * @param offset starting offset.
  8094. */
  8095. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  8096. if (offset === void 0) { offset = 0; }
  8097. this.iterations = iterations;
  8098. this._fn = _fn;
  8099. this._successCallback = _successCallback;
  8100. this.index = offset - 1;
  8101. this._done = false;
  8102. }
  8103. /**
  8104. * Execute the next iteration. Must be called after the last iteration was finished.
  8105. */
  8106. AsyncLoop.prototype.executeNext = function () {
  8107. if (!this._done) {
  8108. if (this.index + 1 < this.iterations) {
  8109. ++this.index;
  8110. this._fn(this);
  8111. }
  8112. else {
  8113. this.breakLoop();
  8114. }
  8115. }
  8116. };
  8117. /**
  8118. * Break the loop and run the success callback.
  8119. */
  8120. AsyncLoop.prototype.breakLoop = function () {
  8121. this._done = true;
  8122. this._successCallback();
  8123. };
  8124. /**
  8125. * Helper function
  8126. */
  8127. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  8128. if (offset === void 0) { offset = 0; }
  8129. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  8130. loop.executeNext();
  8131. return loop;
  8132. };
  8133. /**
  8134. * A for-loop that will run a given number of iterations synchronous and the rest async.
  8135. * @param iterations total number of iterations
  8136. * @param syncedIterations number of synchronous iterations in each async iteration.
  8137. * @param fn the function to call each iteration.
  8138. * @param callback a success call back that will be called when iterating stops.
  8139. * @param breakFunction a break condition (optional)
  8140. * @param timeout timeout settings for the setTimeout function. default - 0.
  8141. * @constructor
  8142. */
  8143. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  8144. if (timeout === void 0) { timeout = 0; }
  8145. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  8146. if (breakFunction && breakFunction())
  8147. loop.breakLoop();
  8148. else {
  8149. setTimeout(function () {
  8150. for (var i = 0; i < syncedIterations; ++i) {
  8151. var iteration = (loop.index * syncedIterations) + i;
  8152. if (iteration >= iterations)
  8153. break;
  8154. fn(iteration);
  8155. if (breakFunction && breakFunction()) {
  8156. loop.breakLoop();
  8157. break;
  8158. }
  8159. }
  8160. loop.executeNext();
  8161. }, timeout);
  8162. }
  8163. }, callback);
  8164. };
  8165. return AsyncLoop;
  8166. }());
  8167. BABYLON.AsyncLoop = AsyncLoop;
  8168. })(BABYLON || (BABYLON = {}));
  8169. //# sourceMappingURL=babylon.tools.js.map
  8170. var BABYLON;
  8171. (function (BABYLON) {
  8172. var _AlphaState = /** @class */ (function () {
  8173. /**
  8174. * Initializes the state.
  8175. */
  8176. function _AlphaState() {
  8177. this._isAlphaBlendDirty = false;
  8178. this._isBlendFunctionParametersDirty = false;
  8179. this._isBlendEquationParametersDirty = false;
  8180. this._isBlendConstantsDirty = false;
  8181. this._alphaBlend = false;
  8182. this._blendFunctionParameters = new Array(4);
  8183. this._blendEquationParameters = new Array(2);
  8184. this._blendConstants = new Array(4);
  8185. this.reset();
  8186. }
  8187. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  8188. get: function () {
  8189. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  8190. },
  8191. enumerable: true,
  8192. configurable: true
  8193. });
  8194. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  8195. get: function () {
  8196. return this._alphaBlend;
  8197. },
  8198. set: function (value) {
  8199. if (this._alphaBlend === value) {
  8200. return;
  8201. }
  8202. this._alphaBlend = value;
  8203. this._isAlphaBlendDirty = true;
  8204. },
  8205. enumerable: true,
  8206. configurable: true
  8207. });
  8208. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  8209. if (this._blendConstants[0] === r &&
  8210. this._blendConstants[1] === g &&
  8211. this._blendConstants[2] === b &&
  8212. this._blendConstants[3] === a) {
  8213. return;
  8214. }
  8215. this._blendConstants[0] = r;
  8216. this._blendConstants[1] = g;
  8217. this._blendConstants[2] = b;
  8218. this._blendConstants[3] = a;
  8219. this._isBlendConstantsDirty = true;
  8220. };
  8221. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  8222. if (this._blendFunctionParameters[0] === value0 &&
  8223. this._blendFunctionParameters[1] === value1 &&
  8224. this._blendFunctionParameters[2] === value2 &&
  8225. this._blendFunctionParameters[3] === value3) {
  8226. return;
  8227. }
  8228. this._blendFunctionParameters[0] = value0;
  8229. this._blendFunctionParameters[1] = value1;
  8230. this._blendFunctionParameters[2] = value2;
  8231. this._blendFunctionParameters[3] = value3;
  8232. this._isBlendFunctionParametersDirty = true;
  8233. };
  8234. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  8235. if (this._blendEquationParameters[0] === rgb &&
  8236. this._blendEquationParameters[1] === alpha) {
  8237. return;
  8238. }
  8239. this._blendEquationParameters[0] = rgb;
  8240. this._blendEquationParameters[1] = alpha;
  8241. this._isBlendEquationParametersDirty = true;
  8242. };
  8243. _AlphaState.prototype.reset = function () {
  8244. this._alphaBlend = false;
  8245. this._blendFunctionParameters[0] = null;
  8246. this._blendFunctionParameters[1] = null;
  8247. this._blendFunctionParameters[2] = null;
  8248. this._blendFunctionParameters[3] = null;
  8249. this._blendEquationParameters[0] = null;
  8250. this._blendEquationParameters[1] = null;
  8251. this._blendConstants[0] = null;
  8252. this._blendConstants[1] = null;
  8253. this._blendConstants[2] = null;
  8254. this._blendConstants[3] = null;
  8255. this._isAlphaBlendDirty = true;
  8256. this._isBlendFunctionParametersDirty = false;
  8257. this._isBlendEquationParametersDirty = false;
  8258. this._isBlendConstantsDirty = false;
  8259. };
  8260. _AlphaState.prototype.apply = function (gl) {
  8261. if (!this.isDirty) {
  8262. return;
  8263. }
  8264. // Alpha blend
  8265. if (this._isAlphaBlendDirty) {
  8266. if (this._alphaBlend) {
  8267. gl.enable(gl.BLEND);
  8268. }
  8269. else {
  8270. gl.disable(gl.BLEND);
  8271. }
  8272. this._isAlphaBlendDirty = false;
  8273. }
  8274. // Alpha function
  8275. if (this._isBlendFunctionParametersDirty) {
  8276. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  8277. this._isBlendFunctionParametersDirty = false;
  8278. }
  8279. // Alpha equation
  8280. if (this._isBlendEquationParametersDirty) {
  8281. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  8282. this._isBlendEquationParametersDirty = false;
  8283. }
  8284. // Constants
  8285. if (this._isBlendConstantsDirty) {
  8286. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  8287. this._isBlendConstantsDirty = false;
  8288. }
  8289. };
  8290. return _AlphaState;
  8291. }());
  8292. BABYLON._AlphaState = _AlphaState;
  8293. })(BABYLON || (BABYLON = {}));
  8294. //# sourceMappingURL=babylon.alphaCullingState.js.map
  8295. var BABYLON;
  8296. (function (BABYLON) {
  8297. var _DepthCullingState = /** @class */ (function () {
  8298. /**
  8299. * Initializes the state.
  8300. */
  8301. function _DepthCullingState() {
  8302. this._isDepthTestDirty = false;
  8303. this._isDepthMaskDirty = false;
  8304. this._isDepthFuncDirty = false;
  8305. this._isCullFaceDirty = false;
  8306. this._isCullDirty = false;
  8307. this._isZOffsetDirty = false;
  8308. this._isFrontFaceDirty = false;
  8309. this.reset();
  8310. }
  8311. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  8312. get: function () {
  8313. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  8314. },
  8315. enumerable: true,
  8316. configurable: true
  8317. });
  8318. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  8319. get: function () {
  8320. return this._zOffset;
  8321. },
  8322. set: function (value) {
  8323. if (this._zOffset === value) {
  8324. return;
  8325. }
  8326. this._zOffset = value;
  8327. this._isZOffsetDirty = true;
  8328. },
  8329. enumerable: true,
  8330. configurable: true
  8331. });
  8332. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  8333. get: function () {
  8334. return this._cullFace;
  8335. },
  8336. set: function (value) {
  8337. if (this._cullFace === value) {
  8338. return;
  8339. }
  8340. this._cullFace = value;
  8341. this._isCullFaceDirty = true;
  8342. },
  8343. enumerable: true,
  8344. configurable: true
  8345. });
  8346. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  8347. get: function () {
  8348. return this._cull;
  8349. },
  8350. set: function (value) {
  8351. if (this._cull === value) {
  8352. return;
  8353. }
  8354. this._cull = value;
  8355. this._isCullDirty = true;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  8361. get: function () {
  8362. return this._depthFunc;
  8363. },
  8364. set: function (value) {
  8365. if (this._depthFunc === value) {
  8366. return;
  8367. }
  8368. this._depthFunc = value;
  8369. this._isDepthFuncDirty = true;
  8370. },
  8371. enumerable: true,
  8372. configurable: true
  8373. });
  8374. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  8375. get: function () {
  8376. return this._depthMask;
  8377. },
  8378. set: function (value) {
  8379. if (this._depthMask === value) {
  8380. return;
  8381. }
  8382. this._depthMask = value;
  8383. this._isDepthMaskDirty = true;
  8384. },
  8385. enumerable: true,
  8386. configurable: true
  8387. });
  8388. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  8389. get: function () {
  8390. return this._depthTest;
  8391. },
  8392. set: function (value) {
  8393. if (this._depthTest === value) {
  8394. return;
  8395. }
  8396. this._depthTest = value;
  8397. this._isDepthTestDirty = true;
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  8403. get: function () {
  8404. return this._frontFace;
  8405. },
  8406. set: function (value) {
  8407. if (this._frontFace === value) {
  8408. return;
  8409. }
  8410. this._frontFace = value;
  8411. this._isFrontFaceDirty = true;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. _DepthCullingState.prototype.reset = function () {
  8417. this._depthMask = true;
  8418. this._depthTest = true;
  8419. this._depthFunc = null;
  8420. this._cullFace = null;
  8421. this._cull = null;
  8422. this._zOffset = 0;
  8423. this._frontFace = null;
  8424. this._isDepthTestDirty = true;
  8425. this._isDepthMaskDirty = true;
  8426. this._isDepthFuncDirty = false;
  8427. this._isCullFaceDirty = false;
  8428. this._isCullDirty = false;
  8429. this._isZOffsetDirty = false;
  8430. this._isFrontFaceDirty = false;
  8431. };
  8432. _DepthCullingState.prototype.apply = function (gl) {
  8433. if (!this.isDirty) {
  8434. return;
  8435. }
  8436. // Cull
  8437. if (this._isCullDirty) {
  8438. if (this.cull) {
  8439. gl.enable(gl.CULL_FACE);
  8440. }
  8441. else {
  8442. gl.disable(gl.CULL_FACE);
  8443. }
  8444. this._isCullDirty = false;
  8445. }
  8446. // Cull face
  8447. if (this._isCullFaceDirty) {
  8448. gl.cullFace(this.cullFace);
  8449. this._isCullFaceDirty = false;
  8450. }
  8451. // Depth mask
  8452. if (this._isDepthMaskDirty) {
  8453. gl.depthMask(this.depthMask);
  8454. this._isDepthMaskDirty = false;
  8455. }
  8456. // Depth test
  8457. if (this._isDepthTestDirty) {
  8458. if (this.depthTest) {
  8459. gl.enable(gl.DEPTH_TEST);
  8460. }
  8461. else {
  8462. gl.disable(gl.DEPTH_TEST);
  8463. }
  8464. this._isDepthTestDirty = false;
  8465. }
  8466. // Depth func
  8467. if (this._isDepthFuncDirty) {
  8468. gl.depthFunc(this.depthFunc);
  8469. this._isDepthFuncDirty = false;
  8470. }
  8471. // zOffset
  8472. if (this._isZOffsetDirty) {
  8473. if (this.zOffset) {
  8474. gl.enable(gl.POLYGON_OFFSET_FILL);
  8475. gl.polygonOffset(this.zOffset, 0);
  8476. }
  8477. else {
  8478. gl.disable(gl.POLYGON_OFFSET_FILL);
  8479. }
  8480. this._isZOffsetDirty = false;
  8481. }
  8482. // Front face
  8483. if (this._isFrontFaceDirty) {
  8484. gl.frontFace(this.frontFace);
  8485. this._isFrontFaceDirty = false;
  8486. }
  8487. };
  8488. return _DepthCullingState;
  8489. }());
  8490. BABYLON._DepthCullingState = _DepthCullingState;
  8491. })(BABYLON || (BABYLON = {}));
  8492. //# sourceMappingURL=babylon.depthCullingState.js.map
  8493. var BABYLON;
  8494. (function (BABYLON) {
  8495. var _StencilState = /** @class */ (function () {
  8496. function _StencilState() {
  8497. this._isStencilTestDirty = false;
  8498. this._isStencilMaskDirty = false;
  8499. this._isStencilFuncDirty = false;
  8500. this._isStencilOpDirty = false;
  8501. this.reset();
  8502. }
  8503. Object.defineProperty(_StencilState.prototype, "isDirty", {
  8504. get: function () {
  8505. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  8506. },
  8507. enumerable: true,
  8508. configurable: true
  8509. });
  8510. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  8511. get: function () {
  8512. return this._stencilFunc;
  8513. },
  8514. set: function (value) {
  8515. if (this._stencilFunc === value) {
  8516. return;
  8517. }
  8518. this._stencilFunc = value;
  8519. this._isStencilFuncDirty = true;
  8520. },
  8521. enumerable: true,
  8522. configurable: true
  8523. });
  8524. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  8525. get: function () {
  8526. return this._stencilFuncRef;
  8527. },
  8528. set: function (value) {
  8529. if (this._stencilFuncRef === value) {
  8530. return;
  8531. }
  8532. this._stencilFuncRef = value;
  8533. this._isStencilFuncDirty = true;
  8534. },
  8535. enumerable: true,
  8536. configurable: true
  8537. });
  8538. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  8539. get: function () {
  8540. return this._stencilFuncMask;
  8541. },
  8542. set: function (value) {
  8543. if (this._stencilFuncMask === value) {
  8544. return;
  8545. }
  8546. this._stencilFuncMask = value;
  8547. this._isStencilFuncDirty = true;
  8548. },
  8549. enumerable: true,
  8550. configurable: true
  8551. });
  8552. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  8553. get: function () {
  8554. return this._stencilOpStencilFail;
  8555. },
  8556. set: function (value) {
  8557. if (this._stencilOpStencilFail === value) {
  8558. return;
  8559. }
  8560. this._stencilOpStencilFail = value;
  8561. this._isStencilOpDirty = true;
  8562. },
  8563. enumerable: true,
  8564. configurable: true
  8565. });
  8566. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  8567. get: function () {
  8568. return this._stencilOpDepthFail;
  8569. },
  8570. set: function (value) {
  8571. if (this._stencilOpDepthFail === value) {
  8572. return;
  8573. }
  8574. this._stencilOpDepthFail = value;
  8575. this._isStencilOpDirty = true;
  8576. },
  8577. enumerable: true,
  8578. configurable: true
  8579. });
  8580. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  8581. get: function () {
  8582. return this._stencilOpStencilDepthPass;
  8583. },
  8584. set: function (value) {
  8585. if (this._stencilOpStencilDepthPass === value) {
  8586. return;
  8587. }
  8588. this._stencilOpStencilDepthPass = value;
  8589. this._isStencilOpDirty = true;
  8590. },
  8591. enumerable: true,
  8592. configurable: true
  8593. });
  8594. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  8595. get: function () {
  8596. return this._stencilMask;
  8597. },
  8598. set: function (value) {
  8599. if (this._stencilMask === value) {
  8600. return;
  8601. }
  8602. this._stencilMask = value;
  8603. this._isStencilMaskDirty = true;
  8604. },
  8605. enumerable: true,
  8606. configurable: true
  8607. });
  8608. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  8609. get: function () {
  8610. return this._stencilTest;
  8611. },
  8612. set: function (value) {
  8613. if (this._stencilTest === value) {
  8614. return;
  8615. }
  8616. this._stencilTest = value;
  8617. this._isStencilTestDirty = true;
  8618. },
  8619. enumerable: true,
  8620. configurable: true
  8621. });
  8622. _StencilState.prototype.reset = function () {
  8623. this._stencilTest = false;
  8624. this._stencilMask = 0xFF;
  8625. this._stencilFunc = BABYLON.Engine.ALWAYS;
  8626. this._stencilFuncRef = 1;
  8627. this._stencilFuncMask = 0xFF;
  8628. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  8629. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  8630. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  8631. this._isStencilTestDirty = true;
  8632. this._isStencilMaskDirty = true;
  8633. this._isStencilFuncDirty = true;
  8634. this._isStencilOpDirty = true;
  8635. };
  8636. _StencilState.prototype.apply = function (gl) {
  8637. if (!this.isDirty) {
  8638. return;
  8639. }
  8640. // Stencil test
  8641. if (this._isStencilTestDirty) {
  8642. if (this.stencilTest) {
  8643. gl.enable(gl.STENCIL_TEST);
  8644. }
  8645. else {
  8646. gl.disable(gl.STENCIL_TEST);
  8647. }
  8648. this._isStencilTestDirty = false;
  8649. }
  8650. // Stencil mask
  8651. if (this._isStencilMaskDirty) {
  8652. gl.stencilMask(this.stencilMask);
  8653. this._isStencilMaskDirty = false;
  8654. }
  8655. // Stencil func
  8656. if (this._isStencilFuncDirty) {
  8657. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  8658. this._isStencilFuncDirty = false;
  8659. }
  8660. // Stencil op
  8661. if (this._isStencilOpDirty) {
  8662. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  8663. this._isStencilOpDirty = false;
  8664. }
  8665. };
  8666. return _StencilState;
  8667. }());
  8668. BABYLON._StencilState = _StencilState;
  8669. })(BABYLON || (BABYLON = {}));
  8670. //# sourceMappingURL=babylon.stencilState.js.map
  8671. var BABYLON;
  8672. (function (BABYLON) {
  8673. var compileShader = function (gl, source, type, defines, shaderVersion) {
  8674. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  8675. };
  8676. var compileRawShader = function (gl, source, type) {
  8677. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  8678. gl.shaderSource(shader, source);
  8679. gl.compileShader(shader);
  8680. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  8681. var log = gl.getShaderInfoLog(shader);
  8682. if (log) {
  8683. throw new Error(log);
  8684. }
  8685. }
  8686. if (!shader) {
  8687. throw new Error("Something went wrong while compile the shader.");
  8688. }
  8689. return shader;
  8690. };
  8691. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  8692. var magFilter = gl.NEAREST;
  8693. var minFilter = gl.NEAREST;
  8694. switch (samplingMode) {
  8695. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  8696. magFilter = gl.LINEAR;
  8697. if (generateMipMaps) {
  8698. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8699. }
  8700. else {
  8701. minFilter = gl.LINEAR;
  8702. }
  8703. break;
  8704. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  8705. magFilter = gl.LINEAR;
  8706. if (generateMipMaps) {
  8707. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8708. }
  8709. else {
  8710. minFilter = gl.LINEAR;
  8711. }
  8712. break;
  8713. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  8714. magFilter = gl.NEAREST;
  8715. if (generateMipMaps) {
  8716. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8717. }
  8718. else {
  8719. minFilter = gl.NEAREST;
  8720. }
  8721. break;
  8722. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  8723. magFilter = gl.NEAREST;
  8724. if (generateMipMaps) {
  8725. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8726. }
  8727. else {
  8728. minFilter = gl.NEAREST;
  8729. }
  8730. break;
  8731. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  8732. magFilter = gl.NEAREST;
  8733. if (generateMipMaps) {
  8734. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  8735. }
  8736. else {
  8737. minFilter = gl.LINEAR;
  8738. }
  8739. break;
  8740. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  8741. magFilter = gl.NEAREST;
  8742. if (generateMipMaps) {
  8743. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  8744. }
  8745. else {
  8746. minFilter = gl.LINEAR;
  8747. }
  8748. break;
  8749. case BABYLON.Texture.NEAREST_LINEAR:
  8750. magFilter = gl.NEAREST;
  8751. minFilter = gl.LINEAR;
  8752. break;
  8753. case BABYLON.Texture.NEAREST_NEAREST:
  8754. magFilter = gl.NEAREST;
  8755. minFilter = gl.NEAREST;
  8756. break;
  8757. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  8758. magFilter = gl.LINEAR;
  8759. if (generateMipMaps) {
  8760. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  8761. }
  8762. else {
  8763. minFilter = gl.NEAREST;
  8764. }
  8765. break;
  8766. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  8767. magFilter = gl.LINEAR;
  8768. if (generateMipMaps) {
  8769. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  8770. }
  8771. else {
  8772. minFilter = gl.NEAREST;
  8773. }
  8774. break;
  8775. case BABYLON.Texture.LINEAR_LINEAR:
  8776. magFilter = gl.LINEAR;
  8777. minFilter = gl.LINEAR;
  8778. break;
  8779. case BABYLON.Texture.LINEAR_NEAREST:
  8780. magFilter = gl.LINEAR;
  8781. minFilter = gl.NEAREST;
  8782. break;
  8783. }
  8784. return {
  8785. min: minFilter,
  8786. mag: magFilter
  8787. };
  8788. };
  8789. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  8790. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  8791. var img;
  8792. var onload = function () {
  8793. loadedImages[index] = img;
  8794. loadedImages._internalCount++;
  8795. if (scene) {
  8796. scene._removePendingData(img);
  8797. }
  8798. if (loadedImages._internalCount === 6) {
  8799. onfinish(loadedImages);
  8800. }
  8801. };
  8802. var onerror = function (message, exception) {
  8803. if (scene) {
  8804. scene._removePendingData(img);
  8805. }
  8806. if (onErrorCallBack) {
  8807. onErrorCallBack(message, exception);
  8808. }
  8809. };
  8810. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  8811. if (scene) {
  8812. scene._addPendingData(img);
  8813. }
  8814. };
  8815. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  8816. if (onError === void 0) { onError = null; }
  8817. var loadedImages = [];
  8818. loadedImages._internalCount = 0;
  8819. for (var index = 0; index < 6; index++) {
  8820. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  8821. }
  8822. };
  8823. var BufferPointer = /** @class */ (function () {
  8824. function BufferPointer() {
  8825. }
  8826. return BufferPointer;
  8827. }());
  8828. var InstancingAttributeInfo = /** @class */ (function () {
  8829. function InstancingAttributeInfo() {
  8830. }
  8831. return InstancingAttributeInfo;
  8832. }());
  8833. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  8834. /**
  8835. * Define options used to create a render target texture
  8836. */
  8837. var RenderTargetCreationOptions = /** @class */ (function () {
  8838. function RenderTargetCreationOptions() {
  8839. }
  8840. return RenderTargetCreationOptions;
  8841. }());
  8842. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  8843. /**
  8844. * Regroup several parameters relative to the browser in use
  8845. */
  8846. var EngineCapabilities = /** @class */ (function () {
  8847. function EngineCapabilities() {
  8848. }
  8849. return EngineCapabilities;
  8850. }());
  8851. BABYLON.EngineCapabilities = EngineCapabilities;
  8852. /**
  8853. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8854. */
  8855. var Engine = /** @class */ (function () {
  8856. /**
  8857. * @constructor
  8858. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  8859. * @param antialias defines enable antialiasing (default: false)
  8860. * @param options defines further options to be sent to the getContext() function
  8861. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  8862. */
  8863. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8864. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8865. var _this = this;
  8866. // Public members
  8867. this.forcePOTTextures = false;
  8868. this.isFullscreen = false;
  8869. this.isPointerLock = false;
  8870. this.cullBackFaces = true;
  8871. this.renderEvenInBackground = true;
  8872. this.preventCacheWipeBetweenFrames = false;
  8873. // To enable/disable IDB support and avoid XHR on .manifest
  8874. this.enableOfflineSupport = false;
  8875. this.scenes = new Array();
  8876. this.postProcesses = new Array();
  8877. // Observables
  8878. /**
  8879. * Observable event triggered each time the rendering canvas is resized
  8880. */
  8881. this.onResizeObservable = new BABYLON.Observable();
  8882. /**
  8883. * Observable event triggered each time the canvas loses focus
  8884. */
  8885. this.onCanvasBlurObservable = new BABYLON.Observable();
  8886. /**
  8887. * Observable event triggered each time the canvas gains focus
  8888. */
  8889. this.onCanvasFocusObservable = new BABYLON.Observable();
  8890. /**
  8891. * Observable event triggered each time the canvas receives pointerout event
  8892. */
  8893. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8894. /**
  8895. * Observable event triggered before each texture is initialized
  8896. */
  8897. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8898. //WebVR
  8899. this._vrDisplay = undefined;
  8900. this._vrSupported = false;
  8901. this._vrExclusivePointerMode = false;
  8902. // Uniform buffers list
  8903. this.disableUniformBuffers = false;
  8904. this._uniformBuffers = new Array();
  8905. // Observables
  8906. /**
  8907. * Observable raised when the engine begins a new frame
  8908. */
  8909. this.onBeginFrameObservable = new BABYLON.Observable();
  8910. /**
  8911. * Observable raised when the engine ends the current frame
  8912. */
  8913. this.onEndFrameObservable = new BABYLON.Observable();
  8914. /**
  8915. * Observable raised when the engine is about to compile a shader
  8916. */
  8917. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8918. /**
  8919. * Observable raised when the engine has jsut compiled a shader
  8920. */
  8921. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8922. this._windowIsBackground = false;
  8923. this._webGLVersion = 1.0;
  8924. this._badOS = false;
  8925. this._badDesktopOS = false;
  8926. /**
  8927. * Gets or sets a value indicating if we want to disable texture binding optmization.
  8928. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  8929. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  8930. */
  8931. this.disableTextureBindingOptimization = false;
  8932. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8933. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8934. this.onVRRequestPresentStart = new BABYLON.Observable();
  8935. this._colorWrite = true;
  8936. this._drawCalls = new BABYLON.PerfCounter();
  8937. this._textureCollisions = new BABYLON.PerfCounter();
  8938. this._renderingQueueLaunched = false;
  8939. this._activeRenderLoops = new Array();
  8940. // Deterministic lockstepMaxSteps
  8941. this._deterministicLockstep = false;
  8942. this._lockstepMaxSteps = 4;
  8943. // Lost context
  8944. this.onContextLostObservable = new BABYLON.Observable();
  8945. this.onContextRestoredObservable = new BABYLON.Observable();
  8946. this._contextWasLost = false;
  8947. this._doNotHandleContextLost = false;
  8948. // FPS
  8949. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8950. this._fps = 60;
  8951. this._deltaTime = 0;
  8952. /**
  8953. * Turn this value on if you want to pause FPS computation when in background
  8954. */
  8955. this.disablePerformanceMonitorInBackground = false;
  8956. // States
  8957. this._depthCullingState = new BABYLON._DepthCullingState();
  8958. this._stencilState = new BABYLON._StencilState();
  8959. this._alphaState = new BABYLON._AlphaState();
  8960. this._alphaMode = Engine.ALPHA_DISABLE;
  8961. // Cache
  8962. this._internalTexturesCache = new Array();
  8963. this._activeChannel = 0;
  8964. this._currentTextureChannel = -1;
  8965. this._boundTexturesCache = {};
  8966. this._boundTexturesStack = new Array();
  8967. this._compiledEffects = {};
  8968. this._vertexAttribArraysEnabled = [];
  8969. this._uintIndicesCurrentlySet = false;
  8970. this._currentBoundBuffer = new Array();
  8971. this._currentBufferPointers = new Array();
  8972. this._currentInstanceLocations = new Array();
  8973. this._currentInstanceBuffers = new Array();
  8974. this._vaoRecordInProgress = false;
  8975. this._mustWipeVertexAttributes = false;
  8976. this._nextFreeTextureSlots = new Array();
  8977. this._maxSimultaneousTextures = 0;
  8978. this._activeRequests = new Array();
  8979. // Hardware supported Compressed Textures
  8980. this._texturesSupported = new Array();
  8981. this._onVRFullScreenTriggered = function () {
  8982. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8983. //get the old size before we change
  8984. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8985. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8986. //get the width and height, change the render size
  8987. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8988. _this.setHardwareScalingLevel(1);
  8989. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8990. }
  8991. else {
  8992. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8993. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8994. }
  8995. };
  8996. this._boundUniforms = {};
  8997. var canvas = null;
  8998. Engine.Instances.push(this);
  8999. if (!canvasOrContext) {
  9000. return;
  9001. }
  9002. options = options || {};
  9003. if (canvasOrContext.getContext) {
  9004. canvas = canvasOrContext;
  9005. this._renderingCanvas = canvas;
  9006. if (antialias != null) {
  9007. options.antialias = antialias;
  9008. }
  9009. if (options.deterministicLockstep === undefined) {
  9010. options.deterministicLockstep = false;
  9011. }
  9012. if (options.lockstepMaxSteps === undefined) {
  9013. options.lockstepMaxSteps = 4;
  9014. }
  9015. if (options.preserveDrawingBuffer === undefined) {
  9016. options.preserveDrawingBuffer = false;
  9017. }
  9018. if (options.audioEngine === undefined) {
  9019. options.audioEngine = true;
  9020. }
  9021. if (options.stencil === undefined) {
  9022. options.stencil = true;
  9023. }
  9024. this._deterministicLockstep = options.deterministicLockstep;
  9025. this._lockstepMaxSteps = options.lockstepMaxSteps;
  9026. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  9027. // Exceptions
  9028. if (navigator && navigator.userAgent) {
  9029. var ua = navigator.userAgent;
  9030. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  9031. var exception = _a[_i];
  9032. var key = exception.key;
  9033. var targets = exception.targets;
  9034. if (ua.indexOf(key) > -1) {
  9035. if (exception.capture && exception.captureConstraint) {
  9036. var capture = exception.capture;
  9037. var constraint = exception.captureConstraint;
  9038. var regex = new RegExp(capture);
  9039. var matches = regex.exec(ua);
  9040. if (matches && matches.length > 0) {
  9041. var capturedValue = parseInt(matches[matches.length - 1]);
  9042. if (capturedValue >= constraint) {
  9043. continue;
  9044. }
  9045. }
  9046. }
  9047. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  9048. var target = targets_1[_b];
  9049. switch (target) {
  9050. case "uniformBuffer":
  9051. this.disableUniformBuffers = true;
  9052. break;
  9053. case "textureBindingOptimization":
  9054. this.disableTextureBindingOptimization = true;
  9055. break;
  9056. }
  9057. }
  9058. break;
  9059. }
  9060. }
  9061. }
  9062. // GL
  9063. if (!options.disableWebGL2Support) {
  9064. try {
  9065. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  9066. if (this._gl) {
  9067. this._webGLVersion = 2.0;
  9068. }
  9069. }
  9070. catch (e) {
  9071. // Do nothing
  9072. }
  9073. }
  9074. if (!this._gl) {
  9075. if (!canvas) {
  9076. throw new Error("The provided canvas is null or undefined.");
  9077. }
  9078. try {
  9079. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  9080. }
  9081. catch (e) {
  9082. throw new Error("WebGL not supported");
  9083. }
  9084. }
  9085. if (!this._gl) {
  9086. throw new Error("WebGL not supported");
  9087. }
  9088. this._onCanvasFocus = function () {
  9089. _this.onCanvasFocusObservable.notifyObservers(_this);
  9090. };
  9091. this._onCanvasBlur = function () {
  9092. _this.onCanvasBlurObservable.notifyObservers(_this);
  9093. };
  9094. canvas.addEventListener("focus", this._onCanvasFocus);
  9095. canvas.addEventListener("blur", this._onCanvasBlur);
  9096. this._onBlur = function () {
  9097. if (_this.disablePerformanceMonitorInBackground) {
  9098. _this._performanceMonitor.disable();
  9099. }
  9100. _this._windowIsBackground = true;
  9101. };
  9102. this._onFocus = function () {
  9103. if (_this.disablePerformanceMonitorInBackground) {
  9104. _this._performanceMonitor.enable();
  9105. }
  9106. _this._windowIsBackground = false;
  9107. };
  9108. this._onCanvasPointerOut = function () {
  9109. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  9110. };
  9111. window.addEventListener("blur", this._onBlur);
  9112. window.addEventListener("focus", this._onFocus);
  9113. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  9114. // Context lost
  9115. if (!this._doNotHandleContextLost) {
  9116. this._onContextLost = function (evt) {
  9117. evt.preventDefault();
  9118. _this._contextWasLost = true;
  9119. BABYLON.Tools.Warn("WebGL context lost.");
  9120. _this.onContextLostObservable.notifyObservers(_this);
  9121. };
  9122. this._onContextRestored = function (evt) {
  9123. // Adding a timeout to avoid race condition at browser level
  9124. setTimeout(function () {
  9125. // Rebuild gl context
  9126. _this._initGLContext();
  9127. // Rebuild effects
  9128. _this._rebuildEffects();
  9129. // Rebuild textures
  9130. _this._rebuildInternalTextures();
  9131. // Rebuild buffers
  9132. _this._rebuildBuffers();
  9133. // Cache
  9134. _this.wipeCaches(true);
  9135. BABYLON.Tools.Warn("WebGL context successfully restored.");
  9136. _this.onContextRestoredObservable.notifyObservers(_this);
  9137. _this._contextWasLost = false;
  9138. }, 0);
  9139. };
  9140. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  9141. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  9142. }
  9143. }
  9144. else {
  9145. this._gl = canvasOrContext;
  9146. this._renderingCanvas = this._gl.canvas;
  9147. if (this._gl.renderbufferStorageMultisample) {
  9148. this._webGLVersion = 2.0;
  9149. }
  9150. options.stencil = this._gl.getContextAttributes().stencil;
  9151. }
  9152. // Viewport
  9153. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  9154. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  9155. this.resize();
  9156. this._isStencilEnable = options.stencil ? true : false;
  9157. this._initGLContext();
  9158. if (canvas) {
  9159. // Fullscreen
  9160. this._onFullscreenChange = function () {
  9161. if (document.fullscreen !== undefined) {
  9162. _this.isFullscreen = document.fullscreen;
  9163. }
  9164. else if (document.mozFullScreen !== undefined) {
  9165. _this.isFullscreen = document.mozFullScreen;
  9166. }
  9167. else if (document.webkitIsFullScreen !== undefined) {
  9168. _this.isFullscreen = document.webkitIsFullScreen;
  9169. }
  9170. else if (document.msIsFullScreen !== undefined) {
  9171. _this.isFullscreen = document.msIsFullScreen;
  9172. }
  9173. // Pointer lock
  9174. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  9175. canvas.requestPointerLock = canvas.requestPointerLock ||
  9176. canvas.msRequestPointerLock ||
  9177. canvas.mozRequestPointerLock ||
  9178. canvas.webkitRequestPointerLock;
  9179. if (canvas.requestPointerLock) {
  9180. canvas.requestPointerLock();
  9181. }
  9182. }
  9183. };
  9184. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  9185. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  9186. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  9187. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  9188. // Pointer lock
  9189. this._onPointerLockChange = function () {
  9190. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  9191. document.webkitPointerLockElement === canvas ||
  9192. document.msPointerLockElement === canvas ||
  9193. document.pointerLockElement === canvas);
  9194. };
  9195. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  9196. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  9197. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  9198. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  9199. this._onVRDisplayPointerRestricted = function () {
  9200. if (canvas) {
  9201. canvas.requestPointerLock();
  9202. }
  9203. };
  9204. this._onVRDisplayPointerUnrestricted = function () {
  9205. document.exitPointerLock();
  9206. };
  9207. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  9208. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  9209. }
  9210. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  9211. Engine.audioEngine = new BABYLON.AudioEngine();
  9212. }
  9213. // Prepare buffer pointers
  9214. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9215. this._currentBufferPointers[i] = new BufferPointer();
  9216. }
  9217. // Load WebVR Devices
  9218. if (options.autoEnableWebVR) {
  9219. this.initWebVR();
  9220. }
  9221. // Detect if we are running on a faulty buggy OS.
  9222. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  9223. // Detect if we are running on a faulty buggy desktop OS.
  9224. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  9225. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  9226. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  9227. }
  9228. Object.defineProperty(Engine, "LastCreatedEngine", {
  9229. get: function () {
  9230. if (Engine.Instances.length === 0) {
  9231. return null;
  9232. }
  9233. return Engine.Instances[Engine.Instances.length - 1];
  9234. },
  9235. enumerable: true,
  9236. configurable: true
  9237. });
  9238. Object.defineProperty(Engine, "LastCreatedScene", {
  9239. get: function () {
  9240. var lastCreatedEngine = Engine.LastCreatedEngine;
  9241. if (!lastCreatedEngine) {
  9242. return null;
  9243. }
  9244. if (lastCreatedEngine.scenes.length === 0) {
  9245. return null;
  9246. }
  9247. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  9248. },
  9249. enumerable: true,
  9250. configurable: true
  9251. });
  9252. /**
  9253. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  9254. */
  9255. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  9256. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  9257. var engine = Engine.Instances[engineIndex];
  9258. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  9259. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  9260. }
  9261. }
  9262. };
  9263. Object.defineProperty(Engine, "NEVER", {
  9264. get: function () {
  9265. return Engine._NEVER;
  9266. },
  9267. enumerable: true,
  9268. configurable: true
  9269. });
  9270. Object.defineProperty(Engine, "ALWAYS", {
  9271. get: function () {
  9272. return Engine._ALWAYS;
  9273. },
  9274. enumerable: true,
  9275. configurable: true
  9276. });
  9277. Object.defineProperty(Engine, "LESS", {
  9278. get: function () {
  9279. return Engine._LESS;
  9280. },
  9281. enumerable: true,
  9282. configurable: true
  9283. });
  9284. Object.defineProperty(Engine, "EQUAL", {
  9285. get: function () {
  9286. return Engine._EQUAL;
  9287. },
  9288. enumerable: true,
  9289. configurable: true
  9290. });
  9291. Object.defineProperty(Engine, "LEQUAL", {
  9292. get: function () {
  9293. return Engine._LEQUAL;
  9294. },
  9295. enumerable: true,
  9296. configurable: true
  9297. });
  9298. Object.defineProperty(Engine, "GREATER", {
  9299. get: function () {
  9300. return Engine._GREATER;
  9301. },
  9302. enumerable: true,
  9303. configurable: true
  9304. });
  9305. Object.defineProperty(Engine, "GEQUAL", {
  9306. get: function () {
  9307. return Engine._GEQUAL;
  9308. },
  9309. enumerable: true,
  9310. configurable: true
  9311. });
  9312. Object.defineProperty(Engine, "NOTEQUAL", {
  9313. get: function () {
  9314. return Engine._NOTEQUAL;
  9315. },
  9316. enumerable: true,
  9317. configurable: true
  9318. });
  9319. Object.defineProperty(Engine, "KEEP", {
  9320. get: function () {
  9321. return Engine._KEEP;
  9322. },
  9323. enumerable: true,
  9324. configurable: true
  9325. });
  9326. Object.defineProperty(Engine, "REPLACE", {
  9327. get: function () {
  9328. return Engine._REPLACE;
  9329. },
  9330. enumerable: true,
  9331. configurable: true
  9332. });
  9333. Object.defineProperty(Engine, "INCR", {
  9334. get: function () {
  9335. return Engine._INCR;
  9336. },
  9337. enumerable: true,
  9338. configurable: true
  9339. });
  9340. Object.defineProperty(Engine, "DECR", {
  9341. get: function () {
  9342. return Engine._DECR;
  9343. },
  9344. enumerable: true,
  9345. configurable: true
  9346. });
  9347. Object.defineProperty(Engine, "INVERT", {
  9348. get: function () {
  9349. return Engine._INVERT;
  9350. },
  9351. enumerable: true,
  9352. configurable: true
  9353. });
  9354. Object.defineProperty(Engine, "INCR_WRAP", {
  9355. get: function () {
  9356. return Engine._INCR_WRAP;
  9357. },
  9358. enumerable: true,
  9359. configurable: true
  9360. });
  9361. Object.defineProperty(Engine, "DECR_WRAP", {
  9362. get: function () {
  9363. return Engine._DECR_WRAP;
  9364. },
  9365. enumerable: true,
  9366. configurable: true
  9367. });
  9368. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  9369. get: function () {
  9370. return Engine._ALPHA_DISABLE;
  9371. },
  9372. enumerable: true,
  9373. configurable: true
  9374. });
  9375. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  9376. get: function () {
  9377. return Engine._ALPHA_ONEONE;
  9378. },
  9379. enumerable: true,
  9380. configurable: true
  9381. });
  9382. Object.defineProperty(Engine, "ALPHA_ADD", {
  9383. get: function () {
  9384. return Engine._ALPHA_ADD;
  9385. },
  9386. enumerable: true,
  9387. configurable: true
  9388. });
  9389. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  9390. get: function () {
  9391. return Engine._ALPHA_COMBINE;
  9392. },
  9393. enumerable: true,
  9394. configurable: true
  9395. });
  9396. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  9397. get: function () {
  9398. return Engine._ALPHA_SUBTRACT;
  9399. },
  9400. enumerable: true,
  9401. configurable: true
  9402. });
  9403. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  9404. get: function () {
  9405. return Engine._ALPHA_MULTIPLY;
  9406. },
  9407. enumerable: true,
  9408. configurable: true
  9409. });
  9410. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  9411. get: function () {
  9412. return Engine._ALPHA_MAXIMIZED;
  9413. },
  9414. enumerable: true,
  9415. configurable: true
  9416. });
  9417. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  9418. get: function () {
  9419. return Engine._ALPHA_PREMULTIPLIED;
  9420. },
  9421. enumerable: true,
  9422. configurable: true
  9423. });
  9424. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  9425. get: function () {
  9426. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  9427. },
  9428. enumerable: true,
  9429. configurable: true
  9430. });
  9431. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  9432. get: function () {
  9433. return Engine._ALPHA_INTERPOLATE;
  9434. },
  9435. enumerable: true,
  9436. configurable: true
  9437. });
  9438. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  9439. get: function () {
  9440. return Engine._ALPHA_SCREENMODE;
  9441. },
  9442. enumerable: true,
  9443. configurable: true
  9444. });
  9445. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  9446. get: function () {
  9447. return Engine._DELAYLOADSTATE_NONE;
  9448. },
  9449. enumerable: true,
  9450. configurable: true
  9451. });
  9452. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  9453. get: function () {
  9454. return Engine._DELAYLOADSTATE_LOADED;
  9455. },
  9456. enumerable: true,
  9457. configurable: true
  9458. });
  9459. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  9460. get: function () {
  9461. return Engine._DELAYLOADSTATE_LOADING;
  9462. },
  9463. enumerable: true,
  9464. configurable: true
  9465. });
  9466. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  9467. get: function () {
  9468. return Engine._DELAYLOADSTATE_NOTLOADED;
  9469. },
  9470. enumerable: true,
  9471. configurable: true
  9472. });
  9473. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  9474. get: function () {
  9475. return Engine._TEXTUREFORMAT_ALPHA;
  9476. },
  9477. enumerable: true,
  9478. configurable: true
  9479. });
  9480. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  9481. get: function () {
  9482. return Engine._TEXTUREFORMAT_LUMINANCE;
  9483. },
  9484. enumerable: true,
  9485. configurable: true
  9486. });
  9487. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  9488. get: function () {
  9489. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  9490. },
  9491. enumerable: true,
  9492. configurable: true
  9493. });
  9494. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  9495. get: function () {
  9496. return Engine._TEXTUREFORMAT_RGB;
  9497. },
  9498. enumerable: true,
  9499. configurable: true
  9500. });
  9501. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  9502. get: function () {
  9503. return Engine._TEXTUREFORMAT_RGBA;
  9504. },
  9505. enumerable: true,
  9506. configurable: true
  9507. });
  9508. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  9509. get: function () {
  9510. return Engine._TEXTURETYPE_UNSIGNED_INT;
  9511. },
  9512. enumerable: true,
  9513. configurable: true
  9514. });
  9515. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  9516. get: function () {
  9517. return Engine._TEXTURETYPE_FLOAT;
  9518. },
  9519. enumerable: true,
  9520. configurable: true
  9521. });
  9522. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  9523. get: function () {
  9524. return Engine._TEXTURETYPE_HALF_FLOAT;
  9525. },
  9526. enumerable: true,
  9527. configurable: true
  9528. });
  9529. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  9530. get: function () {
  9531. return Engine._SCALEMODE_FLOOR;
  9532. },
  9533. enumerable: true,
  9534. configurable: true
  9535. });
  9536. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  9537. get: function () {
  9538. return Engine._SCALEMODE_NEAREST;
  9539. },
  9540. enumerable: true,
  9541. configurable: true
  9542. });
  9543. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  9544. get: function () {
  9545. return Engine._SCALEMODE_CEILING;
  9546. },
  9547. enumerable: true,
  9548. configurable: true
  9549. });
  9550. Object.defineProperty(Engine, "Version", {
  9551. get: function () {
  9552. return "3.2.0-alpha4";
  9553. },
  9554. enumerable: true,
  9555. configurable: true
  9556. });
  9557. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  9558. get: function () {
  9559. return this._vrExclusivePointerMode;
  9560. },
  9561. enumerable: true,
  9562. configurable: true
  9563. });
  9564. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  9565. get: function () {
  9566. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  9567. },
  9568. enumerable: true,
  9569. configurable: true
  9570. });
  9571. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  9572. get: function () {
  9573. return this._webGLVersion < 2 || this.forcePOTTextures;
  9574. },
  9575. enumerable: true,
  9576. configurable: true
  9577. });
  9578. Object.defineProperty(Engine.prototype, "badOS", {
  9579. get: function () {
  9580. return this._badOS;
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  9586. get: function () {
  9587. return this._badDesktopOS;
  9588. },
  9589. enumerable: true,
  9590. configurable: true
  9591. });
  9592. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  9593. get: function () {
  9594. return this._performanceMonitor;
  9595. },
  9596. enumerable: true,
  9597. configurable: true
  9598. });
  9599. Object.defineProperty(Engine.prototype, "texturesSupported", {
  9600. get: function () {
  9601. return this._texturesSupported;
  9602. },
  9603. enumerable: true,
  9604. configurable: true
  9605. });
  9606. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  9607. get: function () {
  9608. return this._textureFormatInUse;
  9609. },
  9610. enumerable: true,
  9611. configurable: true
  9612. });
  9613. Object.defineProperty(Engine.prototype, "currentViewport", {
  9614. get: function () {
  9615. return this._cachedViewport;
  9616. },
  9617. enumerable: true,
  9618. configurable: true
  9619. });
  9620. Object.defineProperty(Engine.prototype, "emptyTexture", {
  9621. // Empty texture
  9622. get: function () {
  9623. if (!this._emptyTexture) {
  9624. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9625. }
  9626. return this._emptyTexture;
  9627. },
  9628. enumerable: true,
  9629. configurable: true
  9630. });
  9631. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  9632. get: function () {
  9633. if (!this._emptyTexture3D) {
  9634. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9635. }
  9636. return this._emptyTexture3D;
  9637. },
  9638. enumerable: true,
  9639. configurable: true
  9640. });
  9641. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  9642. get: function () {
  9643. if (!this._emptyCubeTexture) {
  9644. var faceData = new Uint8Array(4);
  9645. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  9646. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9647. }
  9648. return this._emptyCubeTexture;
  9649. },
  9650. enumerable: true,
  9651. configurable: true
  9652. });
  9653. Engine.prototype._rebuildInternalTextures = function () {
  9654. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  9655. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  9656. var internalTexture = currentState_1[_i];
  9657. internalTexture._rebuild();
  9658. }
  9659. };
  9660. Engine.prototype._rebuildEffects = function () {
  9661. for (var key in this._compiledEffects) {
  9662. var effect = this._compiledEffects[key];
  9663. effect._prepareEffect();
  9664. }
  9665. BABYLON.Effect.ResetCache();
  9666. };
  9667. Engine.prototype._rebuildBuffers = function () {
  9668. // Index / Vertex
  9669. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  9670. var scene = _a[_i];
  9671. scene.resetCachedMaterial();
  9672. scene._rebuildGeometries();
  9673. scene._rebuildTextures();
  9674. }
  9675. // Uniforms
  9676. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  9677. var uniformBuffer = _c[_b];
  9678. uniformBuffer._rebuild();
  9679. }
  9680. };
  9681. Engine.prototype._initGLContext = function () {
  9682. // Caps
  9683. this._caps = new EngineCapabilities();
  9684. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  9685. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  9686. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  9687. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  9688. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  9689. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  9690. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  9691. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  9692. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  9693. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  9694. // Infos
  9695. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  9696. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  9697. if (rendererInfo != null) {
  9698. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  9699. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  9700. }
  9701. if (!this._glVendor) {
  9702. this._glVendor = "Unknown vendor";
  9703. }
  9704. if (!this._glRenderer) {
  9705. this._glRenderer = "Unknown renderer";
  9706. }
  9707. // Constants
  9708. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9709. if (this._gl.RGBA16F !== 0x881A) {
  9710. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9711. }
  9712. if (this._gl.RGBA32F !== 0x8814) {
  9713. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9714. }
  9715. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  9716. this._gl.DEPTH24_STENCIL8 = 35056;
  9717. }
  9718. // Extensions
  9719. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  9720. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  9721. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  9722. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  9723. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  9724. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  9725. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  9726. 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');
  9727. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  9728. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  9729. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  9730. this._caps.highPrecisionShaderSupported = true;
  9731. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  9732. if (this._caps.timerQuery) {
  9733. if (this._webGLVersion === 1) {
  9734. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  9735. }
  9736. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  9737. }
  9738. // Checks if some of the format renders first to allow the use of webgl inspector.
  9739. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  9740. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  9741. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  9742. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  9743. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  9744. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  9745. if (this._webGLVersion > 1) {
  9746. this._gl.HALF_FLOAT_OES = 0x140B;
  9747. }
  9748. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  9749. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  9750. // Draw buffers
  9751. if (this._webGLVersion > 1) {
  9752. this._caps.drawBuffersExtension = true;
  9753. }
  9754. else {
  9755. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  9756. if (drawBuffersExtension !== null) {
  9757. this._caps.drawBuffersExtension = true;
  9758. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  9759. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  9760. for (var i = 0; i < 16; i++) {
  9761. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  9762. }
  9763. }
  9764. else {
  9765. this._caps.drawBuffersExtension = false;
  9766. }
  9767. }
  9768. // Depth Texture
  9769. if (this._webGLVersion > 1) {
  9770. this._caps.depthTextureExtension = true;
  9771. }
  9772. else {
  9773. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  9774. if (depthTextureExtension != null) {
  9775. this._caps.depthTextureExtension = true;
  9776. }
  9777. }
  9778. // Vertex array object
  9779. if (this._webGLVersion > 1) {
  9780. this._caps.vertexArrayObject = true;
  9781. }
  9782. else {
  9783. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  9784. if (vertexArrayObjectExtension != null) {
  9785. this._caps.vertexArrayObject = true;
  9786. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  9787. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  9788. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  9789. }
  9790. else {
  9791. this._caps.vertexArrayObject = false;
  9792. }
  9793. }
  9794. // Instances count
  9795. if (this._webGLVersion > 1) {
  9796. this._caps.instancedArrays = true;
  9797. }
  9798. else {
  9799. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  9800. if (instanceExtension != null) {
  9801. this._caps.instancedArrays = true;
  9802. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  9803. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  9804. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  9805. }
  9806. else {
  9807. this._caps.instancedArrays = false;
  9808. }
  9809. }
  9810. // Intelligently add supported compressed formats in order to check for.
  9811. // Check for ASTC support first as it is most powerful and to be very cross platform.
  9812. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  9813. // Likely no hardware which supports both PVR & DXT, so order matters little.
  9814. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  9815. if (this._caps.astc)
  9816. this.texturesSupported.push('-astc.ktx');
  9817. if (this._caps.s3tc)
  9818. this.texturesSupported.push('-dxt.ktx');
  9819. if (this._caps.pvrtc)
  9820. this.texturesSupported.push('-pvrtc.ktx');
  9821. if (this._caps.etc2)
  9822. this.texturesSupported.push('-etc2.ktx');
  9823. if (this._caps.etc1)
  9824. this.texturesSupported.push('-etc1.ktx');
  9825. if (this._gl.getShaderPrecisionFormat) {
  9826. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  9827. if (highp) {
  9828. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  9829. }
  9830. }
  9831. // Depth buffer
  9832. this.setDepthBuffer(true);
  9833. this.setDepthFunctionToLessOrEqual();
  9834. this.setDepthWrite(true);
  9835. // Texture maps
  9836. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  9837. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9838. this._nextFreeTextureSlots.push(slot);
  9839. }
  9840. };
  9841. Object.defineProperty(Engine.prototype, "webGLVersion", {
  9842. get: function () {
  9843. return this._webGLVersion;
  9844. },
  9845. enumerable: true,
  9846. configurable: true
  9847. });
  9848. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  9849. /**
  9850. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  9851. */
  9852. get: function () {
  9853. return this._isStencilEnable;
  9854. },
  9855. enumerable: true,
  9856. configurable: true
  9857. });
  9858. Engine.prototype._prepareWorkingCanvas = function () {
  9859. if (this._workingCanvas) {
  9860. return;
  9861. }
  9862. this._workingCanvas = document.createElement("canvas");
  9863. var context = this._workingCanvas.getContext("2d");
  9864. if (context) {
  9865. this._workingContext = context;
  9866. }
  9867. };
  9868. Engine.prototype.resetTextureCache = function () {
  9869. for (var key in this._boundTexturesCache) {
  9870. var boundTexture = this._boundTexturesCache[key];
  9871. if (boundTexture) {
  9872. this._removeDesignatedSlot(boundTexture);
  9873. }
  9874. this._boundTexturesCache[key] = null;
  9875. }
  9876. this._nextFreeTextureSlots = [];
  9877. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  9878. this._nextFreeTextureSlots.push(slot);
  9879. }
  9880. this._currentTextureChannel = -1;
  9881. };
  9882. Engine.prototype.isDeterministicLockStep = function () {
  9883. return this._deterministicLockstep;
  9884. };
  9885. Engine.prototype.getLockstepMaxSteps = function () {
  9886. return this._lockstepMaxSteps;
  9887. };
  9888. Engine.prototype.getGlInfo = function () {
  9889. return {
  9890. vendor: this._glVendor,
  9891. renderer: this._glRenderer,
  9892. version: this._glVersion
  9893. };
  9894. };
  9895. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9896. if (useScreen === void 0) { useScreen = false; }
  9897. var viewport = camera.viewport;
  9898. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9899. };
  9900. Engine.prototype.getRenderWidth = function (useScreen) {
  9901. if (useScreen === void 0) { useScreen = false; }
  9902. if (!useScreen && this._currentRenderTarget) {
  9903. return this._currentRenderTarget.width;
  9904. }
  9905. return this._gl.drawingBufferWidth;
  9906. };
  9907. Engine.prototype.getRenderHeight = function (useScreen) {
  9908. if (useScreen === void 0) { useScreen = false; }
  9909. if (!useScreen && this._currentRenderTarget) {
  9910. return this._currentRenderTarget.height;
  9911. }
  9912. return this._gl.drawingBufferHeight;
  9913. };
  9914. Engine.prototype.getRenderingCanvas = function () {
  9915. return this._renderingCanvas;
  9916. };
  9917. Engine.prototype.getRenderingCanvasClientRect = function () {
  9918. if (!this._renderingCanvas) {
  9919. return null;
  9920. }
  9921. return this._renderingCanvas.getBoundingClientRect();
  9922. };
  9923. Engine.prototype.setHardwareScalingLevel = function (level) {
  9924. this._hardwareScalingLevel = level;
  9925. this.resize();
  9926. };
  9927. Engine.prototype.getHardwareScalingLevel = function () {
  9928. return this._hardwareScalingLevel;
  9929. };
  9930. Engine.prototype.getLoadedTexturesCache = function () {
  9931. return this._internalTexturesCache;
  9932. };
  9933. Engine.prototype.getCaps = function () {
  9934. return this._caps;
  9935. };
  9936. Object.defineProperty(Engine.prototype, "drawCalls", {
  9937. /** The number of draw calls submitted last frame */
  9938. get: function () {
  9939. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9940. return 0;
  9941. },
  9942. enumerable: true,
  9943. configurable: true
  9944. });
  9945. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9946. get: function () {
  9947. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9948. return null;
  9949. },
  9950. enumerable: true,
  9951. configurable: true
  9952. });
  9953. Engine.prototype.getDepthFunction = function () {
  9954. return this._depthCullingState.depthFunc;
  9955. };
  9956. Engine.prototype.setDepthFunction = function (depthFunc) {
  9957. this._depthCullingState.depthFunc = depthFunc;
  9958. };
  9959. Engine.prototype.setDepthFunctionToGreater = function () {
  9960. this._depthCullingState.depthFunc = this._gl.GREATER;
  9961. };
  9962. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9963. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9964. };
  9965. Engine.prototype.setDepthFunctionToLess = function () {
  9966. this._depthCullingState.depthFunc = this._gl.LESS;
  9967. };
  9968. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9969. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9970. };
  9971. Engine.prototype.getStencilBuffer = function () {
  9972. return this._stencilState.stencilTest;
  9973. };
  9974. Engine.prototype.setStencilBuffer = function (enable) {
  9975. this._stencilState.stencilTest = enable;
  9976. };
  9977. Engine.prototype.getStencilMask = function () {
  9978. return this._stencilState.stencilMask;
  9979. };
  9980. Engine.prototype.setStencilMask = function (mask) {
  9981. this._stencilState.stencilMask = mask;
  9982. };
  9983. Engine.prototype.getStencilFunction = function () {
  9984. return this._stencilState.stencilFunc;
  9985. };
  9986. Engine.prototype.getStencilFunctionReference = function () {
  9987. return this._stencilState.stencilFuncRef;
  9988. };
  9989. Engine.prototype.getStencilFunctionMask = function () {
  9990. return this._stencilState.stencilFuncMask;
  9991. };
  9992. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9993. this._stencilState.stencilFunc = stencilFunc;
  9994. };
  9995. Engine.prototype.setStencilFunctionReference = function (reference) {
  9996. this._stencilState.stencilFuncRef = reference;
  9997. };
  9998. Engine.prototype.setStencilFunctionMask = function (mask) {
  9999. this._stencilState.stencilFuncMask = mask;
  10000. };
  10001. Engine.prototype.getStencilOperationFail = function () {
  10002. return this._stencilState.stencilOpStencilFail;
  10003. };
  10004. Engine.prototype.getStencilOperationDepthFail = function () {
  10005. return this._stencilState.stencilOpDepthFail;
  10006. };
  10007. Engine.prototype.getStencilOperationPass = function () {
  10008. return this._stencilState.stencilOpStencilDepthPass;
  10009. };
  10010. Engine.prototype.setStencilOperationFail = function (operation) {
  10011. this._stencilState.stencilOpStencilFail = operation;
  10012. };
  10013. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  10014. this._stencilState.stencilOpDepthFail = operation;
  10015. };
  10016. Engine.prototype.setStencilOperationPass = function (operation) {
  10017. this._stencilState.stencilOpStencilDepthPass = operation;
  10018. };
  10019. Engine.prototype.setDitheringState = function (value) {
  10020. if (value) {
  10021. this._gl.enable(this._gl.DITHER);
  10022. }
  10023. else {
  10024. this._gl.disable(this._gl.DITHER);
  10025. }
  10026. };
  10027. Engine.prototype.setRasterizerState = function (value) {
  10028. if (value) {
  10029. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  10030. }
  10031. else {
  10032. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  10033. }
  10034. };
  10035. /**
  10036. * stop executing a render loop function and remove it from the execution array
  10037. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  10038. */
  10039. Engine.prototype.stopRenderLoop = function (renderFunction) {
  10040. if (!renderFunction) {
  10041. this._activeRenderLoops = [];
  10042. return;
  10043. }
  10044. var index = this._activeRenderLoops.indexOf(renderFunction);
  10045. if (index >= 0) {
  10046. this._activeRenderLoops.splice(index, 1);
  10047. }
  10048. };
  10049. Engine.prototype._renderLoop = function () {
  10050. if (!this._contextWasLost) {
  10051. var shouldRender = true;
  10052. if (!this.renderEvenInBackground && this._windowIsBackground) {
  10053. shouldRender = false;
  10054. }
  10055. if (shouldRender) {
  10056. // Start new frame
  10057. this.beginFrame();
  10058. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  10059. var renderFunction = this._activeRenderLoops[index];
  10060. renderFunction();
  10061. }
  10062. // Present
  10063. this.endFrame();
  10064. }
  10065. }
  10066. if (this._activeRenderLoops.length > 0) {
  10067. // Register new frame
  10068. var requester = null;
  10069. if (this._vrDisplay && this._vrDisplay.isPresenting)
  10070. requester = this._vrDisplay;
  10071. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  10072. }
  10073. else {
  10074. this._renderingQueueLaunched = false;
  10075. }
  10076. };
  10077. /**
  10078. * Register and execute a render loop. The engine can have more than one render function.
  10079. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  10080. * @example
  10081. * engine.runRenderLoop(function () {
  10082. * scene.render()
  10083. * })
  10084. */
  10085. Engine.prototype.runRenderLoop = function (renderFunction) {
  10086. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  10087. return;
  10088. }
  10089. this._activeRenderLoops.push(renderFunction);
  10090. if (!this._renderingQueueLaunched) {
  10091. this._renderingQueueLaunched = true;
  10092. this._bindedRenderFunction = this._renderLoop.bind(this);
  10093. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  10094. }
  10095. };
  10096. /**
  10097. * Toggle full screen mode.
  10098. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  10099. * @param {any} options - an options object to be sent to the requestFullscreen function
  10100. */
  10101. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  10102. if (this.isFullscreen) {
  10103. BABYLON.Tools.ExitFullscreen();
  10104. }
  10105. else {
  10106. this._pointerLockRequested = requestPointerLock;
  10107. if (this._renderingCanvas) {
  10108. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  10109. }
  10110. }
  10111. };
  10112. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  10113. if (stencil === void 0) { stencil = false; }
  10114. this.applyStates();
  10115. var mode = 0;
  10116. if (backBuffer && color) {
  10117. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  10118. mode |= this._gl.COLOR_BUFFER_BIT;
  10119. }
  10120. if (depth) {
  10121. this._gl.clearDepth(1.0);
  10122. mode |= this._gl.DEPTH_BUFFER_BIT;
  10123. }
  10124. if (stencil) {
  10125. this._gl.clearStencil(0);
  10126. mode |= this._gl.STENCIL_BUFFER_BIT;
  10127. }
  10128. this._gl.clear(mode);
  10129. };
  10130. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  10131. var gl = this._gl;
  10132. // Save state
  10133. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  10134. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  10135. // Change state
  10136. gl.enable(gl.SCISSOR_TEST);
  10137. gl.scissor(x, y, width, height);
  10138. // Clear
  10139. this.clear(clearColor, true, true, true);
  10140. // Restore state
  10141. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  10142. if (curScissor === true) {
  10143. gl.enable(gl.SCISSOR_TEST);
  10144. }
  10145. else {
  10146. gl.disable(gl.SCISSOR_TEST);
  10147. }
  10148. };
  10149. /**
  10150. * Set the WebGL's viewport
  10151. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  10152. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  10153. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  10154. */
  10155. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  10156. var width = requiredWidth || this.getRenderWidth();
  10157. var height = requiredHeight || this.getRenderHeight();
  10158. var x = viewport.x || 0;
  10159. var y = viewport.y || 0;
  10160. this._cachedViewport = viewport;
  10161. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  10162. };
  10163. /**
  10164. * Directly set the WebGL Viewport
  10165. * The x, y, width & height are directly passed to the WebGL call
  10166. * @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.
  10167. */
  10168. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  10169. var currentViewport = this._cachedViewport;
  10170. this._cachedViewport = null;
  10171. this._gl.viewport(x, y, width, height);
  10172. return currentViewport;
  10173. };
  10174. Engine.prototype.beginFrame = function () {
  10175. this.onBeginFrameObservable.notifyObservers(this);
  10176. this._measureFps();
  10177. };
  10178. Engine.prototype.endFrame = function () {
  10179. //force a flush in case we are using a bad OS.
  10180. if (this._badOS) {
  10181. this.flushFramebuffer();
  10182. }
  10183. //submit frame to the vr device, if enabled
  10184. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10185. // TODO: We should only submit the frame if we read frameData successfully.
  10186. this._vrDisplay.submitFrame();
  10187. }
  10188. this.onEndFrameObservable.notifyObservers(this);
  10189. };
  10190. /**
  10191. * resize the view according to the canvas' size.
  10192. * @example
  10193. * window.addEventListener("resize", function () {
  10194. * engine.resize();
  10195. * });
  10196. */
  10197. Engine.prototype.resize = function () {
  10198. // We're not resizing the size of the canvas while in VR mode & presenting
  10199. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  10200. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  10201. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  10202. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  10203. }
  10204. };
  10205. /**
  10206. * force a specific size of the canvas
  10207. * @param {number} width - the new canvas' width
  10208. * @param {number} height - the new canvas' height
  10209. */
  10210. Engine.prototype.setSize = function (width, height) {
  10211. if (!this._renderingCanvas) {
  10212. return;
  10213. }
  10214. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  10215. return;
  10216. }
  10217. this._renderingCanvas.width = width;
  10218. this._renderingCanvas.height = height;
  10219. for (var index = 0; index < this.scenes.length; index++) {
  10220. var scene = this.scenes[index];
  10221. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  10222. var cam = scene.cameras[camIndex];
  10223. cam._currentRenderId = 0;
  10224. }
  10225. }
  10226. if (this.onResizeObservable.hasObservers) {
  10227. this.onResizeObservable.notifyObservers(this);
  10228. }
  10229. };
  10230. // WebVR functions
  10231. Engine.prototype.isVRDevicePresent = function () {
  10232. return !!this._vrDisplay;
  10233. };
  10234. Engine.prototype.getVRDevice = function () {
  10235. return this._vrDisplay;
  10236. };
  10237. Engine.prototype.initWebVR = function () {
  10238. var _this = this;
  10239. var notifyObservers = function () {
  10240. var eventArgs = {
  10241. vrDisplay: _this._vrDisplay,
  10242. vrSupported: _this._vrSupported
  10243. };
  10244. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  10245. };
  10246. if (!this._onVrDisplayConnect) {
  10247. this._onVrDisplayConnect = function (event) {
  10248. _this._vrDisplay = event.display;
  10249. notifyObservers();
  10250. };
  10251. this._onVrDisplayDisconnect = function () {
  10252. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  10253. _this._vrDisplay = undefined;
  10254. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  10255. notifyObservers();
  10256. };
  10257. this._onVrDisplayPresentChange = function () {
  10258. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  10259. };
  10260. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  10261. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  10262. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  10263. }
  10264. this._getVRDisplays(notifyObservers);
  10265. return this.onVRDisplayChangedObservable;
  10266. };
  10267. Engine.prototype.enableVR = function () {
  10268. var _this = this;
  10269. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  10270. var onResolved = function () {
  10271. _this.onVRRequestPresentComplete.notifyObservers(true);
  10272. _this._onVRFullScreenTriggered();
  10273. };
  10274. var onRejected = function () {
  10275. _this.onVRRequestPresentComplete.notifyObservers(false);
  10276. };
  10277. this.onVRRequestPresentStart.notifyObservers(this);
  10278. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  10279. }
  10280. };
  10281. Engine.prototype.disableVR = function () {
  10282. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  10283. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  10284. }
  10285. };
  10286. Engine.prototype._getVRDisplays = function (callback) {
  10287. var _this = this;
  10288. var getWebVRDevices = function (devices) {
  10289. _this._vrSupported = true;
  10290. // note that devices may actually be an empty array. This is fine;
  10291. // we expect this._vrDisplay to be undefined in this case.
  10292. return _this._vrDisplay = devices[0];
  10293. };
  10294. if (navigator.getVRDisplays) {
  10295. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  10296. // TODO: System CANNOT support WebVR, despite API presence.
  10297. _this._vrSupported = false;
  10298. callback();
  10299. });
  10300. }
  10301. else {
  10302. // TODO: Browser does not support WebVR
  10303. this._vrDisplay = undefined;
  10304. this._vrSupported = false;
  10305. callback();
  10306. }
  10307. };
  10308. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  10309. if (this._currentRenderTarget) {
  10310. this.unBindFramebuffer(this._currentRenderTarget);
  10311. }
  10312. this._currentRenderTarget = texture;
  10313. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  10314. var gl = this._gl;
  10315. if (texture.isCube) {
  10316. if (faceIndex === undefined) {
  10317. faceIndex = 0;
  10318. }
  10319. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10320. }
  10321. if (this._cachedViewport && !forceFullscreenViewport) {
  10322. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  10323. }
  10324. else {
  10325. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  10326. }
  10327. this.wipeCaches();
  10328. };
  10329. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  10330. if (this._currentFramebuffer !== framebuffer) {
  10331. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  10332. this._currentFramebuffer = framebuffer;
  10333. }
  10334. };
  10335. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  10336. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10337. this._currentRenderTarget = null;
  10338. // If MSAA, we need to bitblt back to main texture
  10339. var gl = this._gl;
  10340. if (texture._MSAAFramebuffer) {
  10341. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  10342. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  10343. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10344. }
  10345. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10346. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10347. gl.generateMipmap(gl.TEXTURE_2D);
  10348. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10349. }
  10350. if (onBeforeUnbind) {
  10351. if (texture._MSAAFramebuffer) {
  10352. // Bind the correct framebuffer
  10353. this.bindUnboundFramebuffer(texture._framebuffer);
  10354. }
  10355. onBeforeUnbind();
  10356. }
  10357. this.bindUnboundFramebuffer(null);
  10358. };
  10359. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  10360. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  10361. this._currentRenderTarget = null;
  10362. // If MSAA, we need to bitblt back to main texture
  10363. var gl = this._gl;
  10364. if (textures[0]._MSAAFramebuffer) {
  10365. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  10366. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  10367. var attachments = textures[0]._attachments;
  10368. if (!attachments) {
  10369. attachments = new Array(textures.length);
  10370. textures[0]._attachments = attachments;
  10371. }
  10372. for (var i = 0; i < textures.length; i++) {
  10373. var texture = textures[i];
  10374. for (var j = 0; j < attachments.length; j++) {
  10375. attachments[j] = gl.NONE;
  10376. }
  10377. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10378. gl.readBuffer(attachments[i]);
  10379. gl.drawBuffers(attachments);
  10380. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  10381. }
  10382. for (var i = 0; i < attachments.length; i++) {
  10383. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10384. }
  10385. gl.drawBuffers(attachments);
  10386. }
  10387. for (var i = 0; i < textures.length; i++) {
  10388. var texture = textures[i];
  10389. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  10390. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10391. gl.generateMipmap(gl.TEXTURE_2D);
  10392. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10393. }
  10394. }
  10395. if (onBeforeUnbind) {
  10396. if (textures[0]._MSAAFramebuffer) {
  10397. // Bind the correct framebuffer
  10398. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  10399. }
  10400. onBeforeUnbind();
  10401. }
  10402. this.bindUnboundFramebuffer(null);
  10403. };
  10404. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  10405. if (texture.generateMipMaps) {
  10406. var gl = this._gl;
  10407. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  10408. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10409. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10410. }
  10411. };
  10412. Engine.prototype.flushFramebuffer = function () {
  10413. this._gl.flush();
  10414. };
  10415. Engine.prototype.restoreDefaultFramebuffer = function () {
  10416. if (this._currentRenderTarget) {
  10417. this.unBindFramebuffer(this._currentRenderTarget);
  10418. }
  10419. else {
  10420. this.bindUnboundFramebuffer(null);
  10421. }
  10422. if (this._cachedViewport) {
  10423. this.setViewport(this._cachedViewport);
  10424. }
  10425. this.wipeCaches();
  10426. };
  10427. // UBOs
  10428. Engine.prototype.createUniformBuffer = function (elements) {
  10429. var ubo = this._gl.createBuffer();
  10430. if (!ubo) {
  10431. throw new Error("Unable to create uniform buffer");
  10432. }
  10433. this.bindUniformBuffer(ubo);
  10434. if (elements instanceof Float32Array) {
  10435. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  10436. }
  10437. else {
  10438. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  10439. }
  10440. this.bindUniformBuffer(null);
  10441. ubo.references = 1;
  10442. return ubo;
  10443. };
  10444. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  10445. var ubo = this._gl.createBuffer();
  10446. if (!ubo) {
  10447. throw new Error("Unable to create dynamic uniform buffer");
  10448. }
  10449. this.bindUniformBuffer(ubo);
  10450. if (elements instanceof Float32Array) {
  10451. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  10452. }
  10453. else {
  10454. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  10455. }
  10456. this.bindUniformBuffer(null);
  10457. ubo.references = 1;
  10458. return ubo;
  10459. };
  10460. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  10461. this.bindUniformBuffer(uniformBuffer);
  10462. if (offset === undefined) {
  10463. offset = 0;
  10464. }
  10465. if (count === undefined) {
  10466. if (elements instanceof Float32Array) {
  10467. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  10468. }
  10469. else {
  10470. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  10471. }
  10472. }
  10473. else {
  10474. if (elements instanceof Float32Array) {
  10475. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  10476. }
  10477. else {
  10478. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  10479. }
  10480. }
  10481. this.bindUniformBuffer(null);
  10482. };
  10483. // VBOs
  10484. Engine.prototype._resetVertexBufferBinding = function () {
  10485. this.bindArrayBuffer(null);
  10486. this._cachedVertexBuffers = null;
  10487. };
  10488. Engine.prototype.createVertexBuffer = function (vertices) {
  10489. var vbo = this._gl.createBuffer();
  10490. if (!vbo) {
  10491. throw new Error("Unable to create vertex buffer");
  10492. }
  10493. this.bindArrayBuffer(vbo);
  10494. if (vertices instanceof Float32Array) {
  10495. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  10496. }
  10497. else {
  10498. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  10499. }
  10500. this._resetVertexBufferBinding();
  10501. vbo.references = 1;
  10502. return vbo;
  10503. };
  10504. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  10505. var vbo = this._gl.createBuffer();
  10506. if (!vbo) {
  10507. throw new Error("Unable to create dynamic vertex buffer");
  10508. }
  10509. this.bindArrayBuffer(vbo);
  10510. if (vertices instanceof Float32Array) {
  10511. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  10512. }
  10513. else {
  10514. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  10515. }
  10516. this._resetVertexBufferBinding();
  10517. vbo.references = 1;
  10518. return vbo;
  10519. };
  10520. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  10521. if (offset === void 0) { offset = 0; }
  10522. // Force cache update
  10523. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  10524. this.bindIndexBuffer(indexBuffer);
  10525. var arrayBuffer;
  10526. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  10527. arrayBuffer = indices;
  10528. }
  10529. else {
  10530. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10531. }
  10532. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  10533. this._resetIndexBufferBinding();
  10534. };
  10535. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  10536. this.bindArrayBuffer(vertexBuffer);
  10537. if (offset === undefined) {
  10538. offset = 0;
  10539. }
  10540. if (count === undefined) {
  10541. if (vertices instanceof Float32Array) {
  10542. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  10543. }
  10544. else {
  10545. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  10546. }
  10547. }
  10548. else {
  10549. if (vertices instanceof Float32Array) {
  10550. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  10551. }
  10552. else {
  10553. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  10554. }
  10555. }
  10556. this._resetVertexBufferBinding();
  10557. };
  10558. Engine.prototype._resetIndexBufferBinding = function () {
  10559. this.bindIndexBuffer(null);
  10560. this._cachedIndexBuffer = null;
  10561. };
  10562. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  10563. var vbo = this._gl.createBuffer();
  10564. if (!vbo) {
  10565. throw new Error("Unable to create index buffer");
  10566. }
  10567. this.bindIndexBuffer(vbo);
  10568. // Check for 32 bits indices
  10569. var arrayBuffer;
  10570. var need32Bits = false;
  10571. if (indices instanceof Uint16Array) {
  10572. arrayBuffer = indices;
  10573. }
  10574. else {
  10575. //check 32 bit support
  10576. if (this._caps.uintIndices) {
  10577. if (indices instanceof Uint32Array) {
  10578. arrayBuffer = indices;
  10579. need32Bits = true;
  10580. }
  10581. else {
  10582. //number[] or Int32Array, check if 32 bit is necessary
  10583. for (var index = 0; index < indices.length; index++) {
  10584. if (indices[index] > 65535) {
  10585. need32Bits = true;
  10586. break;
  10587. }
  10588. }
  10589. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  10590. }
  10591. }
  10592. else {
  10593. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  10594. arrayBuffer = new Uint16Array(indices);
  10595. }
  10596. }
  10597. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  10598. this._resetIndexBufferBinding();
  10599. vbo.references = 1;
  10600. vbo.is32Bits = need32Bits;
  10601. return vbo;
  10602. };
  10603. Engine.prototype.bindArrayBuffer = function (buffer) {
  10604. if (!this._vaoRecordInProgress) {
  10605. this._unbindVertexArrayObject();
  10606. }
  10607. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  10608. };
  10609. Engine.prototype.bindUniformBuffer = function (buffer) {
  10610. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  10611. };
  10612. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  10613. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  10614. };
  10615. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  10616. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  10617. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  10618. };
  10619. ;
  10620. Engine.prototype.bindIndexBuffer = function (buffer) {
  10621. if (!this._vaoRecordInProgress) {
  10622. this._unbindVertexArrayObject();
  10623. }
  10624. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  10625. };
  10626. Engine.prototype.bindBuffer = function (buffer, target) {
  10627. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  10628. this._gl.bindBuffer(target, buffer);
  10629. this._currentBoundBuffer[target] = buffer;
  10630. }
  10631. };
  10632. Engine.prototype.updateArrayBuffer = function (data) {
  10633. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10634. };
  10635. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  10636. var pointer = this._currentBufferPointers[indx];
  10637. var changed = false;
  10638. if (!pointer.active) {
  10639. changed = true;
  10640. pointer.active = true;
  10641. pointer.index = indx;
  10642. pointer.size = size;
  10643. pointer.type = type;
  10644. pointer.normalized = normalized;
  10645. pointer.stride = stride;
  10646. pointer.offset = offset;
  10647. pointer.buffer = buffer;
  10648. }
  10649. else {
  10650. if (pointer.buffer !== buffer) {
  10651. pointer.buffer = buffer;
  10652. changed = true;
  10653. }
  10654. if (pointer.size !== size) {
  10655. pointer.size = size;
  10656. changed = true;
  10657. }
  10658. if (pointer.type !== type) {
  10659. pointer.type = type;
  10660. changed = true;
  10661. }
  10662. if (pointer.normalized !== normalized) {
  10663. pointer.normalized = normalized;
  10664. changed = true;
  10665. }
  10666. if (pointer.stride !== stride) {
  10667. pointer.stride = stride;
  10668. changed = true;
  10669. }
  10670. if (pointer.offset !== offset) {
  10671. pointer.offset = offset;
  10672. changed = true;
  10673. }
  10674. }
  10675. if (changed || this._vaoRecordInProgress) {
  10676. this.bindArrayBuffer(buffer);
  10677. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  10678. }
  10679. };
  10680. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  10681. if (indexBuffer == null) {
  10682. return;
  10683. }
  10684. if (this._cachedIndexBuffer !== indexBuffer) {
  10685. this._cachedIndexBuffer = indexBuffer;
  10686. this.bindIndexBuffer(indexBuffer);
  10687. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  10688. }
  10689. };
  10690. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  10691. var attributes = effect.getAttributesNames();
  10692. if (!this._vaoRecordInProgress) {
  10693. this._unbindVertexArrayObject();
  10694. }
  10695. this.unbindAllAttributes();
  10696. for (var index = 0; index < attributes.length; index++) {
  10697. var order = effect.getAttributeLocation(index);
  10698. if (order >= 0) {
  10699. var vertexBuffer = vertexBuffers[attributes[index]];
  10700. if (!vertexBuffer) {
  10701. continue;
  10702. }
  10703. this._gl.enableVertexAttribArray(order);
  10704. if (!this._vaoRecordInProgress) {
  10705. this._vertexAttribArraysEnabled[order] = true;
  10706. }
  10707. var buffer = vertexBuffer.getBuffer();
  10708. if (buffer) {
  10709. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  10710. if (vertexBuffer.getIsInstanced()) {
  10711. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  10712. if (!this._vaoRecordInProgress) {
  10713. this._currentInstanceLocations.push(order);
  10714. this._currentInstanceBuffers.push(buffer);
  10715. }
  10716. }
  10717. }
  10718. }
  10719. }
  10720. };
  10721. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  10722. var vao = this._gl.createVertexArray();
  10723. this._vaoRecordInProgress = true;
  10724. this._gl.bindVertexArray(vao);
  10725. this._mustWipeVertexAttributes = true;
  10726. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10727. this.bindIndexBuffer(indexBuffer);
  10728. this._vaoRecordInProgress = false;
  10729. this._gl.bindVertexArray(null);
  10730. return vao;
  10731. };
  10732. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  10733. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  10734. this._cachedVertexArrayObject = vertexArrayObject;
  10735. this._gl.bindVertexArray(vertexArrayObject);
  10736. this._cachedVertexBuffers = null;
  10737. this._cachedIndexBuffer = null;
  10738. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  10739. this._mustWipeVertexAttributes = true;
  10740. }
  10741. };
  10742. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  10743. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  10744. this._cachedVertexBuffers = vertexBuffer;
  10745. this._cachedEffectForVertexBuffers = effect;
  10746. var attributesCount = effect.getAttributesCount();
  10747. this._unbindVertexArrayObject();
  10748. this.unbindAllAttributes();
  10749. var offset = 0;
  10750. for (var index = 0; index < attributesCount; index++) {
  10751. if (index < vertexDeclaration.length) {
  10752. var order = effect.getAttributeLocation(index);
  10753. if (order >= 0) {
  10754. this._gl.enableVertexAttribArray(order);
  10755. this._vertexAttribArraysEnabled[order] = true;
  10756. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  10757. }
  10758. offset += vertexDeclaration[index] * 4;
  10759. }
  10760. }
  10761. }
  10762. this._bindIndexBufferWithCache(indexBuffer);
  10763. };
  10764. Engine.prototype._unbindVertexArrayObject = function () {
  10765. if (!this._cachedVertexArrayObject) {
  10766. return;
  10767. }
  10768. this._cachedVertexArrayObject = null;
  10769. this._gl.bindVertexArray(null);
  10770. };
  10771. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  10772. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  10773. this._cachedVertexBuffers = vertexBuffers;
  10774. this._cachedEffectForVertexBuffers = effect;
  10775. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  10776. }
  10777. this._bindIndexBufferWithCache(indexBuffer);
  10778. };
  10779. Engine.prototype.unbindInstanceAttributes = function () {
  10780. var boundBuffer;
  10781. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  10782. var instancesBuffer = this._currentInstanceBuffers[i];
  10783. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  10784. boundBuffer = instancesBuffer;
  10785. this.bindArrayBuffer(instancesBuffer);
  10786. }
  10787. var offsetLocation = this._currentInstanceLocations[i];
  10788. this._gl.vertexAttribDivisor(offsetLocation, 0);
  10789. }
  10790. this._currentInstanceBuffers.length = 0;
  10791. this._currentInstanceLocations.length = 0;
  10792. };
  10793. Engine.prototype.releaseVertexArrayObject = function (vao) {
  10794. this._gl.deleteVertexArray(vao);
  10795. };
  10796. Engine.prototype._releaseBuffer = function (buffer) {
  10797. buffer.references--;
  10798. if (buffer.references === 0) {
  10799. this._gl.deleteBuffer(buffer);
  10800. return true;
  10801. }
  10802. return false;
  10803. };
  10804. Engine.prototype.createInstancesBuffer = function (capacity) {
  10805. var buffer = this._gl.createBuffer();
  10806. if (!buffer) {
  10807. throw new Error("Unable to create instance buffer");
  10808. }
  10809. buffer.capacity = capacity;
  10810. this.bindArrayBuffer(buffer);
  10811. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  10812. return buffer;
  10813. };
  10814. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  10815. this._gl.deleteBuffer(buffer);
  10816. };
  10817. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  10818. this.bindArrayBuffer(instancesBuffer);
  10819. if (data) {
  10820. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  10821. }
  10822. if (offsetLocations[0].index !== undefined) {
  10823. var stride = 0;
  10824. for (var i = 0; i < offsetLocations.length; i++) {
  10825. var ai = offsetLocations[i];
  10826. stride += ai.attributeSize * 4;
  10827. }
  10828. for (var i = 0; i < offsetLocations.length; i++) {
  10829. var ai = offsetLocations[i];
  10830. if (!this._vertexAttribArraysEnabled[ai.index]) {
  10831. this._gl.enableVertexAttribArray(ai.index);
  10832. this._vertexAttribArraysEnabled[ai.index] = true;
  10833. }
  10834. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  10835. this._gl.vertexAttribDivisor(ai.index, 1);
  10836. this._currentInstanceLocations.push(ai.index);
  10837. this._currentInstanceBuffers.push(instancesBuffer);
  10838. }
  10839. }
  10840. else {
  10841. for (var index = 0; index < 4; index++) {
  10842. var offsetLocation = offsetLocations[index];
  10843. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  10844. this._gl.enableVertexAttribArray(offsetLocation);
  10845. this._vertexAttribArraysEnabled[offsetLocation] = true;
  10846. }
  10847. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  10848. this._gl.vertexAttribDivisor(offsetLocation, 1);
  10849. this._currentInstanceLocations.push(offsetLocation);
  10850. this._currentInstanceBuffers.push(instancesBuffer);
  10851. }
  10852. }
  10853. };
  10854. Engine.prototype.applyStates = function () {
  10855. this._depthCullingState.apply(this._gl);
  10856. this._stencilState.apply(this._gl);
  10857. this._alphaState.apply(this._gl);
  10858. };
  10859. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  10860. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  10861. };
  10862. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  10863. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  10864. };
  10865. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  10866. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  10867. };
  10868. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  10869. // Apply states
  10870. this.applyStates();
  10871. this._drawCalls.addCount(1, false);
  10872. // Render
  10873. var drawMode = this.DrawMode(fillMode);
  10874. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  10875. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10876. if (instancesCount) {
  10877. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10878. }
  10879. else {
  10880. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10881. }
  10882. };
  10883. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10884. // Apply states
  10885. this.applyStates();
  10886. this._drawCalls.addCount(1, false);
  10887. var drawMode = this.DrawMode(fillMode);
  10888. if (instancesCount) {
  10889. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10890. }
  10891. else {
  10892. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10893. }
  10894. };
  10895. Engine.prototype.DrawMode = function (fillMode) {
  10896. switch (fillMode) {
  10897. // Triangle views
  10898. case BABYLON.Material.TriangleFillMode:
  10899. return this._gl.TRIANGLES;
  10900. case BABYLON.Material.PointFillMode:
  10901. return this._gl.POINTS;
  10902. case BABYLON.Material.WireFrameFillMode:
  10903. return this._gl.LINES;
  10904. // Draw modes
  10905. case BABYLON.Material.PointListDrawMode:
  10906. return this._gl.POINTS;
  10907. case BABYLON.Material.LineListDrawMode:
  10908. return this._gl.LINES;
  10909. case BABYLON.Material.LineLoopDrawMode:
  10910. return this._gl.LINE_LOOP;
  10911. case BABYLON.Material.LineStripDrawMode:
  10912. return this._gl.LINE_STRIP;
  10913. case BABYLON.Material.TriangleStripDrawMode:
  10914. return this._gl.TRIANGLE_STRIP;
  10915. case BABYLON.Material.TriangleFanDrawMode:
  10916. return this._gl.TRIANGLE_FAN;
  10917. default:
  10918. return this._gl.TRIANGLES;
  10919. }
  10920. };
  10921. // Shaders
  10922. Engine.prototype._releaseEffect = function (effect) {
  10923. if (this._compiledEffects[effect._key]) {
  10924. delete this._compiledEffects[effect._key];
  10925. this._deleteProgram(effect.getProgram());
  10926. }
  10927. };
  10928. Engine.prototype._deleteProgram = function (program) {
  10929. if (program) {
  10930. program.__SPECTOR_rebuildProgram = null;
  10931. if (program.transformFeedback) {
  10932. this.deleteTransformFeedback(program.transformFeedback);
  10933. program.transformFeedback = null;
  10934. }
  10935. this._gl.deleteProgram(program);
  10936. }
  10937. };
  10938. /**
  10939. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10940. * @param samplers An array of string used to represent textures
  10941. */
  10942. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10943. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10944. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10945. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10946. if (this._compiledEffects[name]) {
  10947. var compiledEffect = this._compiledEffects[name];
  10948. if (onCompiled && compiledEffect.isReady()) {
  10949. onCompiled(compiledEffect);
  10950. }
  10951. return compiledEffect;
  10952. }
  10953. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10954. effect._key = name;
  10955. this._compiledEffects[name] = effect;
  10956. return effect;
  10957. };
  10958. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10959. if (uniformsNames === void 0) { uniformsNames = []; }
  10960. if (samplers === void 0) { samplers = []; }
  10961. if (defines === void 0) { defines = ""; }
  10962. return this.createEffect({
  10963. vertex: "particles",
  10964. fragmentElement: fragmentName
  10965. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10966. };
  10967. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10968. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10969. context = context || this._gl;
  10970. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10971. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10972. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10973. };
  10974. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10975. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10976. context = context || this._gl;
  10977. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10978. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10979. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10980. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10981. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10982. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10983. return program;
  10984. };
  10985. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10986. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10987. var shaderProgram = context.createProgram();
  10988. if (!shaderProgram) {
  10989. throw new Error("Unable to create program");
  10990. }
  10991. context.attachShader(shaderProgram, vertexShader);
  10992. context.attachShader(shaderProgram, fragmentShader);
  10993. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10994. var transformFeedback = this.createTransformFeedback();
  10995. this.bindTransformFeedback(transformFeedback);
  10996. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10997. shaderProgram.transformFeedback = transformFeedback;
  10998. }
  10999. context.linkProgram(shaderProgram);
  11000. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  11001. this.bindTransformFeedback(null);
  11002. }
  11003. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  11004. if (!linked) {
  11005. context.validateProgram(shaderProgram);
  11006. var error = context.getProgramInfoLog(shaderProgram);
  11007. if (error) {
  11008. throw new Error(error);
  11009. }
  11010. }
  11011. context.deleteShader(vertexShader);
  11012. context.deleteShader(fragmentShader);
  11013. return shaderProgram;
  11014. };
  11015. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  11016. var results = new Array();
  11017. for (var index = 0; index < uniformsNames.length; index++) {
  11018. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  11019. }
  11020. return results;
  11021. };
  11022. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  11023. var results = [];
  11024. for (var index = 0; index < attributesNames.length; index++) {
  11025. try {
  11026. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  11027. }
  11028. catch (e) {
  11029. results.push(-1);
  11030. }
  11031. }
  11032. return results;
  11033. };
  11034. Engine.prototype.enableEffect = function (effect) {
  11035. if (!effect) {
  11036. return;
  11037. }
  11038. // Use program
  11039. this.bindSamplers(effect);
  11040. this._currentEffect = effect;
  11041. if (effect.onBind) {
  11042. effect.onBind(effect);
  11043. }
  11044. effect.onBindObservable.notifyObservers(effect);
  11045. };
  11046. Engine.prototype.setIntArray = function (uniform, array) {
  11047. if (!uniform)
  11048. return;
  11049. this._gl.uniform1iv(uniform, array);
  11050. };
  11051. Engine.prototype.setIntArray2 = function (uniform, array) {
  11052. if (!uniform || array.length % 2 !== 0)
  11053. return;
  11054. this._gl.uniform2iv(uniform, array);
  11055. };
  11056. Engine.prototype.setIntArray3 = function (uniform, array) {
  11057. if (!uniform || array.length % 3 !== 0)
  11058. return;
  11059. this._gl.uniform3iv(uniform, array);
  11060. };
  11061. Engine.prototype.setIntArray4 = function (uniform, array) {
  11062. if (!uniform || array.length % 4 !== 0)
  11063. return;
  11064. this._gl.uniform4iv(uniform, array);
  11065. };
  11066. Engine.prototype.setFloatArray = function (uniform, array) {
  11067. if (!uniform)
  11068. return;
  11069. this._gl.uniform1fv(uniform, array);
  11070. };
  11071. Engine.prototype.setFloatArray2 = function (uniform, array) {
  11072. if (!uniform || array.length % 2 !== 0)
  11073. return;
  11074. this._gl.uniform2fv(uniform, array);
  11075. };
  11076. Engine.prototype.setFloatArray3 = function (uniform, array) {
  11077. if (!uniform || array.length % 3 !== 0)
  11078. return;
  11079. this._gl.uniform3fv(uniform, array);
  11080. };
  11081. Engine.prototype.setFloatArray4 = function (uniform, array) {
  11082. if (!uniform || array.length % 4 !== 0)
  11083. return;
  11084. this._gl.uniform4fv(uniform, array);
  11085. };
  11086. Engine.prototype.setArray = function (uniform, array) {
  11087. if (!uniform)
  11088. return;
  11089. this._gl.uniform1fv(uniform, array);
  11090. };
  11091. Engine.prototype.setArray2 = function (uniform, array) {
  11092. if (!uniform || array.length % 2 !== 0)
  11093. return;
  11094. this._gl.uniform2fv(uniform, array);
  11095. };
  11096. Engine.prototype.setArray3 = function (uniform, array) {
  11097. if (!uniform || array.length % 3 !== 0)
  11098. return;
  11099. this._gl.uniform3fv(uniform, array);
  11100. };
  11101. Engine.prototype.setArray4 = function (uniform, array) {
  11102. if (!uniform || array.length % 4 !== 0)
  11103. return;
  11104. this._gl.uniform4fv(uniform, array);
  11105. };
  11106. Engine.prototype.setMatrices = function (uniform, matrices) {
  11107. if (!uniform)
  11108. return;
  11109. this._gl.uniformMatrix4fv(uniform, false, matrices);
  11110. };
  11111. Engine.prototype.setMatrix = function (uniform, matrix) {
  11112. if (!uniform)
  11113. return;
  11114. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  11115. };
  11116. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  11117. if (!uniform)
  11118. return;
  11119. this._gl.uniformMatrix3fv(uniform, false, matrix);
  11120. };
  11121. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  11122. if (!uniform)
  11123. return;
  11124. this._gl.uniformMatrix2fv(uniform, false, matrix);
  11125. };
  11126. Engine.prototype.setInt = function (uniform, value) {
  11127. if (!uniform)
  11128. return;
  11129. this._gl.uniform1i(uniform, value);
  11130. };
  11131. Engine.prototype.setFloat = function (uniform, value) {
  11132. if (!uniform)
  11133. return;
  11134. this._gl.uniform1f(uniform, value);
  11135. };
  11136. Engine.prototype.setFloat2 = function (uniform, x, y) {
  11137. if (!uniform)
  11138. return;
  11139. this._gl.uniform2f(uniform, x, y);
  11140. };
  11141. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  11142. if (!uniform)
  11143. return;
  11144. this._gl.uniform3f(uniform, x, y, z);
  11145. };
  11146. Engine.prototype.setBool = function (uniform, bool) {
  11147. if (!uniform)
  11148. return;
  11149. this._gl.uniform1i(uniform, bool);
  11150. };
  11151. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  11152. if (!uniform)
  11153. return;
  11154. this._gl.uniform4f(uniform, x, y, z, w);
  11155. };
  11156. Engine.prototype.setColor3 = function (uniform, color3) {
  11157. if (!uniform)
  11158. return;
  11159. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  11160. };
  11161. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  11162. if (!uniform)
  11163. return;
  11164. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  11165. };
  11166. // States
  11167. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  11168. if (zOffset === void 0) { zOffset = 0; }
  11169. if (reverseSide === void 0) { reverseSide = false; }
  11170. // Culling
  11171. if (this._depthCullingState.cull !== culling || force) {
  11172. this._depthCullingState.cull = culling;
  11173. }
  11174. // Cull face
  11175. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  11176. if (this._depthCullingState.cullFace !== cullFace || force) {
  11177. this._depthCullingState.cullFace = cullFace;
  11178. }
  11179. // Z offset
  11180. this.setZOffset(zOffset);
  11181. // Front face
  11182. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  11183. if (this._depthCullingState.frontFace !== frontFace || force) {
  11184. this._depthCullingState.frontFace = frontFace;
  11185. }
  11186. };
  11187. Engine.prototype.setZOffset = function (value) {
  11188. this._depthCullingState.zOffset = value;
  11189. };
  11190. Engine.prototype.getZOffset = function () {
  11191. return this._depthCullingState.zOffset;
  11192. };
  11193. Engine.prototype.setDepthBuffer = function (enable) {
  11194. this._depthCullingState.depthTest = enable;
  11195. };
  11196. Engine.prototype.getDepthWrite = function () {
  11197. return this._depthCullingState.depthMask;
  11198. };
  11199. Engine.prototype.setDepthWrite = function (enable) {
  11200. this._depthCullingState.depthMask = enable;
  11201. };
  11202. Engine.prototype.setColorWrite = function (enable) {
  11203. this._gl.colorMask(enable, enable, enable, enable);
  11204. this._colorWrite = enable;
  11205. };
  11206. Engine.prototype.getColorWrite = function () {
  11207. return this._colorWrite;
  11208. };
  11209. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  11210. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  11211. };
  11212. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  11213. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  11214. if (this._alphaMode === mode) {
  11215. return;
  11216. }
  11217. switch (mode) {
  11218. case Engine.ALPHA_DISABLE:
  11219. this._alphaState.alphaBlend = false;
  11220. break;
  11221. case Engine.ALPHA_PREMULTIPLIED:
  11222. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11223. this._alphaState.alphaBlend = true;
  11224. break;
  11225. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  11226. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11227. this._alphaState.alphaBlend = true;
  11228. break;
  11229. case Engine.ALPHA_COMBINE:
  11230. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  11231. this._alphaState.alphaBlend = true;
  11232. break;
  11233. case Engine.ALPHA_ONEONE:
  11234. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11235. this._alphaState.alphaBlend = true;
  11236. break;
  11237. case Engine.ALPHA_ADD:
  11238. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  11239. this._alphaState.alphaBlend = true;
  11240. break;
  11241. case Engine.ALPHA_SUBTRACT:
  11242. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11243. this._alphaState.alphaBlend = true;
  11244. break;
  11245. case Engine.ALPHA_MULTIPLY:
  11246. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  11247. this._alphaState.alphaBlend = true;
  11248. break;
  11249. case Engine.ALPHA_MAXIMIZED:
  11250. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  11251. this._alphaState.alphaBlend = true;
  11252. break;
  11253. case Engine.ALPHA_INTERPOLATE:
  11254. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  11255. this._alphaState.alphaBlend = true;
  11256. break;
  11257. case Engine.ALPHA_SCREENMODE:
  11258. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  11259. this._alphaState.alphaBlend = true;
  11260. break;
  11261. }
  11262. if (!noDepthWriteChange) {
  11263. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  11264. }
  11265. this._alphaMode = mode;
  11266. };
  11267. Engine.prototype.getAlphaMode = function () {
  11268. return this._alphaMode;
  11269. };
  11270. // Textures
  11271. Engine.prototype.wipeCaches = function (bruteForce) {
  11272. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  11273. return;
  11274. }
  11275. this._currentEffect = null;
  11276. // 6/8/2017: deltakosh: Should not be required anymore.
  11277. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  11278. if (bruteForce) {
  11279. this.resetTextureCache();
  11280. this._currentProgram = null;
  11281. this._stencilState.reset();
  11282. this._depthCullingState.reset();
  11283. this.setDepthFunctionToLessOrEqual();
  11284. this._alphaState.reset();
  11285. }
  11286. this._resetVertexBufferBinding();
  11287. this._cachedIndexBuffer = null;
  11288. this._cachedEffectForVertexBuffers = null;
  11289. this._unbindVertexArrayObject();
  11290. this.bindIndexBuffer(null);
  11291. };
  11292. /**
  11293. * Set the compressed texture format to use, based on the formats you have, and the formats
  11294. * supported by the hardware / browser.
  11295. *
  11296. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  11297. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  11298. * to API arguments needed to compressed textures. This puts the burden on the container
  11299. * generator to house the arcane code for determining these for current & future formats.
  11300. *
  11301. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  11302. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  11303. *
  11304. * Note: The result of this call is not taken into account when a texture is base64.
  11305. *
  11306. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  11307. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  11308. *
  11309. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  11310. * @returns The extension selected.
  11311. */
  11312. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  11313. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  11314. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  11315. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  11316. return this._textureFormatInUse = this._texturesSupported[i];
  11317. }
  11318. }
  11319. }
  11320. // actively set format to nothing, to allow this to be called more than once
  11321. // and possibly fail the 2nd time
  11322. this._textureFormatInUse = null;
  11323. return null;
  11324. };
  11325. Engine.prototype._createTexture = function () {
  11326. var texture = this._gl.createTexture();
  11327. if (!texture) {
  11328. throw new Error("Unable to create texture");
  11329. }
  11330. return texture;
  11331. };
  11332. /**
  11333. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  11334. * @param {string} urlArg- This contains one of the following:
  11335. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  11336. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  11337. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  11338. *
  11339. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  11340. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  11341. * @param {Scene} scene- Needed for loading to the correct scene.
  11342. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  11343. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  11344. * @param {callback} onError- Optional callback to be called upon failure.
  11345. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  11346. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  11347. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  11348. *
  11349. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  11350. */
  11351. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  11352. var _this = this;
  11353. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11354. if (onLoad === void 0) { onLoad = null; }
  11355. if (onError === void 0) { onError = null; }
  11356. if (buffer === void 0) { buffer = null; }
  11357. if (fallBack === void 0) { fallBack = null; }
  11358. if (format === void 0) { format = null; }
  11359. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  11360. var fromData = url.substr(0, 5) === "data:";
  11361. var fromBlob = url.substr(0, 5) === "blob:";
  11362. var isBase64 = fromData && url.indexOf("base64") !== -1;
  11363. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  11364. // establish the file extension, if possible
  11365. var lastDot = url.lastIndexOf('.');
  11366. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  11367. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  11368. var isTGA = (extension === ".tga");
  11369. // determine if a ktx file should be substituted
  11370. var isKTX = false;
  11371. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  11372. url = url.substring(0, lastDot) + this._textureFormatInUse;
  11373. isKTX = true;
  11374. }
  11375. if (scene) {
  11376. scene._addPendingData(texture);
  11377. }
  11378. texture.url = url;
  11379. texture.generateMipMaps = !noMipmap;
  11380. texture.samplingMode = samplingMode;
  11381. texture.invertY = invertY;
  11382. if (!this._doNotHandleContextLost) {
  11383. // Keep a link to the buffer only if we plan to handle context lost
  11384. texture._buffer = buffer;
  11385. }
  11386. var onLoadObserver = null;
  11387. if (onLoad && !fallBack) {
  11388. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  11389. }
  11390. if (!fallBack)
  11391. this._internalTexturesCache.push(texture);
  11392. var onerror = function (message, exception) {
  11393. if (scene) {
  11394. scene._removePendingData(texture);
  11395. }
  11396. if (onLoadObserver) {
  11397. texture.onLoadedObservable.remove(onLoadObserver);
  11398. }
  11399. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  11400. if (isKTX) {
  11401. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11402. }
  11403. else if (BABYLON.Tools.UseFallbackTexture) {
  11404. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  11405. }
  11406. if (onError) {
  11407. onError(message || "Unknown error", exception);
  11408. }
  11409. };
  11410. var callback = null;
  11411. // processing for non-image formats
  11412. if (isKTX || isTGA || isDDS) {
  11413. if (isKTX) {
  11414. callback = function (data) {
  11415. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  11416. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  11417. ktx.uploadLevels(_this._gl, !noMipmap);
  11418. return false;
  11419. }, samplingMode);
  11420. };
  11421. }
  11422. else if (isTGA) {
  11423. callback = function (arrayBuffer) {
  11424. var data = new Uint8Array(arrayBuffer);
  11425. var header = BABYLON.TGATools.GetTGAHeader(data);
  11426. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  11427. BABYLON.TGATools.UploadContent(_this._gl, data);
  11428. return false;
  11429. }, samplingMode);
  11430. };
  11431. }
  11432. else if (isDDS) {
  11433. callback = function (data) {
  11434. var info = BABYLON.DDSTools.GetDDSInfo(data);
  11435. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  11436. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  11437. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  11438. return false;
  11439. }, samplingMode);
  11440. };
  11441. }
  11442. if (!buffer) {
  11443. this._loadFile(url, function (data) {
  11444. if (callback) {
  11445. callback(data);
  11446. }
  11447. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  11448. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  11449. });
  11450. }
  11451. else {
  11452. if (callback) {
  11453. callback(buffer);
  11454. }
  11455. }
  11456. // image format processing
  11457. }
  11458. else {
  11459. var onload = function (img) {
  11460. if (fromBlob && !_this._doNotHandleContextLost) {
  11461. // We need to store the image if we need to rebuild the texture
  11462. // in case of a webgl context lost
  11463. texture._buffer = img;
  11464. }
  11465. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  11466. var gl = _this._gl;
  11467. var isPot = (img.width === potWidth && img.height === potHeight);
  11468. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  11469. if (isPot) {
  11470. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11471. return false;
  11472. }
  11473. // Using shaders to rescale because canvas.drawImage is lossy
  11474. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11475. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  11476. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  11477. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11478. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11479. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11480. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11481. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  11482. _this._releaseTexture(source);
  11483. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11484. continuationCallback();
  11485. });
  11486. return true;
  11487. }, samplingMode);
  11488. };
  11489. if (!fromData || isBase64)
  11490. if (buffer instanceof HTMLImageElement) {
  11491. onload(buffer);
  11492. }
  11493. else {
  11494. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11495. }
  11496. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  11497. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  11498. else
  11499. onload(buffer);
  11500. }
  11501. return texture;
  11502. };
  11503. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  11504. var _this = this;
  11505. var rtt = this.createRenderTargetTexture({
  11506. width: destination.width,
  11507. height: destination.height,
  11508. }, {
  11509. generateMipMaps: false,
  11510. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  11511. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  11512. generateDepthBuffer: false,
  11513. generateStencilBuffer: false
  11514. });
  11515. if (!this._rescalePostProcess) {
  11516. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  11517. }
  11518. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  11519. _this._rescalePostProcess.onApply = function (effect) {
  11520. effect._bindTexture("textureSampler", source);
  11521. };
  11522. var hostingScene = scene;
  11523. if (!hostingScene) {
  11524. hostingScene = _this.scenes[_this.scenes.length - 1];
  11525. }
  11526. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  11527. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  11528. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  11529. _this.unBindFramebuffer(rtt);
  11530. _this._releaseTexture(rtt);
  11531. if (onComplete) {
  11532. onComplete();
  11533. }
  11534. });
  11535. };
  11536. Engine.prototype._getInternalFormat = function (format) {
  11537. var internalFormat = this._gl.RGBA;
  11538. switch (format) {
  11539. case Engine.TEXTUREFORMAT_ALPHA:
  11540. internalFormat = this._gl.ALPHA;
  11541. break;
  11542. case Engine.TEXTUREFORMAT_LUMINANCE:
  11543. internalFormat = this._gl.LUMINANCE;
  11544. break;
  11545. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  11546. internalFormat = this._gl.LUMINANCE_ALPHA;
  11547. break;
  11548. case Engine.TEXTUREFORMAT_RGB:
  11549. internalFormat = this._gl.RGB;
  11550. break;
  11551. case Engine.TEXTUREFORMAT_RGBA:
  11552. internalFormat = this._gl.RGBA;
  11553. break;
  11554. }
  11555. return internalFormat;
  11556. };
  11557. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  11558. if (compression === void 0) { compression = null; }
  11559. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11560. if (!texture) {
  11561. return;
  11562. }
  11563. var internalFormat = this._getInternalFormat(format);
  11564. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11565. var textureType = this._getWebGLTextureType(type);
  11566. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11567. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11568. if (!this._doNotHandleContextLost) {
  11569. texture._bufferView = data;
  11570. texture.format = format;
  11571. texture.type = type;
  11572. texture.invertY = invertY;
  11573. texture._compression = compression;
  11574. }
  11575. if (texture.width % 4 !== 0) {
  11576. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11577. }
  11578. if (compression && data) {
  11579. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  11580. }
  11581. else {
  11582. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  11583. }
  11584. if (texture.generateMipMaps) {
  11585. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11586. }
  11587. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11588. // this.resetTextureCache();
  11589. texture.isReady = true;
  11590. };
  11591. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  11592. if (compression === void 0) { compression = null; }
  11593. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  11594. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  11595. texture.baseWidth = width;
  11596. texture.baseHeight = height;
  11597. texture.width = width;
  11598. texture.height = height;
  11599. texture.format = format;
  11600. texture.generateMipMaps = generateMipMaps;
  11601. texture.samplingMode = samplingMode;
  11602. texture.invertY = invertY;
  11603. texture._compression = compression;
  11604. texture.type = type;
  11605. if (!this._doNotHandleContextLost) {
  11606. texture._bufferView = data;
  11607. }
  11608. this.updateRawTexture(texture, data, format, invertY, compression, type);
  11609. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11610. // Filters
  11611. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11612. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11613. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11614. if (generateMipMaps) {
  11615. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11616. }
  11617. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11618. this._internalTexturesCache.push(texture);
  11619. return texture;
  11620. };
  11621. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  11622. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  11623. texture.baseWidth = width;
  11624. texture.baseHeight = height;
  11625. if (generateMipMaps) {
  11626. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  11627. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  11628. }
  11629. // this.resetTextureCache();
  11630. texture.width = width;
  11631. texture.height = height;
  11632. texture.isReady = false;
  11633. texture.generateMipMaps = generateMipMaps;
  11634. texture.samplingMode = samplingMode;
  11635. this.updateTextureSamplingMode(samplingMode, texture);
  11636. this._internalTexturesCache.push(texture);
  11637. return texture;
  11638. };
  11639. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  11640. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  11641. if (texture.isCube) {
  11642. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11643. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11644. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11645. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11646. }
  11647. else if (texture.is3D) {
  11648. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11649. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11650. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11651. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11652. }
  11653. else {
  11654. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11655. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11656. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11657. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11658. }
  11659. texture.samplingMode = samplingMode;
  11660. };
  11661. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  11662. if (premulAlpha === void 0) { premulAlpha = false; }
  11663. if (!texture) {
  11664. return;
  11665. }
  11666. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11667. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  11668. if (premulAlpha) {
  11669. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  11670. }
  11671. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  11672. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  11673. if (texture.generateMipMaps) {
  11674. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11675. }
  11676. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11677. if (premulAlpha) {
  11678. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  11679. }
  11680. texture.isReady = true;
  11681. };
  11682. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  11683. if (!texture || texture._isDisabled) {
  11684. return;
  11685. }
  11686. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  11687. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  11688. try {
  11689. // Testing video texture support
  11690. if (this._videoTextureSupported === undefined) {
  11691. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11692. if (this._gl.getError() !== 0) {
  11693. this._videoTextureSupported = false;
  11694. }
  11695. else {
  11696. this._videoTextureSupported = true;
  11697. }
  11698. }
  11699. // Copy video through the current working canvas if video texture is not supported
  11700. if (!this._videoTextureSupported) {
  11701. if (!texture._workingCanvas) {
  11702. texture._workingCanvas = document.createElement("canvas");
  11703. var context = texture._workingCanvas.getContext("2d");
  11704. if (!context) {
  11705. throw new Error("Unable to get 2d context");
  11706. }
  11707. texture._workingContext = context;
  11708. texture._workingCanvas.width = texture.width;
  11709. texture._workingCanvas.height = texture.height;
  11710. }
  11711. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  11712. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  11713. }
  11714. else {
  11715. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  11716. }
  11717. if (texture.generateMipMaps) {
  11718. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11719. }
  11720. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11721. // this.resetTextureCache();
  11722. texture.isReady = true;
  11723. }
  11724. catch (ex) {
  11725. // Something unexpected
  11726. // Let's disable the texture
  11727. texture._isDisabled = true;
  11728. }
  11729. };
  11730. Engine.prototype.createRenderTargetTexture = function (size, options) {
  11731. var fullOptions = new RenderTargetCreationOptions();
  11732. if (options !== undefined && typeof options === "object") {
  11733. fullOptions.generateMipMaps = options.generateMipMaps;
  11734. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11735. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  11736. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  11737. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  11738. }
  11739. else {
  11740. fullOptions.generateMipMaps = options;
  11741. fullOptions.generateDepthBuffer = true;
  11742. fullOptions.generateStencilBuffer = false;
  11743. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11744. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11745. }
  11746. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11747. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11748. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11749. }
  11750. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11751. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11752. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11753. }
  11754. var gl = this._gl;
  11755. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11756. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11757. var width = size.width || size;
  11758. var height = size.height || size;
  11759. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  11760. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11761. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11762. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11763. }
  11764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11766. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11767. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11768. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  11769. // Create the framebuffer
  11770. var framebuffer = gl.createFramebuffer();
  11771. this.bindUnboundFramebuffer(framebuffer);
  11772. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11773. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  11774. if (fullOptions.generateMipMaps) {
  11775. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11776. }
  11777. // Unbind
  11778. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11779. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11780. this.bindUnboundFramebuffer(null);
  11781. texture._framebuffer = framebuffer;
  11782. texture.baseWidth = width;
  11783. texture.baseHeight = height;
  11784. texture.width = width;
  11785. texture.height = height;
  11786. texture.isReady = true;
  11787. texture.samples = 1;
  11788. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  11789. texture.samplingMode = fullOptions.samplingMode;
  11790. texture.type = fullOptions.type;
  11791. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  11792. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  11793. // this.resetTextureCache();
  11794. this._internalTexturesCache.push(texture);
  11795. return texture;
  11796. };
  11797. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  11798. var generateMipMaps = false;
  11799. var generateDepthBuffer = true;
  11800. var generateStencilBuffer = false;
  11801. var generateDepthTexture = false;
  11802. var textureCount = 1;
  11803. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  11804. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11805. var types = [], samplingModes = [];
  11806. if (options !== undefined) {
  11807. generateMipMaps = options.generateMipMaps;
  11808. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11809. generateStencilBuffer = options.generateStencilBuffer;
  11810. generateDepthTexture = options.generateDepthTexture;
  11811. textureCount = options.textureCount || 1;
  11812. if (options.types) {
  11813. types = options.types;
  11814. }
  11815. if (options.samplingModes) {
  11816. samplingModes = options.samplingModes;
  11817. }
  11818. }
  11819. var gl = this._gl;
  11820. // Create the framebuffer
  11821. var framebuffer = gl.createFramebuffer();
  11822. this.bindUnboundFramebuffer(framebuffer);
  11823. var width = size.width || size;
  11824. var height = size.height || size;
  11825. var textures = [];
  11826. var attachments = [];
  11827. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  11828. for (var i = 0; i < textureCount; i++) {
  11829. var samplingMode = samplingModes[i] || defaultSamplingMode;
  11830. var type = types[i] || defaultType;
  11831. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  11832. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  11833. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11834. }
  11835. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  11836. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  11837. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  11838. }
  11839. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11840. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  11841. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  11842. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  11843. }
  11844. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11845. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11846. textures.push(texture);
  11847. attachments.push(attachment);
  11848. gl.activeTexture(gl["TEXTURE" + i]);
  11849. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  11850. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11851. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11852. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11854. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11855. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  11856. if (generateMipMaps) {
  11857. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  11858. }
  11859. // Unbind
  11860. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11861. texture._framebuffer = framebuffer;
  11862. texture._depthStencilBuffer = depthStencilBuffer;
  11863. texture.baseWidth = width;
  11864. texture.baseHeight = height;
  11865. texture.width = width;
  11866. texture.height = height;
  11867. texture.isReady = true;
  11868. texture.samples = 1;
  11869. texture.generateMipMaps = generateMipMaps;
  11870. texture.samplingMode = samplingMode;
  11871. texture.type = type;
  11872. texture._generateDepthBuffer = generateDepthBuffer;
  11873. texture._generateStencilBuffer = generateStencilBuffer;
  11874. texture._attachments = attachments;
  11875. this._internalTexturesCache.push(texture);
  11876. }
  11877. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11878. // Depth texture
  11879. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11880. gl.activeTexture(gl.TEXTURE0);
  11881. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11884. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11885. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11886. 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);
  11887. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11888. depthTexture._framebuffer = framebuffer;
  11889. depthTexture.baseWidth = width;
  11890. depthTexture.baseHeight = height;
  11891. depthTexture.width = width;
  11892. depthTexture.height = height;
  11893. depthTexture.isReady = true;
  11894. depthTexture.samples = 1;
  11895. depthTexture.generateMipMaps = generateMipMaps;
  11896. depthTexture.samplingMode = gl.NEAREST;
  11897. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11898. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11899. textures.push(depthTexture);
  11900. this._internalTexturesCache.push(depthTexture);
  11901. }
  11902. gl.drawBuffers(attachments);
  11903. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11904. this.bindUnboundFramebuffer(null);
  11905. this.resetTextureCache();
  11906. return textures;
  11907. };
  11908. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11909. if (samples === void 0) { samples = 1; }
  11910. var depthStencilBuffer = null;
  11911. var gl = this._gl;
  11912. // Create the depth/stencil buffer
  11913. if (generateStencilBuffer) {
  11914. depthStencilBuffer = gl.createRenderbuffer();
  11915. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11916. if (samples > 1) {
  11917. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11918. }
  11919. else {
  11920. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11921. }
  11922. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11923. }
  11924. else if (generateDepthBuffer) {
  11925. depthStencilBuffer = gl.createRenderbuffer();
  11926. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11927. if (samples > 1) {
  11928. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11929. }
  11930. else {
  11931. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11932. }
  11933. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11934. }
  11935. return depthStencilBuffer;
  11936. };
  11937. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11938. if (this.webGLVersion < 2 || !texture) {
  11939. return 1;
  11940. }
  11941. if (texture.samples === samples) {
  11942. return samples;
  11943. }
  11944. var gl = this._gl;
  11945. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11946. // Dispose previous render buffers
  11947. if (texture._depthStencilBuffer) {
  11948. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11949. texture._depthStencilBuffer = null;
  11950. }
  11951. if (texture._MSAAFramebuffer) {
  11952. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11953. texture._MSAAFramebuffer = null;
  11954. }
  11955. if (texture._MSAARenderBuffer) {
  11956. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11957. texture._MSAARenderBuffer = null;
  11958. }
  11959. if (samples > 1) {
  11960. var framebuffer = gl.createFramebuffer();
  11961. if (!framebuffer) {
  11962. throw new Error("Unable to create multi sampled framebuffer");
  11963. }
  11964. texture._MSAAFramebuffer = framebuffer;
  11965. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11966. var colorRenderbuffer = gl.createRenderbuffer();
  11967. if (!colorRenderbuffer) {
  11968. throw new Error("Unable to create multi sampled framebuffer");
  11969. }
  11970. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11971. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  11972. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11973. texture._MSAARenderBuffer = colorRenderbuffer;
  11974. }
  11975. else {
  11976. this.bindUnboundFramebuffer(texture._framebuffer);
  11977. }
  11978. texture.samples = samples;
  11979. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11980. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11981. this.bindUnboundFramebuffer(null);
  11982. return samples;
  11983. };
  11984. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11985. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11986. return 1;
  11987. }
  11988. if (textures[0].samples === samples) {
  11989. return samples;
  11990. }
  11991. var gl = this._gl;
  11992. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11993. // Dispose previous render buffers
  11994. if (textures[0]._depthStencilBuffer) {
  11995. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11996. textures[0]._depthStencilBuffer = null;
  11997. }
  11998. if (textures[0]._MSAAFramebuffer) {
  11999. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  12000. textures[0]._MSAAFramebuffer = null;
  12001. }
  12002. for (var i = 0; i < textures.length; i++) {
  12003. if (textures[i]._MSAARenderBuffer) {
  12004. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  12005. textures[i]._MSAARenderBuffer = null;
  12006. }
  12007. }
  12008. if (samples > 1) {
  12009. var framebuffer = gl.createFramebuffer();
  12010. if (!framebuffer) {
  12011. throw new Error("Unable to create multi sampled framebuffer");
  12012. }
  12013. this.bindUnboundFramebuffer(framebuffer);
  12014. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  12015. var attachments = [];
  12016. for (var i = 0; i < textures.length; i++) {
  12017. var texture = textures[i];
  12018. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12019. var colorRenderbuffer = gl.createRenderbuffer();
  12020. if (!colorRenderbuffer) {
  12021. throw new Error("Unable to create multi sampled framebuffer");
  12022. }
  12023. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  12024. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  12025. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  12026. texture._MSAAFramebuffer = framebuffer;
  12027. texture._MSAARenderBuffer = colorRenderbuffer;
  12028. texture.samples = samples;
  12029. texture._depthStencilBuffer = depthStencilBuffer;
  12030. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12031. attachments.push(attachment);
  12032. }
  12033. gl.drawBuffers(attachments);
  12034. }
  12035. else {
  12036. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12037. }
  12038. this.bindUnboundFramebuffer(null);
  12039. return samples;
  12040. };
  12041. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  12042. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  12043. };
  12044. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  12045. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  12046. };
  12047. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  12048. var gl = this._gl;
  12049. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  12050. var generateMipMaps = true;
  12051. var generateDepthBuffer = true;
  12052. var generateStencilBuffer = false;
  12053. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  12054. if (options !== undefined) {
  12055. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  12056. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  12057. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  12058. if (options.samplingMode !== undefined) {
  12059. samplingMode = options.samplingMode;
  12060. }
  12061. }
  12062. texture.isCube = true;
  12063. texture.generateMipMaps = generateMipMaps;
  12064. texture.samples = 1;
  12065. texture.samplingMode = samplingMode;
  12066. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12067. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12068. for (var face = 0; face < 6; face++) {
  12069. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  12070. }
  12071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12072. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12073. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12074. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12075. // Create the framebuffer
  12076. var framebuffer = gl.createFramebuffer();
  12077. this.bindUnboundFramebuffer(framebuffer);
  12078. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  12079. // Mipmaps
  12080. if (texture.generateMipMaps) {
  12081. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12082. }
  12083. // Unbind
  12084. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12085. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  12086. this.bindUnboundFramebuffer(null);
  12087. texture._framebuffer = framebuffer;
  12088. texture.width = size;
  12089. texture.height = size;
  12090. texture.isReady = true;
  12091. //this.resetTextureCache();
  12092. this._internalTexturesCache.push(texture);
  12093. return texture;
  12094. };
  12095. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  12096. var _this = this;
  12097. if (onLoad === void 0) { onLoad = null; }
  12098. if (onError === void 0) { onError = null; }
  12099. if (forcedExtension === void 0) { forcedExtension = null; }
  12100. var callback = function (loadData) {
  12101. if (!loadData) {
  12102. if (onLoad) {
  12103. onLoad(null);
  12104. }
  12105. return;
  12106. }
  12107. var texture = loadData.texture;
  12108. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  12109. texture._lodGenerationScale = scale;
  12110. texture._lodGenerationOffset = offset;
  12111. if (_this._caps.textureLOD) {
  12112. // Do not add extra process if texture lod is supported.
  12113. if (onLoad) {
  12114. onLoad(texture);
  12115. }
  12116. return;
  12117. }
  12118. var mipSlices = 3;
  12119. var gl = _this._gl;
  12120. var width = loadData.width;
  12121. if (!width) {
  12122. return;
  12123. }
  12124. var textures = [];
  12125. for (var i = 0; i < mipSlices; i++) {
  12126. //compute LOD from even spacing in smoothness (matching shader calculation)
  12127. var smoothness = i / (mipSlices - 1);
  12128. var roughness = 1 - smoothness;
  12129. var minLODIndex = offset; // roughness = 0
  12130. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  12131. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  12132. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  12133. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12134. glTextureFromLod.isCube = true;
  12135. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  12136. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12137. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12138. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12139. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12140. if (loadData.isDDS) {
  12141. var info = loadData.info;
  12142. var data = loadData.data;
  12143. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12144. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  12145. }
  12146. else {
  12147. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  12148. }
  12149. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12150. // Wrap in a base texture for easy binding.
  12151. var lodTexture = new BABYLON.BaseTexture(scene);
  12152. lodTexture.isCube = true;
  12153. lodTexture._texture = glTextureFromLod;
  12154. glTextureFromLod.isReady = true;
  12155. textures.push(lodTexture);
  12156. }
  12157. texture._lodTextureHigh = textures[2];
  12158. texture._lodTextureMid = textures[1];
  12159. texture._lodTextureLow = textures[0];
  12160. if (onLoad) {
  12161. onLoad(texture);
  12162. }
  12163. };
  12164. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  12165. };
  12166. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  12167. var _this = this;
  12168. if (onLoad === void 0) { onLoad = null; }
  12169. if (onError === void 0) { onError = null; }
  12170. if (forcedExtension === void 0) { forcedExtension = null; }
  12171. var gl = this._gl;
  12172. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  12173. texture.isCube = true;
  12174. texture.url = rootUrl;
  12175. texture.generateMipMaps = !noMipmap;
  12176. if (!this._doNotHandleContextLost) {
  12177. texture._extension = forcedExtension;
  12178. texture._files = files;
  12179. }
  12180. var isKTX = false;
  12181. var isDDS = false;
  12182. var lastDot = rootUrl.lastIndexOf('.');
  12183. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  12184. if (this._textureFormatInUse) {
  12185. extension = this._textureFormatInUse;
  12186. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  12187. isKTX = true;
  12188. }
  12189. else {
  12190. isDDS = (extension === ".dds");
  12191. }
  12192. var onerror = function (request, exception) {
  12193. if (onError && request) {
  12194. onError(request.status + " " + request.statusText, exception);
  12195. }
  12196. };
  12197. if (isKTX) {
  12198. this._loadFile(rootUrl, function (data) {
  12199. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  12200. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  12201. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12202. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  12203. ktx.uploadLevels(_this._gl, !noMipmap);
  12204. _this.setCubeMapTextureParams(gl, loadMipmap);
  12205. texture.width = ktx.pixelWidth;
  12206. texture.height = ktx.pixelHeight;
  12207. texture.isReady = true;
  12208. }, undefined, undefined, true, onerror);
  12209. }
  12210. else if (isDDS) {
  12211. if (files && files.length === 6) {
  12212. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  12213. var info;
  12214. var loadMipmap = false;
  12215. var width = 0;
  12216. for (var index = 0; index < imgs.length; index++) {
  12217. var data = imgs[index];
  12218. info = BABYLON.DDSTools.GetDDSInfo(data);
  12219. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12220. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12221. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12222. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  12223. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12224. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12225. }
  12226. texture.width = info.width;
  12227. texture.height = info.height;
  12228. texture.type = info.textureType;
  12229. width = info.width;
  12230. }
  12231. _this.setCubeMapTextureParams(gl, loadMipmap);
  12232. texture.isReady = true;
  12233. if (onLoad) {
  12234. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  12235. }
  12236. }, files, onError);
  12237. }
  12238. else {
  12239. this._loadFile(rootUrl, function (data) {
  12240. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12241. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  12242. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12243. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  12244. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  12245. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  12246. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12247. }
  12248. _this.setCubeMapTextureParams(gl, loadMipmap);
  12249. texture.width = info.width;
  12250. texture.height = info.height;
  12251. texture.isReady = true;
  12252. texture.type = info.textureType;
  12253. if (onLoad) {
  12254. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  12255. }
  12256. }, undefined, undefined, true, onerror);
  12257. }
  12258. }
  12259. else {
  12260. if (!files) {
  12261. throw new Error("Cannot load cubemap because files were not defined");
  12262. }
  12263. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  12264. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  12265. var height = width;
  12266. _this._prepareWorkingCanvas();
  12267. if (!_this._workingCanvas || !_this._workingContext) {
  12268. return;
  12269. }
  12270. _this._workingCanvas.width = width;
  12271. _this._workingCanvas.height = height;
  12272. var faces = [
  12273. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  12274. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  12275. ];
  12276. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12277. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12278. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  12279. for (var index = 0; index < faces.length; index++) {
  12280. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  12281. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  12282. }
  12283. if (!noMipmap) {
  12284. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12285. }
  12286. _this.setCubeMapTextureParams(gl, !noMipmap);
  12287. texture.width = width;
  12288. texture.height = height;
  12289. texture.isReady = true;
  12290. if (format) {
  12291. texture.format = format;
  12292. }
  12293. texture.onLoadedObservable.notifyObservers(texture);
  12294. texture.onLoadedObservable.clear();
  12295. if (onLoad) {
  12296. onLoad();
  12297. }
  12298. }, files, onError);
  12299. }
  12300. this._internalTexturesCache.push(texture);
  12301. return texture;
  12302. };
  12303. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  12304. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12305. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  12306. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12307. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12308. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12309. // this.resetTextureCache();
  12310. };
  12311. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  12312. if (compression === void 0) { compression = null; }
  12313. if (level === void 0) { level = 0; }
  12314. texture._bufferViewArray = data;
  12315. texture.format = format;
  12316. texture.type = type;
  12317. texture.invertY = invertY;
  12318. texture._compression = compression;
  12319. var gl = this._gl;
  12320. var textureType = this._getWebGLTextureType(type);
  12321. var internalFormat = this._getInternalFormat(format);
  12322. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  12323. var needConversion = false;
  12324. if (internalFormat === gl.RGB) {
  12325. internalFormat = gl.RGBA;
  12326. needConversion = true;
  12327. }
  12328. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12329. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12330. if (texture.width % 4 !== 0) {
  12331. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  12332. }
  12333. // Data are known to be in +X +Y +Z -X -Y -Z
  12334. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12335. var faceData = data[faceIndex];
  12336. if (compression) {
  12337. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  12338. }
  12339. else {
  12340. if (needConversion) {
  12341. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  12342. }
  12343. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  12344. }
  12345. }
  12346. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12347. if (isPot && texture.generateMipMaps && level === 0) {
  12348. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12349. }
  12350. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12351. // this.resetTextureCache();
  12352. texture.isReady = true;
  12353. };
  12354. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  12355. if (compression === void 0) { compression = null; }
  12356. var gl = this._gl;
  12357. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  12358. texture.isCube = true;
  12359. texture.generateMipMaps = generateMipMaps;
  12360. texture.format = format;
  12361. texture.type = type;
  12362. if (!this._doNotHandleContextLost) {
  12363. texture._bufferViewArray = data;
  12364. }
  12365. var textureType = this._getWebGLTextureType(type);
  12366. var internalFormat = this._getInternalFormat(format);
  12367. if (internalFormat === gl.RGB) {
  12368. internalFormat = gl.RGBA;
  12369. }
  12370. var width = size;
  12371. var height = width;
  12372. texture.width = width;
  12373. texture.height = height;
  12374. // Double check on POT to generate Mips.
  12375. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  12376. if (!isPot) {
  12377. generateMipMaps = false;
  12378. }
  12379. // Upload data if needed. The texture won't be ready until then.
  12380. if (data) {
  12381. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  12382. }
  12383. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  12384. // Filters
  12385. if (data && generateMipMaps) {
  12386. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  12387. }
  12388. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  12389. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12390. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12391. }
  12392. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  12393. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12394. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12395. }
  12396. else {
  12397. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  12398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  12399. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  12400. }
  12401. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12402. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12403. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12404. return texture;
  12405. };
  12406. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  12407. var _this = this;
  12408. if (onLoad === void 0) { onLoad = null; }
  12409. if (onError === void 0) { onError = null; }
  12410. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12411. if (invertY === void 0) { invertY = false; }
  12412. var gl = this._gl;
  12413. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  12414. scene._addPendingData(texture);
  12415. texture.url = url;
  12416. this._internalTexturesCache.push(texture);
  12417. var onerror = function (request, exception) {
  12418. scene._removePendingData(texture);
  12419. if (onError && request) {
  12420. onError(request.status + " " + request.statusText, exception);
  12421. }
  12422. };
  12423. var internalCallback = function (data) {
  12424. var width = texture.width;
  12425. var faceDataArrays = callback(data);
  12426. if (!faceDataArrays) {
  12427. return;
  12428. }
  12429. if (mipmmapGenerator) {
  12430. var textureType = _this._getWebGLTextureType(type);
  12431. var internalFormat = _this._getInternalFormat(format);
  12432. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  12433. var needConversion = false;
  12434. if (internalFormat === gl.RGB) {
  12435. internalFormat = gl.RGBA;
  12436. needConversion = true;
  12437. }
  12438. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12439. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  12440. var mipData = mipmmapGenerator(faceDataArrays);
  12441. for (var level = 0; level < mipData.length; level++) {
  12442. var mipSize = width >> level;
  12443. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  12444. var mipFaceData = mipData[level][faceIndex];
  12445. if (needConversion) {
  12446. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  12447. }
  12448. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  12449. }
  12450. }
  12451. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12452. }
  12453. else {
  12454. texture.generateMipMaps = !noMipmap;
  12455. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  12456. }
  12457. texture.isReady = true;
  12458. // this.resetTextureCache();
  12459. scene._removePendingData(texture);
  12460. if (onLoad) {
  12461. onLoad();
  12462. }
  12463. };
  12464. this._loadFile(url, function (data) {
  12465. internalCallback(data);
  12466. }, undefined, scene.database, true, onerror);
  12467. return texture;
  12468. };
  12469. ;
  12470. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  12471. if (compression === void 0) { compression = null; }
  12472. var internalFormat = this._getInternalFormat(format);
  12473. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12474. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12475. if (!this._doNotHandleContextLost) {
  12476. texture._bufferView = data;
  12477. texture.format = format;
  12478. texture.invertY = invertY;
  12479. texture._compression = compression;
  12480. }
  12481. if (texture.width % 4 !== 0) {
  12482. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12483. }
  12484. if (compression && data) {
  12485. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  12486. }
  12487. else {
  12488. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  12489. }
  12490. if (texture.generateMipMaps) {
  12491. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12492. }
  12493. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12494. // this.resetTextureCache();
  12495. texture.isReady = true;
  12496. };
  12497. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  12498. if (compression === void 0) { compression = null; }
  12499. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  12500. texture.baseWidth = width;
  12501. texture.baseHeight = height;
  12502. texture.baseDepth = depth;
  12503. texture.width = width;
  12504. texture.height = height;
  12505. texture.depth = depth;
  12506. texture.format = format;
  12507. texture.generateMipMaps = generateMipMaps;
  12508. texture.samplingMode = samplingMode;
  12509. texture.is3D = true;
  12510. if (!this._doNotHandleContextLost) {
  12511. texture._bufferView = data;
  12512. }
  12513. this.updateRawTexture3D(texture, data, format, invertY, compression);
  12514. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  12515. // Filters
  12516. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  12517. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  12518. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  12519. if (generateMipMaps) {
  12520. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  12521. }
  12522. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12523. this._internalTexturesCache.push(texture);
  12524. return texture;
  12525. };
  12526. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  12527. var gl = this._gl;
  12528. if (!gl) {
  12529. return;
  12530. }
  12531. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  12532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  12533. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  12534. if (!noMipmap && !isCompressed) {
  12535. gl.generateMipmap(gl.TEXTURE_2D);
  12536. }
  12537. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12538. // this.resetTextureCache();
  12539. if (scene) {
  12540. scene._removePendingData(texture);
  12541. }
  12542. texture.onLoadedObservable.notifyObservers(texture);
  12543. texture.onLoadedObservable.clear();
  12544. };
  12545. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  12546. var _this = this;
  12547. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12548. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  12549. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  12550. var gl = this._gl;
  12551. if (!gl) {
  12552. return;
  12553. }
  12554. if (!texture._webGLTexture) {
  12555. // this.resetTextureCache();
  12556. if (scene) {
  12557. scene._removePendingData(texture);
  12558. }
  12559. return;
  12560. }
  12561. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12562. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12563. texture.baseWidth = width;
  12564. texture.baseHeight = height;
  12565. texture.width = potWidth;
  12566. texture.height = potHeight;
  12567. texture.isReady = true;
  12568. if (processFunction(potWidth, potHeight, function () {
  12569. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12570. })) {
  12571. // Returning as texture needs extra async steps
  12572. return;
  12573. }
  12574. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  12575. };
  12576. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  12577. // Create new RGBA data container.
  12578. var rgbaData;
  12579. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  12580. rgbaData = new Float32Array(width * height * 4);
  12581. }
  12582. else {
  12583. rgbaData = new Uint32Array(width * height * 4);
  12584. }
  12585. // Convert each pixel.
  12586. for (var x = 0; x < width; x++) {
  12587. for (var y = 0; y < height; y++) {
  12588. var index = (y * width + x) * 3;
  12589. var newIndex = (y * width + x) * 4;
  12590. // Map Old Value to new value.
  12591. rgbaData[newIndex + 0] = rgbData[index + 0];
  12592. rgbaData[newIndex + 1] = rgbData[index + 1];
  12593. rgbaData[newIndex + 2] = rgbData[index + 2];
  12594. // Add fully opaque alpha channel.
  12595. rgbaData[newIndex + 3] = 1;
  12596. }
  12597. }
  12598. return rgbaData;
  12599. };
  12600. Engine.prototype._releaseFramebufferObjects = function (texture) {
  12601. var gl = this._gl;
  12602. if (texture._framebuffer) {
  12603. gl.deleteFramebuffer(texture._framebuffer);
  12604. texture._framebuffer = null;
  12605. }
  12606. if (texture._depthStencilBuffer) {
  12607. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  12608. texture._depthStencilBuffer = null;
  12609. }
  12610. if (texture._MSAAFramebuffer) {
  12611. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  12612. texture._MSAAFramebuffer = null;
  12613. }
  12614. if (texture._MSAARenderBuffer) {
  12615. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  12616. texture._MSAARenderBuffer = null;
  12617. }
  12618. };
  12619. Engine.prototype._releaseTexture = function (texture) {
  12620. var gl = this._gl;
  12621. this._releaseFramebufferObjects(texture);
  12622. gl.deleteTexture(texture._webGLTexture);
  12623. // Unbind channels
  12624. this.unbindAllTextures();
  12625. var index = this._internalTexturesCache.indexOf(texture);
  12626. if (index !== -1) {
  12627. this._internalTexturesCache.splice(index, 1);
  12628. }
  12629. // Integrated fixed lod samplers.
  12630. if (texture._lodTextureHigh) {
  12631. texture._lodTextureHigh.dispose();
  12632. }
  12633. if (texture._lodTextureMid) {
  12634. texture._lodTextureMid.dispose();
  12635. }
  12636. if (texture._lodTextureLow) {
  12637. texture._lodTextureLow.dispose();
  12638. }
  12639. };
  12640. Engine.prototype.setProgram = function (program) {
  12641. if (this._currentProgram !== program) {
  12642. this._gl.useProgram(program);
  12643. this._currentProgram = program;
  12644. }
  12645. };
  12646. Engine.prototype.bindSamplers = function (effect) {
  12647. this.setProgram(effect.getProgram());
  12648. var samplers = effect.getSamplers();
  12649. for (var index = 0; index < samplers.length; index++) {
  12650. var uniform = effect.getUniform(samplers[index]);
  12651. if (uniform) {
  12652. this._boundUniforms[index] = uniform;
  12653. }
  12654. }
  12655. this._currentEffect = null;
  12656. };
  12657. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  12658. var index = this._boundTexturesStack.indexOf(internalTexture);
  12659. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  12660. this._boundTexturesStack.splice(index, 1);
  12661. this._boundTexturesStack.push(internalTexture);
  12662. }
  12663. };
  12664. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  12665. if (!internalTexture) {
  12666. return -1;
  12667. }
  12668. internalTexture._initialSlot = channel;
  12669. if (this.disableTextureBindingOptimization) {
  12670. if (channel !== internalTexture._designatedSlot) {
  12671. this._textureCollisions.addCount(1, false);
  12672. }
  12673. }
  12674. else {
  12675. if (channel !== internalTexture._designatedSlot) {
  12676. if (internalTexture._designatedSlot > -1) {
  12677. return internalTexture._designatedSlot;
  12678. }
  12679. else {
  12680. // No slot for this texture, let's pick a new one (if we find a free slot)
  12681. if (this._nextFreeTextureSlots.length) {
  12682. return this._nextFreeTextureSlots[0];
  12683. }
  12684. // We need to recycle the oldest bound texture, sorry.
  12685. this._textureCollisions.addCount(1, false);
  12686. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  12687. }
  12688. }
  12689. }
  12690. return channel;
  12691. };
  12692. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  12693. var currentSlot = internalTexture._designatedSlot;
  12694. internalTexture._designatedSlot = -1;
  12695. var index = this._boundTexturesStack.indexOf(internalTexture);
  12696. if (index > -1) {
  12697. this._boundTexturesStack.splice(index, 1);
  12698. if (currentSlot > -1) {
  12699. this._boundTexturesCache[currentSlot] = null;
  12700. this._nextFreeTextureSlots.push(currentSlot);
  12701. }
  12702. }
  12703. return currentSlot;
  12704. };
  12705. Engine.prototype._activateCurrentTexture = function () {
  12706. if (this._currentTextureChannel !== this._activeChannel) {
  12707. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  12708. this._currentTextureChannel = this._activeChannel;
  12709. }
  12710. };
  12711. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  12712. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  12713. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  12714. this._activeChannel = texture._designatedSlot;
  12715. }
  12716. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  12717. var isTextureForRendering = texture && texture._initialSlot > -1;
  12718. if (currentTextureBound !== texture) {
  12719. if (currentTextureBound && !this.disableTextureBindingOptimization) {
  12720. this._removeDesignatedSlot(currentTextureBound);
  12721. }
  12722. this._activateCurrentTexture();
  12723. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  12724. this._boundTexturesCache[this._activeChannel] = texture;
  12725. if (texture) {
  12726. if (!this.disableTextureBindingOptimization) {
  12727. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  12728. if (slotIndex > -1) {
  12729. this._nextFreeTextureSlots.splice(slotIndex, 1);
  12730. }
  12731. this._boundTexturesStack.push(texture);
  12732. }
  12733. texture._designatedSlot = this._activeChannel;
  12734. }
  12735. }
  12736. else if (forTextureDataUpdate) {
  12737. this._activateCurrentTexture();
  12738. }
  12739. if (isTextureForRendering && !forTextureDataUpdate) {
  12740. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  12741. }
  12742. };
  12743. Engine.prototype._bindTexture = function (channel, texture) {
  12744. if (channel < 0) {
  12745. return;
  12746. }
  12747. if (texture) {
  12748. channel = this._getCorrectTextureChannel(channel, texture);
  12749. }
  12750. this._activeChannel = channel;
  12751. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  12752. };
  12753. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12754. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  12755. };
  12756. Engine.prototype.unbindAllTextures = function () {
  12757. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  12758. this._activeChannel = channel;
  12759. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12760. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12761. if (this.webGLVersion > 1) {
  12762. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12763. }
  12764. }
  12765. };
  12766. Engine.prototype.setTexture = function (channel, uniform, texture) {
  12767. if (channel < 0) {
  12768. return;
  12769. }
  12770. if (uniform) {
  12771. this._boundUniforms[channel] = uniform;
  12772. }
  12773. this._setTexture(channel, texture);
  12774. };
  12775. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  12776. var uniform = this._boundUniforms[sourceSlot];
  12777. if (uniform._currentState === destination) {
  12778. return;
  12779. }
  12780. this._gl.uniform1i(uniform, destination);
  12781. uniform._currentState = destination;
  12782. };
  12783. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  12784. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  12785. // Not ready?
  12786. if (!texture) {
  12787. if (this._boundTexturesCache[channel] != null) {
  12788. this._activeChannel = channel;
  12789. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12790. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  12791. if (this.webGLVersion > 1) {
  12792. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  12793. }
  12794. }
  12795. return false;
  12796. }
  12797. // Video
  12798. if (texture.video) {
  12799. this._activeChannel = channel;
  12800. texture.update();
  12801. }
  12802. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  12803. texture.delayLoad();
  12804. return false;
  12805. }
  12806. var internalTexture;
  12807. if (texture.isReady()) {
  12808. internalTexture = texture.getInternalTexture();
  12809. }
  12810. else if (texture.isCube) {
  12811. internalTexture = this.emptyCubeTexture;
  12812. }
  12813. else if (texture.is3D) {
  12814. internalTexture = this.emptyTexture3D;
  12815. }
  12816. else {
  12817. internalTexture = this.emptyTexture;
  12818. }
  12819. if (!isPartOfTextureArray) {
  12820. channel = this._getCorrectTextureChannel(channel, internalTexture);
  12821. }
  12822. if (this._boundTexturesCache[channel] === internalTexture) {
  12823. this._moveBoundTextureOnTop(internalTexture);
  12824. if (!isPartOfTextureArray) {
  12825. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  12826. }
  12827. return false;
  12828. }
  12829. this._activeChannel = channel;
  12830. if (internalTexture && internalTexture.is3D) {
  12831. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  12832. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12833. internalTexture._cachedWrapU = texture.wrapU;
  12834. switch (texture.wrapU) {
  12835. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12836. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12837. break;
  12838. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12839. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12840. break;
  12841. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12842. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12843. break;
  12844. }
  12845. }
  12846. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12847. internalTexture._cachedWrapV = texture.wrapV;
  12848. switch (texture.wrapV) {
  12849. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12850. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12851. break;
  12852. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12853. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12854. break;
  12855. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12856. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12857. break;
  12858. }
  12859. }
  12860. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  12861. internalTexture._cachedWrapR = texture.wrapR;
  12862. switch (texture.wrapV) {
  12863. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12864. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  12865. break;
  12866. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12867. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  12868. break;
  12869. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12870. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  12871. break;
  12872. }
  12873. }
  12874. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  12875. }
  12876. else if (internalTexture && internalTexture.isCube) {
  12877. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  12878. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  12879. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  12880. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  12881. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12882. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12883. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12884. }
  12885. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12886. }
  12887. else {
  12888. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12889. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12890. internalTexture._cachedWrapU = texture.wrapU;
  12891. switch (texture.wrapU) {
  12892. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12893. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12894. break;
  12895. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12896. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12897. break;
  12898. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12899. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12900. break;
  12901. }
  12902. }
  12903. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12904. internalTexture._cachedWrapV = texture.wrapV;
  12905. switch (texture.wrapV) {
  12906. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12907. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12908. break;
  12909. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12910. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12911. break;
  12912. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12913. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12914. break;
  12915. }
  12916. }
  12917. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12918. }
  12919. return true;
  12920. };
  12921. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12922. if (channel < 0 || !uniform) {
  12923. return;
  12924. }
  12925. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12926. this._textureUnits = new Int32Array(textures.length);
  12927. }
  12928. for (var i = 0; i < textures.length; i++) {
  12929. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12930. }
  12931. this._gl.uniform1iv(uniform, this._textureUnits);
  12932. for (var index = 0; index < textures.length; index++) {
  12933. this._setTexture(this._textureUnits[index], textures[index], true);
  12934. }
  12935. };
  12936. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12937. var internalTexture = texture.getInternalTexture();
  12938. if (!internalTexture) {
  12939. return;
  12940. }
  12941. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12942. var value = texture.anisotropicFilteringLevel;
  12943. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12944. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12945. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12946. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12947. }
  12948. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12949. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12950. internalTexture._cachedAnisotropicFilteringLevel = value;
  12951. }
  12952. };
  12953. Engine.prototype.readPixels = function (x, y, width, height) {
  12954. var data = new Uint8Array(height * width * 4);
  12955. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12956. return data;
  12957. };
  12958. /**
  12959. * Add an externaly attached data from its key.
  12960. * This method call will fail and return false, if such key already exists.
  12961. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12962. * @param key the unique key that identifies the data
  12963. * @param data the data object to associate to the key for this Engine instance
  12964. * @return true if no such key were already present and the data was added successfully, false otherwise
  12965. */
  12966. Engine.prototype.addExternalData = function (key, data) {
  12967. if (!this._externalData) {
  12968. this._externalData = new BABYLON.StringDictionary();
  12969. }
  12970. return this._externalData.add(key, data);
  12971. };
  12972. /**
  12973. * Get an externaly attached data from its key
  12974. * @param key the unique key that identifies the data
  12975. * @return the associated data, if present (can be null), or undefined if not present
  12976. */
  12977. Engine.prototype.getExternalData = function (key) {
  12978. if (!this._externalData) {
  12979. this._externalData = new BABYLON.StringDictionary();
  12980. }
  12981. return this._externalData.get(key);
  12982. };
  12983. /**
  12984. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12985. * @param key the unique key that identifies the data
  12986. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12987. * @return the associated data, can be null if the factory returned null.
  12988. */
  12989. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12990. if (!this._externalData) {
  12991. this._externalData = new BABYLON.StringDictionary();
  12992. }
  12993. return this._externalData.getOrAddWithFactory(key, factory);
  12994. };
  12995. /**
  12996. * Remove an externaly attached data from the Engine instance
  12997. * @param key the unique key that identifies the data
  12998. * @return true if the data was successfully removed, false if it doesn't exist
  12999. */
  13000. Engine.prototype.removeExternalData = function (key) {
  13001. if (!this._externalData) {
  13002. this._externalData = new BABYLON.StringDictionary();
  13003. }
  13004. return this._externalData.remove(key);
  13005. };
  13006. Engine.prototype.unbindAllAttributes = function () {
  13007. if (this._mustWipeVertexAttributes) {
  13008. this._mustWipeVertexAttributes = false;
  13009. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  13010. this._gl.disableVertexAttribArray(i);
  13011. this._vertexAttribArraysEnabled[i] = false;
  13012. this._currentBufferPointers[i].active = false;
  13013. }
  13014. return;
  13015. }
  13016. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  13017. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  13018. continue;
  13019. }
  13020. this._gl.disableVertexAttribArray(i);
  13021. this._vertexAttribArraysEnabled[i] = false;
  13022. this._currentBufferPointers[i].active = false;
  13023. }
  13024. };
  13025. Engine.prototype.releaseEffects = function () {
  13026. for (var name in this._compiledEffects) {
  13027. this._deleteProgram(this._compiledEffects[name]._program);
  13028. }
  13029. this._compiledEffects = {};
  13030. };
  13031. // Dispose
  13032. Engine.prototype.dispose = function () {
  13033. this.hideLoadingUI();
  13034. this.stopRenderLoop();
  13035. // Release postProcesses
  13036. while (this.postProcesses.length) {
  13037. this.postProcesses[0].dispose();
  13038. }
  13039. // Empty texture
  13040. if (this._emptyTexture) {
  13041. this._releaseTexture(this._emptyTexture);
  13042. this._emptyTexture = null;
  13043. }
  13044. if (this._emptyCubeTexture) {
  13045. this._releaseTexture(this._emptyCubeTexture);
  13046. this._emptyCubeTexture = null;
  13047. }
  13048. // Rescale PP
  13049. if (this._rescalePostProcess) {
  13050. this._rescalePostProcess.dispose();
  13051. }
  13052. // Release scenes
  13053. while (this.scenes.length) {
  13054. this.scenes[0].dispose();
  13055. }
  13056. // Release audio engine
  13057. if (Engine.audioEngine) {
  13058. Engine.audioEngine.dispose();
  13059. }
  13060. // Release effects
  13061. this.releaseEffects();
  13062. // Unbind
  13063. this.unbindAllAttributes();
  13064. if (this._dummyFramebuffer) {
  13065. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  13066. }
  13067. //WebVR
  13068. this.disableVR();
  13069. // Events
  13070. if (BABYLON.Tools.IsWindowObjectExist()) {
  13071. window.removeEventListener("blur", this._onBlur);
  13072. window.removeEventListener("focus", this._onFocus);
  13073. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  13074. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  13075. if (this._renderingCanvas) {
  13076. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  13077. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  13078. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  13079. if (!this._doNotHandleContextLost) {
  13080. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  13081. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  13082. }
  13083. }
  13084. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  13085. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  13086. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  13087. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  13088. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  13089. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  13090. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  13091. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  13092. if (this._onVrDisplayConnect) {
  13093. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13094. if (this._onVrDisplayDisconnect) {
  13095. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13096. }
  13097. if (this._onVrDisplayPresentChange) {
  13098. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13099. }
  13100. this._onVrDisplayConnect = null;
  13101. this._onVrDisplayDisconnect = null;
  13102. }
  13103. }
  13104. // Remove from Instances
  13105. var index = Engine.Instances.indexOf(this);
  13106. if (index >= 0) {
  13107. delete Engine.Instances[index];
  13108. }
  13109. this._workingCanvas = null;
  13110. this._workingContext = null;
  13111. this._currentBufferPointers = [];
  13112. this._renderingCanvas = null;
  13113. this._currentProgram = null;
  13114. this.onResizeObservable.clear();
  13115. this.onCanvasBlurObservable.clear();
  13116. this.onCanvasFocusObservable.clear();
  13117. this.onCanvasPointerOutObservable.clear();
  13118. this.onBeginFrameObservable.clear();
  13119. this.onEndFrameObservable.clear();
  13120. BABYLON.Effect.ResetCache();
  13121. // Abort active requests
  13122. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  13123. var request = _a[_i];
  13124. request.abort();
  13125. }
  13126. };
  13127. // Loading screen
  13128. Engine.prototype.displayLoadingUI = function () {
  13129. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13130. return;
  13131. }
  13132. var loadingScreen = this.loadingScreen;
  13133. if (loadingScreen) {
  13134. loadingScreen.displayLoadingUI();
  13135. }
  13136. };
  13137. Engine.prototype.hideLoadingUI = function () {
  13138. if (!BABYLON.Tools.IsWindowObjectExist()) {
  13139. return;
  13140. }
  13141. var loadingScreen = this.loadingScreen;
  13142. if (loadingScreen) {
  13143. loadingScreen.hideLoadingUI();
  13144. }
  13145. };
  13146. Object.defineProperty(Engine.prototype, "loadingScreen", {
  13147. get: function () {
  13148. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  13149. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  13150. return this._loadingScreen;
  13151. },
  13152. set: function (loadingScreen) {
  13153. this._loadingScreen = loadingScreen;
  13154. },
  13155. enumerable: true,
  13156. configurable: true
  13157. });
  13158. Object.defineProperty(Engine.prototype, "loadingUIText", {
  13159. set: function (text) {
  13160. this.loadingScreen.loadingUIText = text;
  13161. },
  13162. enumerable: true,
  13163. configurable: true
  13164. });
  13165. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  13166. set: function (color) {
  13167. this.loadingScreen.loadingUIBackgroundColor = color;
  13168. },
  13169. enumerable: true,
  13170. configurable: true
  13171. });
  13172. Engine.prototype.attachContextLostEvent = function (callback) {
  13173. if (this._renderingCanvas) {
  13174. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  13175. }
  13176. };
  13177. Engine.prototype.attachContextRestoredEvent = function (callback) {
  13178. if (this._renderingCanvas) {
  13179. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  13180. }
  13181. };
  13182. Engine.prototype.getVertexShaderSource = function (program) {
  13183. var shaders = this._gl.getAttachedShaders(program);
  13184. if (!shaders) {
  13185. return null;
  13186. }
  13187. return this._gl.getShaderSource(shaders[0]);
  13188. };
  13189. Engine.prototype.getFragmentShaderSource = function (program) {
  13190. var shaders = this._gl.getAttachedShaders(program);
  13191. if (!shaders) {
  13192. return null;
  13193. }
  13194. return this._gl.getShaderSource(shaders[1]);
  13195. };
  13196. Engine.prototype.getError = function () {
  13197. return this._gl.getError();
  13198. };
  13199. // FPS
  13200. Engine.prototype.getFps = function () {
  13201. return this._fps;
  13202. };
  13203. Engine.prototype.getDeltaTime = function () {
  13204. return this._deltaTime;
  13205. };
  13206. Engine.prototype._measureFps = function () {
  13207. this._performanceMonitor.sampleFrame();
  13208. this._fps = this._performanceMonitor.averageFPS;
  13209. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  13210. };
  13211. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  13212. if (faceIndex === void 0) { faceIndex = -1; }
  13213. var gl = this._gl;
  13214. if (!this._dummyFramebuffer) {
  13215. var dummy = gl.createFramebuffer();
  13216. if (!dummy) {
  13217. throw new Error("Unable to create dummy framebuffer");
  13218. }
  13219. this._dummyFramebuffer = dummy;
  13220. }
  13221. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  13222. if (faceIndex > -1) {
  13223. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13224. }
  13225. else {
  13226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13227. }
  13228. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  13229. var buffer;
  13230. switch (readType) {
  13231. case gl.UNSIGNED_BYTE:
  13232. buffer = new Uint8Array(4 * width * height);
  13233. readType = gl.UNSIGNED_BYTE;
  13234. break;
  13235. default:
  13236. buffer = new Float32Array(4 * width * height);
  13237. readType = gl.FLOAT;
  13238. break;
  13239. }
  13240. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  13241. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  13242. return buffer;
  13243. };
  13244. Engine.prototype._canRenderToFloatFramebuffer = function () {
  13245. if (this._webGLVersion > 1) {
  13246. return this._caps.colorBufferFloat;
  13247. }
  13248. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  13249. };
  13250. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  13251. if (this._webGLVersion > 1) {
  13252. return this._caps.colorBufferFloat;
  13253. }
  13254. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  13255. };
  13256. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  13257. Engine.prototype._canRenderToFramebuffer = function (type) {
  13258. var gl = this._gl;
  13259. //clear existing errors
  13260. while (gl.getError() !== gl.NO_ERROR) { }
  13261. var successful = true;
  13262. var texture = gl.createTexture();
  13263. gl.bindTexture(gl.TEXTURE_2D, texture);
  13264. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13267. var fb = gl.createFramebuffer();
  13268. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  13269. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  13270. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  13271. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  13272. successful = successful && (gl.getError() === gl.NO_ERROR);
  13273. //try render by clearing frame buffer's color buffer
  13274. if (successful) {
  13275. gl.clear(gl.COLOR_BUFFER_BIT);
  13276. successful = successful && (gl.getError() === gl.NO_ERROR);
  13277. }
  13278. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  13279. if (successful) {
  13280. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  13281. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13282. var readFormat = gl.RGBA;
  13283. var readType = gl.UNSIGNED_BYTE;
  13284. var buffer = new Uint8Array(4);
  13285. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  13286. successful = successful && (gl.getError() === gl.NO_ERROR);
  13287. }
  13288. //clean up
  13289. gl.deleteTexture(texture);
  13290. gl.deleteFramebuffer(fb);
  13291. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13292. //clear accumulated errors
  13293. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  13294. return successful;
  13295. };
  13296. Engine.prototype._getWebGLTextureType = function (type) {
  13297. if (type === Engine.TEXTURETYPE_FLOAT) {
  13298. return this._gl.FLOAT;
  13299. }
  13300. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13301. // Add Half Float Constant.
  13302. return this._gl.HALF_FLOAT_OES;
  13303. }
  13304. return this._gl.UNSIGNED_BYTE;
  13305. };
  13306. ;
  13307. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  13308. if (this._webGLVersion === 1) {
  13309. return this._gl.RGBA;
  13310. }
  13311. if (type === Engine.TEXTURETYPE_FLOAT) {
  13312. return this._gl.RGBA32F;
  13313. }
  13314. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13315. return this._gl.RGBA16F;
  13316. }
  13317. return this._gl.RGBA;
  13318. };
  13319. ;
  13320. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  13321. if (type === Engine.TEXTURETYPE_FLOAT) {
  13322. return this._gl.RGBA32F;
  13323. }
  13324. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  13325. return this._gl.RGBA16F;
  13326. }
  13327. return this._gl.RGBA8;
  13328. };
  13329. ;
  13330. Engine.prototype.createQuery = function () {
  13331. return this._gl.createQuery();
  13332. };
  13333. Engine.prototype.deleteQuery = function (query) {
  13334. this._gl.deleteQuery(query);
  13335. return this;
  13336. };
  13337. Engine.prototype.isQueryResultAvailable = function (query) {
  13338. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  13339. };
  13340. Engine.prototype.getQueryResult = function (query) {
  13341. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  13342. };
  13343. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  13344. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13345. this._gl.beginQuery(glAlgorithm, query);
  13346. return this;
  13347. };
  13348. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  13349. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  13350. this._gl.endQuery(glAlgorithm);
  13351. return this;
  13352. };
  13353. /* Time queries */
  13354. Engine.prototype._createTimeQuery = function () {
  13355. var timerQuery = this._caps.timerQuery;
  13356. if (timerQuery.createQueryEXT) {
  13357. return timerQuery.createQueryEXT();
  13358. }
  13359. return this.createQuery();
  13360. };
  13361. Engine.prototype._deleteTimeQuery = function (query) {
  13362. var timerQuery = this._caps.timerQuery;
  13363. if (timerQuery.deleteQueryEXT) {
  13364. timerQuery.deleteQueryEXT(query);
  13365. return;
  13366. }
  13367. this.deleteQuery(query);
  13368. };
  13369. Engine.prototype._getTimeQueryResult = function (query) {
  13370. var timerQuery = this._caps.timerQuery;
  13371. if (timerQuery.getQueryObjectEXT) {
  13372. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  13373. }
  13374. return this.getQueryResult(query);
  13375. };
  13376. Engine.prototype._getTimeQueryAvailability = function (query) {
  13377. var timerQuery = this._caps.timerQuery;
  13378. if (timerQuery.getQueryObjectEXT) {
  13379. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  13380. }
  13381. return this.isQueryResultAvailable(query);
  13382. };
  13383. Engine.prototype.startTimeQuery = function () {
  13384. var timerQuery = this._caps.timerQuery;
  13385. if (!timerQuery) {
  13386. return null;
  13387. }
  13388. var token = new BABYLON._TimeToken();
  13389. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13390. if (this._caps.canUseTimestampForTimerQuery) {
  13391. token._startTimeQuery = this._createTimeQuery();
  13392. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  13393. }
  13394. else {
  13395. if (this._currentNonTimestampToken) {
  13396. return this._currentNonTimestampToken;
  13397. }
  13398. token._timeElapsedQuery = this._createTimeQuery();
  13399. if (timerQuery.beginQueryEXT) {
  13400. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13401. }
  13402. else {
  13403. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  13404. }
  13405. this._currentNonTimestampToken = token;
  13406. }
  13407. return token;
  13408. };
  13409. Engine.prototype.endTimeQuery = function (token) {
  13410. var timerQuery = this._caps.timerQuery;
  13411. if (!timerQuery || !token) {
  13412. return -1;
  13413. }
  13414. if (this._caps.canUseTimestampForTimerQuery) {
  13415. if (!token._startTimeQuery) {
  13416. return -1;
  13417. }
  13418. if (!token._endTimeQuery) {
  13419. token._endTimeQuery = this._createTimeQuery();
  13420. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  13421. }
  13422. }
  13423. else if (!token._timeElapsedQueryEnded) {
  13424. if (!token._timeElapsedQuery) {
  13425. return -1;
  13426. }
  13427. if (timerQuery.endQueryEXT) {
  13428. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  13429. }
  13430. else {
  13431. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  13432. }
  13433. token._timeElapsedQueryEnded = true;
  13434. }
  13435. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  13436. var available = false;
  13437. if (token._endTimeQuery) {
  13438. available = this._getTimeQueryAvailability(token._endTimeQuery);
  13439. }
  13440. else if (token._timeElapsedQuery) {
  13441. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  13442. }
  13443. if (available && !disjoint) {
  13444. var result = 0;
  13445. if (this._caps.canUseTimestampForTimerQuery) {
  13446. if (!token._startTimeQuery || !token._endTimeQuery) {
  13447. return -1;
  13448. }
  13449. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  13450. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  13451. result = timeEnd - timeStart;
  13452. this._deleteTimeQuery(token._startTimeQuery);
  13453. this._deleteTimeQuery(token._endTimeQuery);
  13454. token._startTimeQuery = null;
  13455. token._endTimeQuery = null;
  13456. }
  13457. else {
  13458. if (!token._timeElapsedQuery) {
  13459. return -1;
  13460. }
  13461. result = this._getTimeQueryResult(token._timeElapsedQuery);
  13462. this._deleteTimeQuery(token._timeElapsedQuery);
  13463. token._timeElapsedQuery = null;
  13464. token._timeElapsedQueryEnded = false;
  13465. this._currentNonTimestampToken = null;
  13466. }
  13467. return result;
  13468. }
  13469. return -1;
  13470. };
  13471. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  13472. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  13473. };
  13474. // Transform feedback
  13475. Engine.prototype.createTransformFeedback = function () {
  13476. return this._gl.createTransformFeedback();
  13477. };
  13478. Engine.prototype.deleteTransformFeedback = function (value) {
  13479. this._gl.deleteTransformFeedback(value);
  13480. };
  13481. Engine.prototype.bindTransformFeedback = function (value) {
  13482. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  13483. };
  13484. Engine.prototype.beginTransformFeedback = function (usePoints) {
  13485. if (usePoints === void 0) { usePoints = true; }
  13486. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  13487. };
  13488. Engine.prototype.endTransformFeedback = function () {
  13489. this._gl.endTransformFeedback();
  13490. };
  13491. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  13492. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  13493. };
  13494. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  13495. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  13496. };
  13497. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  13498. var _this = this;
  13499. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  13500. this._activeRequests.push(request);
  13501. request.onCompleteObservable.add(function (request) {
  13502. delete _this._activeRequests[_this._activeRequests.indexOf(request)];
  13503. });
  13504. return request;
  13505. };
  13506. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  13507. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  13508. var onload = function (data) {
  13509. loadedFiles[index] = data;
  13510. loadedFiles._internalCount++;
  13511. if (loadedFiles._internalCount === 6) {
  13512. onfinish(loadedFiles);
  13513. }
  13514. };
  13515. var onerror = function (request, exception) {
  13516. if (onErrorCallBack && request) {
  13517. onErrorCallBack(request.status + " " + request.statusText, exception);
  13518. }
  13519. };
  13520. this._loadFile(url, onload, undefined, undefined, true, onerror);
  13521. };
  13522. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  13523. if (onError === void 0) { onError = null; }
  13524. var loadedFiles = [];
  13525. loadedFiles._internalCount = 0;
  13526. for (var index = 0; index < 6; index++) {
  13527. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  13528. }
  13529. };
  13530. // Statics
  13531. Engine.isSupported = function () {
  13532. try {
  13533. var tempcanvas = document.createElement("canvas");
  13534. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  13535. return gl != null && !!window.WebGLRenderingContext;
  13536. }
  13537. catch (e) {
  13538. return false;
  13539. }
  13540. };
  13541. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  13542. Engine.ExceptionList = [
  13543. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  13544. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  13545. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  13546. ];
  13547. Engine.Instances = new Array();
  13548. // Const statics
  13549. Engine._ALPHA_DISABLE = 0;
  13550. Engine._ALPHA_ADD = 1;
  13551. Engine._ALPHA_COMBINE = 2;
  13552. Engine._ALPHA_SUBTRACT = 3;
  13553. Engine._ALPHA_MULTIPLY = 4;
  13554. Engine._ALPHA_MAXIMIZED = 5;
  13555. Engine._ALPHA_ONEONE = 6;
  13556. Engine._ALPHA_PREMULTIPLIED = 7;
  13557. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  13558. Engine._ALPHA_INTERPOLATE = 9;
  13559. Engine._ALPHA_SCREENMODE = 10;
  13560. Engine._DELAYLOADSTATE_NONE = 0;
  13561. Engine._DELAYLOADSTATE_LOADED = 1;
  13562. Engine._DELAYLOADSTATE_LOADING = 2;
  13563. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  13564. Engine._TEXTUREFORMAT_ALPHA = 0;
  13565. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  13566. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  13567. Engine._TEXTUREFORMAT_RGB = 4;
  13568. Engine._TEXTUREFORMAT_RGBA = 5;
  13569. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  13570. Engine._TEXTURETYPE_FLOAT = 1;
  13571. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  13572. // Depht or Stencil test Constants.
  13573. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  13574. 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.
  13575. 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.
  13576. 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.
  13577. 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.
  13578. 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.
  13579. 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.
  13580. 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.
  13581. // Stencil Actions Constants.
  13582. Engine._KEEP = 0x1E00;
  13583. Engine._REPLACE = 0x1E01;
  13584. Engine._INCR = 0x1E02;
  13585. Engine._DECR = 0x1E03;
  13586. Engine._INVERT = 0x150A;
  13587. Engine._INCR_WRAP = 0x8507;
  13588. Engine._DECR_WRAP = 0x8508;
  13589. // Texture rescaling mode
  13590. Engine._SCALEMODE_FLOOR = 1;
  13591. Engine._SCALEMODE_NEAREST = 2;
  13592. Engine._SCALEMODE_CEILING = 3;
  13593. // Updatable statics so stick with vars here
  13594. Engine.CollisionsEpsilon = 0.001;
  13595. Engine.CodeRepository = "src/";
  13596. Engine.ShadersRepository = "src/Shaders/";
  13597. return Engine;
  13598. }());
  13599. BABYLON.Engine = Engine;
  13600. })(BABYLON || (BABYLON = {}));
  13601. //# sourceMappingURL=babylon.engine.js.map
  13602. var BABYLON;
  13603. (function (BABYLON) {
  13604. /**
  13605. * Node is the basic class for all scene objects (Mesh, Light Camera).
  13606. */
  13607. var Node = /** @class */ (function () {
  13608. /**
  13609. * @constructor
  13610. * @param {string} name - the name and id to be given to this node
  13611. * @param {BABYLON.Scene} the scene this node will be added to
  13612. */
  13613. function Node(name, scene) {
  13614. if (scene === void 0) { scene = null; }
  13615. this.state = "";
  13616. this.metadata = null;
  13617. this.doNotSerialize = false;
  13618. this.animations = new Array();
  13619. this._ranges = {};
  13620. this._isEnabled = true;
  13621. this._isReady = true;
  13622. this._currentRenderId = -1;
  13623. this._parentRenderId = -1;
  13624. /**
  13625. * An event triggered when the mesh is disposed.
  13626. * @type {BABYLON.Observable}
  13627. */
  13628. this.onDisposeObservable = new BABYLON.Observable();
  13629. // Behaviors
  13630. this._behaviors = new Array();
  13631. this.name = name;
  13632. this.id = name;
  13633. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  13634. this.uniqueId = this._scene.getUniqueId();
  13635. this._initCache();
  13636. }
  13637. Object.defineProperty(Node.prototype, "parent", {
  13638. get: function () {
  13639. return this._parentNode;
  13640. },
  13641. set: function (parent) {
  13642. if (this._parentNode === parent) {
  13643. return;
  13644. }
  13645. // Remove self from list of children of parent
  13646. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  13647. var index = this._parentNode._children.indexOf(this);
  13648. if (index !== -1) {
  13649. this._parentNode._children.splice(index, 1);
  13650. }
  13651. }
  13652. // Store new parent
  13653. this._parentNode = parent;
  13654. // Add as child to new parent
  13655. if (this._parentNode) {
  13656. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  13657. this._parentNode._children = new Array();
  13658. }
  13659. this._parentNode._children.push(this);
  13660. }
  13661. },
  13662. enumerable: true,
  13663. configurable: true
  13664. });
  13665. Node.prototype.getClassName = function () {
  13666. return "Node";
  13667. };
  13668. Object.defineProperty(Node.prototype, "onDispose", {
  13669. set: function (callback) {
  13670. if (this._onDisposeObserver) {
  13671. this.onDisposeObservable.remove(this._onDisposeObserver);
  13672. }
  13673. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  13674. },
  13675. enumerable: true,
  13676. configurable: true
  13677. });
  13678. Node.prototype.getScene = function () {
  13679. return this._scene;
  13680. };
  13681. Node.prototype.getEngine = function () {
  13682. return this._scene.getEngine();
  13683. };
  13684. Node.prototype.addBehavior = function (behavior) {
  13685. var _this = this;
  13686. var index = this._behaviors.indexOf(behavior);
  13687. if (index !== -1) {
  13688. return this;
  13689. }
  13690. behavior.init();
  13691. if (this._scene.isLoading) {
  13692. // We defer the attach when the scene will be loaded
  13693. var observer = this._scene.onDataLoadedObservable.add(function () {
  13694. behavior.attach(_this);
  13695. setTimeout(function () {
  13696. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  13697. _this._scene.onDataLoadedObservable.remove(observer);
  13698. }, 0);
  13699. });
  13700. }
  13701. else {
  13702. behavior.attach(this);
  13703. }
  13704. this._behaviors.push(behavior);
  13705. return this;
  13706. };
  13707. Node.prototype.removeBehavior = function (behavior) {
  13708. var index = this._behaviors.indexOf(behavior);
  13709. if (index === -1) {
  13710. return this;
  13711. }
  13712. this._behaviors[index].detach();
  13713. this._behaviors.splice(index, 1);
  13714. return this;
  13715. };
  13716. Object.defineProperty(Node.prototype, "behaviors", {
  13717. get: function () {
  13718. return this._behaviors;
  13719. },
  13720. enumerable: true,
  13721. configurable: true
  13722. });
  13723. Node.prototype.getBehaviorByName = function (name) {
  13724. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13725. var behavior = _a[_i];
  13726. if (behavior.name === name) {
  13727. return behavior;
  13728. }
  13729. }
  13730. return null;
  13731. };
  13732. // override it in derived class
  13733. Node.prototype.getWorldMatrix = function () {
  13734. return BABYLON.Matrix.Identity();
  13735. };
  13736. // override it in derived class if you add new variables to the cache
  13737. // and call the parent class method
  13738. Node.prototype._initCache = function () {
  13739. this._cache = {};
  13740. this._cache.parent = undefined;
  13741. };
  13742. Node.prototype.updateCache = function (force) {
  13743. if (!force && this.isSynchronized())
  13744. return;
  13745. this._cache.parent = this.parent;
  13746. this._updateCache();
  13747. };
  13748. // override it in derived class if you add new variables to the cache
  13749. // and call the parent class method if !ignoreParentClass
  13750. Node.prototype._updateCache = function (ignoreParentClass) {
  13751. };
  13752. // override it in derived class if you add new variables to the cache
  13753. Node.prototype._isSynchronized = function () {
  13754. return true;
  13755. };
  13756. Node.prototype._markSyncedWithParent = function () {
  13757. if (this.parent) {
  13758. this._parentRenderId = this.parent._currentRenderId;
  13759. }
  13760. };
  13761. Node.prototype.isSynchronizedWithParent = function () {
  13762. if (!this.parent) {
  13763. return true;
  13764. }
  13765. if (this._parentRenderId !== this.parent._currentRenderId) {
  13766. return false;
  13767. }
  13768. return this.parent.isSynchronized();
  13769. };
  13770. Node.prototype.isSynchronized = function (updateCache) {
  13771. var check = this.hasNewParent();
  13772. check = check || !this.isSynchronizedWithParent();
  13773. check = check || !this._isSynchronized();
  13774. if (updateCache)
  13775. this.updateCache(true);
  13776. return !check;
  13777. };
  13778. Node.prototype.hasNewParent = function (update) {
  13779. if (this._cache.parent === this.parent)
  13780. return false;
  13781. if (update)
  13782. this._cache.parent = this.parent;
  13783. return true;
  13784. };
  13785. /**
  13786. * Is this node ready to be used/rendered
  13787. * @return {boolean} is it ready
  13788. */
  13789. Node.prototype.isReady = function () {
  13790. return this._isReady;
  13791. };
  13792. /**
  13793. * Is this node enabled.
  13794. * 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.
  13795. * @param {boolean} [checkAncestors=true] - Indicates if this method should check the ancestors. The default is to check the ancestors. If set to false, the method will return the value of this node without checking ancestors.
  13796. * @return {boolean} whether this node (and its parent) is enabled.
  13797. * @see setEnabled
  13798. */
  13799. Node.prototype.isEnabled = function (checkAncestors) {
  13800. if (checkAncestors === void 0) { checkAncestors = true; }
  13801. if (checkAncestors === false) {
  13802. return this._isEnabled;
  13803. }
  13804. if (this._isEnabled === false) {
  13805. return false;
  13806. }
  13807. if (this.parent !== undefined && this.parent !== null) {
  13808. return this.parent.isEnabled(checkAncestors);
  13809. }
  13810. return true;
  13811. };
  13812. /**
  13813. * Set the enabled state of this node.
  13814. * @param {boolean} value - the new enabled state
  13815. * @see isEnabled
  13816. */
  13817. Node.prototype.setEnabled = function (value) {
  13818. this._isEnabled = value;
  13819. };
  13820. /**
  13821. * Is this node a descendant of the given node.
  13822. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  13823. * @param {BABYLON.Node} ancestor - The parent node to inspect
  13824. * @see parent
  13825. */
  13826. Node.prototype.isDescendantOf = function (ancestor) {
  13827. if (this.parent) {
  13828. if (this.parent === ancestor) {
  13829. return true;
  13830. }
  13831. return this.parent.isDescendantOf(ancestor);
  13832. }
  13833. return false;
  13834. };
  13835. /**
  13836. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  13837. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  13838. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  13839. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  13840. */
  13841. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  13842. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  13843. if (!this._children) {
  13844. return;
  13845. }
  13846. for (var index = 0; index < this._children.length; index++) {
  13847. var item = this._children[index];
  13848. if (!predicate || predicate(item)) {
  13849. results.push(item);
  13850. }
  13851. if (!directDescendantsOnly) {
  13852. item._getDescendants(results, false, predicate);
  13853. }
  13854. }
  13855. };
  13856. /**
  13857. * Will return all nodes that have this node as ascendant.
  13858. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  13859. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  13860. * @return {BABYLON.Node[]} all children nodes of all types.
  13861. */
  13862. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  13863. var results = new Array();
  13864. this._getDescendants(results, directDescendantsOnly, predicate);
  13865. return results;
  13866. };
  13867. /**
  13868. * Get all child-meshes of this node.
  13869. */
  13870. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  13871. var results = [];
  13872. this._getDescendants(results, directDescendantsOnly, function (node) {
  13873. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  13874. });
  13875. return results;
  13876. };
  13877. /**
  13878. * Get all child-transformNodes of this node.
  13879. */
  13880. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  13881. var results = [];
  13882. this._getDescendants(results, directDescendantsOnly, function (node) {
  13883. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  13884. });
  13885. return results;
  13886. };
  13887. /**
  13888. * Get all direct children of this node.
  13889. */
  13890. Node.prototype.getChildren = function (predicate) {
  13891. return this.getDescendants(true, predicate);
  13892. };
  13893. Node.prototype._setReady = function (state) {
  13894. if (state === this._isReady) {
  13895. return;
  13896. }
  13897. if (!state) {
  13898. this._isReady = false;
  13899. return;
  13900. }
  13901. this._isReady = true;
  13902. if (this.onReady) {
  13903. this.onReady(this);
  13904. }
  13905. };
  13906. Node.prototype.getAnimationByName = function (name) {
  13907. for (var i = 0; i < this.animations.length; i++) {
  13908. var animation = this.animations[i];
  13909. if (animation.name === name) {
  13910. return animation;
  13911. }
  13912. }
  13913. return null;
  13914. };
  13915. Node.prototype.createAnimationRange = function (name, from, to) {
  13916. // check name not already in use
  13917. if (!this._ranges[name]) {
  13918. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13919. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13920. if (this.animations[i]) {
  13921. this.animations[i].createRange(name, from, to);
  13922. }
  13923. }
  13924. }
  13925. };
  13926. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13927. if (deleteFrames === void 0) { deleteFrames = true; }
  13928. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13929. if (this.animations[i]) {
  13930. this.animations[i].deleteRange(name, deleteFrames);
  13931. }
  13932. }
  13933. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13934. };
  13935. Node.prototype.getAnimationRange = function (name) {
  13936. return this._ranges[name];
  13937. };
  13938. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13939. var range = this.getAnimationRange(name);
  13940. if (!range) {
  13941. return;
  13942. }
  13943. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13944. };
  13945. Node.prototype.serializeAnimationRanges = function () {
  13946. var serializationRanges = [];
  13947. for (var name in this._ranges) {
  13948. var localRange = this._ranges[name];
  13949. if (!localRange) {
  13950. continue;
  13951. }
  13952. var range = {};
  13953. range.name = name;
  13954. range.from = localRange.from;
  13955. range.to = localRange.to;
  13956. serializationRanges.push(range);
  13957. }
  13958. return serializationRanges;
  13959. };
  13960. // override it in derived class
  13961. Node.prototype.computeWorldMatrix = function (force) {
  13962. return BABYLON.Matrix.Identity();
  13963. };
  13964. Node.prototype.dispose = function () {
  13965. this.parent = null;
  13966. // Callback
  13967. this.onDisposeObservable.notifyObservers(this);
  13968. this.onDisposeObservable.clear();
  13969. // Behaviors
  13970. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13971. var behavior = _a[_i];
  13972. behavior.detach();
  13973. }
  13974. this._behaviors = [];
  13975. };
  13976. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13977. if (parsedNode.ranges) {
  13978. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13979. var data = parsedNode.ranges[index];
  13980. node.createAnimationRange(data.name, data.from, data.to);
  13981. }
  13982. }
  13983. };
  13984. __decorate([
  13985. BABYLON.serialize()
  13986. ], Node.prototype, "name", void 0);
  13987. __decorate([
  13988. BABYLON.serialize()
  13989. ], Node.prototype, "id", void 0);
  13990. __decorate([
  13991. BABYLON.serialize()
  13992. ], Node.prototype, "uniqueId", void 0);
  13993. __decorate([
  13994. BABYLON.serialize()
  13995. ], Node.prototype, "state", void 0);
  13996. __decorate([
  13997. BABYLON.serialize()
  13998. ], Node.prototype, "metadata", void 0);
  13999. return Node;
  14000. }());
  14001. BABYLON.Node = Node;
  14002. })(BABYLON || (BABYLON = {}));
  14003. //# sourceMappingURL=babylon.node.js.map
  14004. var BABYLON;
  14005. (function (BABYLON) {
  14006. var BoundingSphere = /** @class */ (function () {
  14007. function BoundingSphere(minimum, maximum) {
  14008. this.minimum = minimum;
  14009. this.maximum = maximum;
  14010. this._tempRadiusVector = BABYLON.Vector3.Zero();
  14011. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  14012. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  14013. this.radius = distance * 0.5;
  14014. this.centerWorld = BABYLON.Vector3.Zero();
  14015. this._update(BABYLON.Matrix.Identity());
  14016. }
  14017. // Methods
  14018. BoundingSphere.prototype._update = function (world) {
  14019. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  14020. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  14021. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  14022. };
  14023. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  14024. for (var i = 0; i < 6; i++) {
  14025. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  14026. return false;
  14027. }
  14028. return true;
  14029. };
  14030. BoundingSphere.prototype.intersectsPoint = function (point) {
  14031. var x = this.centerWorld.x - point.x;
  14032. var y = this.centerWorld.y - point.y;
  14033. var z = this.centerWorld.z - point.z;
  14034. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14035. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  14036. return false;
  14037. return true;
  14038. };
  14039. // Statics
  14040. BoundingSphere.Intersects = function (sphere0, sphere1) {
  14041. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  14042. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  14043. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  14044. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  14045. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  14046. return false;
  14047. return true;
  14048. };
  14049. return BoundingSphere;
  14050. }());
  14051. BABYLON.BoundingSphere = BoundingSphere;
  14052. })(BABYLON || (BABYLON = {}));
  14053. //# sourceMappingURL=babylon.boundingSphere.js.map
  14054. var BABYLON;
  14055. (function (BABYLON) {
  14056. var BoundingBox = /** @class */ (function () {
  14057. function BoundingBox(minimum, maximum) {
  14058. this.minimum = minimum;
  14059. this.maximum = maximum;
  14060. this.vectors = new Array();
  14061. this.vectorsWorld = new Array();
  14062. // Bounding vectors
  14063. this.vectors.push(this.minimum.clone());
  14064. this.vectors.push(this.maximum.clone());
  14065. this.vectors.push(this.minimum.clone());
  14066. this.vectors[2].x = this.maximum.x;
  14067. this.vectors.push(this.minimum.clone());
  14068. this.vectors[3].y = this.maximum.y;
  14069. this.vectors.push(this.minimum.clone());
  14070. this.vectors[4].z = this.maximum.z;
  14071. this.vectors.push(this.maximum.clone());
  14072. this.vectors[5].z = this.minimum.z;
  14073. this.vectors.push(this.maximum.clone());
  14074. this.vectors[6].x = this.minimum.x;
  14075. this.vectors.push(this.maximum.clone());
  14076. this.vectors[7].y = this.minimum.y;
  14077. // OBB
  14078. this.center = this.maximum.add(this.minimum).scale(0.5);
  14079. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  14080. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  14081. // World
  14082. for (var index = 0; index < this.vectors.length; index++) {
  14083. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  14084. }
  14085. this.minimumWorld = BABYLON.Vector3.Zero();
  14086. this.maximumWorld = BABYLON.Vector3.Zero();
  14087. this.centerWorld = BABYLON.Vector3.Zero();
  14088. this.extendSizeWorld = BABYLON.Vector3.Zero();
  14089. this._update(BABYLON.Matrix.Identity());
  14090. }
  14091. // Methods
  14092. BoundingBox.prototype.getWorldMatrix = function () {
  14093. return this._worldMatrix;
  14094. };
  14095. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  14096. this._worldMatrix.copyFrom(matrix);
  14097. return this;
  14098. };
  14099. BoundingBox.prototype._update = function (world) {
  14100. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  14101. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  14102. for (var index = 0; index < this.vectors.length; index++) {
  14103. var v = this.vectorsWorld[index];
  14104. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  14105. if (v.x < this.minimumWorld.x)
  14106. this.minimumWorld.x = v.x;
  14107. if (v.y < this.minimumWorld.y)
  14108. this.minimumWorld.y = v.y;
  14109. if (v.z < this.minimumWorld.z)
  14110. this.minimumWorld.z = v.z;
  14111. if (v.x > this.maximumWorld.x)
  14112. this.maximumWorld.x = v.x;
  14113. if (v.y > this.maximumWorld.y)
  14114. this.maximumWorld.y = v.y;
  14115. if (v.z > this.maximumWorld.z)
  14116. this.maximumWorld.z = v.z;
  14117. }
  14118. // Extend
  14119. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  14120. this.extendSizeWorld.scaleInPlace(0.5);
  14121. // OBB
  14122. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  14123. this.centerWorld.scaleInPlace(0.5);
  14124. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  14125. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  14126. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  14127. this._worldMatrix = world;
  14128. };
  14129. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  14130. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  14131. };
  14132. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14133. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  14134. };
  14135. BoundingBox.prototype.intersectsPoint = function (point) {
  14136. var delta = -BABYLON.Epsilon;
  14137. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  14138. return false;
  14139. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  14140. return false;
  14141. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  14142. return false;
  14143. return true;
  14144. };
  14145. BoundingBox.prototype.intersectsSphere = function (sphere) {
  14146. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  14147. };
  14148. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  14149. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  14150. return false;
  14151. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  14152. return false;
  14153. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  14154. return false;
  14155. return true;
  14156. };
  14157. // Statics
  14158. BoundingBox.Intersects = function (box0, box1) {
  14159. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  14160. return false;
  14161. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  14162. return false;
  14163. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  14164. return false;
  14165. return true;
  14166. };
  14167. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  14168. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  14169. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  14170. return (num <= (sphereRadius * sphereRadius));
  14171. };
  14172. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  14173. for (var p = 0; p < 6; p++) {
  14174. for (var i = 0; i < 8; i++) {
  14175. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14176. return false;
  14177. }
  14178. }
  14179. }
  14180. return true;
  14181. };
  14182. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  14183. for (var p = 0; p < 6; p++) {
  14184. var inCount = 8;
  14185. for (var i = 0; i < 8; i++) {
  14186. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  14187. --inCount;
  14188. }
  14189. else {
  14190. break;
  14191. }
  14192. }
  14193. if (inCount === 0)
  14194. return false;
  14195. }
  14196. return true;
  14197. };
  14198. return BoundingBox;
  14199. }());
  14200. BABYLON.BoundingBox = BoundingBox;
  14201. })(BABYLON || (BABYLON = {}));
  14202. //# sourceMappingURL=babylon.boundingBox.js.map
  14203. var BABYLON;
  14204. (function (BABYLON) {
  14205. var computeBoxExtents = function (axis, box) {
  14206. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  14207. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  14208. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  14209. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  14210. var r = r0 + r1 + r2;
  14211. return {
  14212. min: p - r,
  14213. max: p + r
  14214. };
  14215. };
  14216. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  14217. var axisOverlap = function (axis, box0, box1) {
  14218. var result0 = computeBoxExtents(axis, box0);
  14219. var result1 = computeBoxExtents(axis, box1);
  14220. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  14221. };
  14222. var BoundingInfo = /** @class */ (function () {
  14223. function BoundingInfo(minimum, maximum) {
  14224. this.minimum = minimum;
  14225. this.maximum = maximum;
  14226. this._isLocked = false;
  14227. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  14228. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  14229. }
  14230. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  14231. get: function () {
  14232. return this._isLocked;
  14233. },
  14234. set: function (value) {
  14235. this._isLocked = value;
  14236. },
  14237. enumerable: true,
  14238. configurable: true
  14239. });
  14240. // Methods
  14241. BoundingInfo.prototype.update = function (world) {
  14242. if (this._isLocked) {
  14243. return;
  14244. }
  14245. this.boundingBox._update(world);
  14246. this.boundingSphere._update(world);
  14247. };
  14248. /**
  14249. * Recreate the bounding info to be centered around a specific point given a specific extend.
  14250. * @param center New center of the bounding info
  14251. * @param extend New extend of the bounding info
  14252. */
  14253. BoundingInfo.prototype.centerOn = function (center, extend) {
  14254. this.minimum = center.subtract(extend);
  14255. this.maximum = center.add(extend);
  14256. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  14257. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  14258. return this;
  14259. };
  14260. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  14261. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  14262. return false;
  14263. return this.boundingBox.isInFrustum(frustumPlanes);
  14264. };
  14265. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  14266. /**
  14267. * Gets the world distance between the min and max points of the bounding box
  14268. */
  14269. get: function () {
  14270. var boundingBox = this.boundingBox;
  14271. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  14272. return size.length();
  14273. },
  14274. enumerable: true,
  14275. configurable: true
  14276. });
  14277. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  14278. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  14279. };
  14280. BoundingInfo.prototype._checkCollision = function (collider) {
  14281. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  14282. };
  14283. BoundingInfo.prototype.intersectsPoint = function (point) {
  14284. if (!this.boundingSphere.centerWorld) {
  14285. return false;
  14286. }
  14287. if (!this.boundingSphere.intersectsPoint(point)) {
  14288. return false;
  14289. }
  14290. if (!this.boundingBox.intersectsPoint(point)) {
  14291. return false;
  14292. }
  14293. return true;
  14294. };
  14295. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  14296. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  14297. return false;
  14298. }
  14299. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  14300. return false;
  14301. }
  14302. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  14303. return false;
  14304. }
  14305. if (!precise) {
  14306. return true;
  14307. }
  14308. var box0 = this.boundingBox;
  14309. var box1 = boundingInfo.boundingBox;
  14310. if (!axisOverlap(box0.directions[0], box0, box1))
  14311. return false;
  14312. if (!axisOverlap(box0.directions[1], box0, box1))
  14313. return false;
  14314. if (!axisOverlap(box0.directions[2], box0, box1))
  14315. return false;
  14316. if (!axisOverlap(box1.directions[0], box0, box1))
  14317. return false;
  14318. if (!axisOverlap(box1.directions[1], box0, box1))
  14319. return false;
  14320. if (!axisOverlap(box1.directions[2], box0, box1))
  14321. return false;
  14322. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  14323. return false;
  14324. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  14325. return false;
  14326. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  14327. return false;
  14328. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  14329. return false;
  14330. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  14331. return false;
  14332. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  14333. return false;
  14334. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  14335. return false;
  14336. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  14337. return false;
  14338. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  14339. return false;
  14340. return true;
  14341. };
  14342. return BoundingInfo;
  14343. }());
  14344. BABYLON.BoundingInfo = BoundingInfo;
  14345. })(BABYLON || (BABYLON = {}));
  14346. //# sourceMappingURL=babylon.boundingInfo.js.map
  14347. var BABYLON;
  14348. (function (BABYLON) {
  14349. var TransformNode = /** @class */ (function (_super) {
  14350. __extends(TransformNode, _super);
  14351. function TransformNode(name, scene, isPure) {
  14352. if (scene === void 0) { scene = null; }
  14353. if (isPure === void 0) { isPure = true; }
  14354. var _this = _super.call(this, name, scene) || this;
  14355. // Properties
  14356. _this._rotation = BABYLON.Vector3.Zero();
  14357. _this._scaling = BABYLON.Vector3.One();
  14358. _this._isDirty = false;
  14359. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  14360. _this.scalingDeterminant = 1;
  14361. _this.infiniteDistance = false;
  14362. _this.position = BABYLON.Vector3.Zero();
  14363. _this._localWorld = BABYLON.Matrix.Zero();
  14364. _this._worldMatrix = BABYLON.Matrix.Zero();
  14365. _this._worldMatrixDeterminant = 0;
  14366. _this._absolutePosition = BABYLON.Vector3.Zero();
  14367. _this._pivotMatrix = BABYLON.Matrix.Identity();
  14368. _this._postMultiplyPivotMatrix = false;
  14369. _this._isWorldMatrixFrozen = false;
  14370. /**
  14371. * An event triggered after the world matrix is updated
  14372. * @type {BABYLON.Observable}
  14373. */
  14374. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  14375. _this._nonUniformScaling = false;
  14376. if (isPure) {
  14377. _this.getScene().addTransformNode(_this);
  14378. }
  14379. return _this;
  14380. }
  14381. Object.defineProperty(TransformNode.prototype, "rotation", {
  14382. /**
  14383. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  14384. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  14385. * Default : (0.0, 0.0, 0.0)
  14386. */
  14387. get: function () {
  14388. return this._rotation;
  14389. },
  14390. set: function (newRotation) {
  14391. this._rotation = newRotation;
  14392. },
  14393. enumerable: true,
  14394. configurable: true
  14395. });
  14396. Object.defineProperty(TransformNode.prototype, "scaling", {
  14397. /**
  14398. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14399. * Default : (1.0, 1.0, 1.0)
  14400. */
  14401. get: function () {
  14402. return this._scaling;
  14403. },
  14404. /**
  14405. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14406. * Default : (1.0, 1.0, 1.0)
  14407. */
  14408. set: function (newScaling) {
  14409. this._scaling = newScaling;
  14410. },
  14411. enumerable: true,
  14412. configurable: true
  14413. });
  14414. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  14415. /**
  14416. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  14417. * It's null by default.
  14418. * 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)
  14419. */
  14420. get: function () {
  14421. return this._rotationQuaternion;
  14422. },
  14423. set: function (quaternion) {
  14424. this._rotationQuaternion = quaternion;
  14425. //reset the rotation vector.
  14426. if (quaternion && this.rotation.length()) {
  14427. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  14428. }
  14429. },
  14430. enumerable: true,
  14431. configurable: true
  14432. });
  14433. /**
  14434. * Returns the latest update of the World matrix
  14435. * Returns a Matrix.
  14436. */
  14437. TransformNode.prototype.getWorldMatrix = function () {
  14438. if (this._currentRenderId !== this.getScene().getRenderId()) {
  14439. this.computeWorldMatrix();
  14440. }
  14441. return this._worldMatrix;
  14442. };
  14443. /**
  14444. * Returns the latest update of the World matrix determinant.
  14445. */
  14446. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  14447. return this._worldMatrixDeterminant;
  14448. };
  14449. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  14450. /**
  14451. * Returns directly the latest state of the mesh World matrix.
  14452. * A Matrix is returned.
  14453. */
  14454. get: function () {
  14455. return this._worldMatrix;
  14456. },
  14457. enumerable: true,
  14458. configurable: true
  14459. });
  14460. /**
  14461. * Copies the paramater passed Matrix into the mesh Pose matrix.
  14462. * Returns the AbstractMesh.
  14463. */
  14464. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  14465. this._poseMatrix.copyFrom(matrix);
  14466. return this;
  14467. };
  14468. /**
  14469. * Returns the mesh Pose matrix.
  14470. * Returned object : Matrix
  14471. */
  14472. TransformNode.prototype.getPoseMatrix = function () {
  14473. return this._poseMatrix;
  14474. };
  14475. TransformNode.prototype._isSynchronized = function () {
  14476. if (this._isDirty) {
  14477. return false;
  14478. }
  14479. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  14480. return false;
  14481. if (this._cache.pivotMatrixUpdated) {
  14482. return false;
  14483. }
  14484. if (this.infiniteDistance) {
  14485. return false;
  14486. }
  14487. if (!this._cache.position.equals(this.position))
  14488. return false;
  14489. if (this.rotationQuaternion) {
  14490. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  14491. return false;
  14492. }
  14493. if (!this._cache.rotation.equals(this.rotation))
  14494. return false;
  14495. if (!this._cache.scaling.equals(this.scaling))
  14496. return false;
  14497. return true;
  14498. };
  14499. TransformNode.prototype._initCache = function () {
  14500. _super.prototype._initCache.call(this);
  14501. this._cache.localMatrixUpdated = false;
  14502. this._cache.position = BABYLON.Vector3.Zero();
  14503. this._cache.scaling = BABYLON.Vector3.Zero();
  14504. this._cache.rotation = BABYLON.Vector3.Zero();
  14505. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  14506. this._cache.billboardMode = -1;
  14507. };
  14508. TransformNode.prototype.markAsDirty = function (property) {
  14509. if (property === "rotation") {
  14510. this.rotationQuaternion = null;
  14511. }
  14512. this._currentRenderId = Number.MAX_VALUE;
  14513. this._isDirty = true;
  14514. return this;
  14515. };
  14516. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  14517. /**
  14518. * Returns the current mesh absolute position.
  14519. * Retuns a Vector3.
  14520. */
  14521. get: function () {
  14522. return this._absolutePosition;
  14523. },
  14524. enumerable: true,
  14525. configurable: true
  14526. });
  14527. /**
  14528. * Sets a new pivot matrix to the mesh.
  14529. * Returns the AbstractMesh.
  14530. */
  14531. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  14532. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  14533. this._pivotMatrix = matrix.clone();
  14534. this._cache.pivotMatrixUpdated = true;
  14535. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  14536. if (this._postMultiplyPivotMatrix) {
  14537. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  14538. }
  14539. return this;
  14540. };
  14541. /**
  14542. * Returns the mesh pivot matrix.
  14543. * Default : Identity.
  14544. * A Matrix is returned.
  14545. */
  14546. TransformNode.prototype.getPivotMatrix = function () {
  14547. return this._pivotMatrix;
  14548. };
  14549. /**
  14550. * Prevents the World matrix to be computed any longer.
  14551. * Returns the AbstractMesh.
  14552. */
  14553. TransformNode.prototype.freezeWorldMatrix = function () {
  14554. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  14555. this.computeWorldMatrix(true);
  14556. this._isWorldMatrixFrozen = true;
  14557. return this;
  14558. };
  14559. /**
  14560. * Allows back the World matrix computation.
  14561. * Returns the AbstractMesh.
  14562. */
  14563. TransformNode.prototype.unfreezeWorldMatrix = function () {
  14564. this._isWorldMatrixFrozen = false;
  14565. this.computeWorldMatrix(true);
  14566. return this;
  14567. };
  14568. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  14569. /**
  14570. * True if the World matrix has been frozen.
  14571. * Returns a boolean.
  14572. */
  14573. get: function () {
  14574. return this._isWorldMatrixFrozen;
  14575. },
  14576. enumerable: true,
  14577. configurable: true
  14578. });
  14579. /**
  14580. * Retuns the mesh absolute position in the World.
  14581. * Returns a Vector3.
  14582. */
  14583. TransformNode.prototype.getAbsolutePosition = function () {
  14584. this.computeWorldMatrix();
  14585. return this._absolutePosition;
  14586. };
  14587. /**
  14588. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  14589. * Returns the AbstractMesh.
  14590. */
  14591. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  14592. if (!absolutePosition) {
  14593. return this;
  14594. }
  14595. var absolutePositionX;
  14596. var absolutePositionY;
  14597. var absolutePositionZ;
  14598. if (absolutePosition.x === undefined) {
  14599. if (arguments.length < 3) {
  14600. return this;
  14601. }
  14602. absolutePositionX = arguments[0];
  14603. absolutePositionY = arguments[1];
  14604. absolutePositionZ = arguments[2];
  14605. }
  14606. else {
  14607. absolutePositionX = absolutePosition.x;
  14608. absolutePositionY = absolutePosition.y;
  14609. absolutePositionZ = absolutePosition.z;
  14610. }
  14611. if (this.parent) {
  14612. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14613. invertParentWorldMatrix.invert();
  14614. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  14615. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  14616. }
  14617. else {
  14618. this.position.x = absolutePositionX;
  14619. this.position.y = absolutePositionY;
  14620. this.position.z = absolutePositionZ;
  14621. }
  14622. return this;
  14623. };
  14624. /**
  14625. * Sets the mesh position in its local space.
  14626. * Returns the AbstractMesh.
  14627. */
  14628. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  14629. this.computeWorldMatrix();
  14630. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  14631. return this;
  14632. };
  14633. /**
  14634. * Returns the mesh position in the local space from the current World matrix values.
  14635. * Returns a new Vector3.
  14636. */
  14637. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  14638. this.computeWorldMatrix();
  14639. var invLocalWorldMatrix = this._localWorld.clone();
  14640. invLocalWorldMatrix.invert();
  14641. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  14642. };
  14643. /**
  14644. * Translates the mesh along the passed Vector3 in its local space.
  14645. * Returns the AbstractMesh.
  14646. */
  14647. TransformNode.prototype.locallyTranslate = function (vector3) {
  14648. this.computeWorldMatrix(true);
  14649. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  14650. return this;
  14651. };
  14652. /**
  14653. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  14654. * @param targetPoint the position (must be in same space as current mesh) to look at
  14655. * @param yawCor optional yaw (y-axis) correction in radians
  14656. * @param pitchCor optional pitch (x-axis) correction in radians
  14657. * @param rollCor optional roll (z-axis) correction in radians
  14658. * @param space the choosen space of the target
  14659. * @returns the TransformNode.
  14660. */
  14661. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  14662. if (yawCor === void 0) { yawCor = 0; }
  14663. if (pitchCor === void 0) { pitchCor = 0; }
  14664. if (rollCor === void 0) { rollCor = 0; }
  14665. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14666. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  14667. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  14668. targetPoint.subtractToRef(pos, dv);
  14669. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  14670. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  14671. var pitch = Math.atan2(dv.y, len);
  14672. if (this.rotationQuaternion) {
  14673. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  14674. }
  14675. else {
  14676. this.rotation.x = pitch + pitchCor;
  14677. this.rotation.y = yaw + yawCor;
  14678. this.rotation.z = rollCor;
  14679. }
  14680. return this;
  14681. };
  14682. /**
  14683. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  14684. * This Vector3 is expressed in the World space.
  14685. */
  14686. TransformNode.prototype.getDirection = function (localAxis) {
  14687. var result = BABYLON.Vector3.Zero();
  14688. this.getDirectionToRef(localAxis, result);
  14689. return result;
  14690. };
  14691. /**
  14692. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  14693. * localAxis is expressed in the mesh local space.
  14694. * result is computed in the Wordl space from the mesh World matrix.
  14695. * Returns the AbstractMesh.
  14696. */
  14697. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  14698. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14699. return this;
  14700. };
  14701. TransformNode.prototype.setPivotPoint = function (point, space) {
  14702. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  14703. if (this.getScene().getRenderId() == 0) {
  14704. this.computeWorldMatrix(true);
  14705. }
  14706. var wm = this.getWorldMatrix();
  14707. if (space == BABYLON.Space.WORLD) {
  14708. var tmat = BABYLON.Tmp.Matrix[0];
  14709. wm.invertToRef(tmat);
  14710. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  14711. }
  14712. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  14713. this._pivotMatrix.m[12] = -point.x;
  14714. this._pivotMatrix.m[13] = -point.y;
  14715. this._pivotMatrix.m[14] = -point.z;
  14716. this._cache.pivotMatrixUpdated = true;
  14717. return this;
  14718. };
  14719. /**
  14720. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  14721. */
  14722. TransformNode.prototype.getPivotPoint = function () {
  14723. var point = BABYLON.Vector3.Zero();
  14724. this.getPivotPointToRef(point);
  14725. return point;
  14726. };
  14727. /**
  14728. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  14729. * Returns the AbstractMesh.
  14730. */
  14731. TransformNode.prototype.getPivotPointToRef = function (result) {
  14732. result.x = -this._pivotMatrix.m[12];
  14733. result.y = -this._pivotMatrix.m[13];
  14734. result.z = -this._pivotMatrix.m[14];
  14735. return this;
  14736. };
  14737. /**
  14738. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  14739. */
  14740. TransformNode.prototype.getAbsolutePivotPoint = function () {
  14741. var point = BABYLON.Vector3.Zero();
  14742. this.getAbsolutePivotPointToRef(point);
  14743. return point;
  14744. };
  14745. /**
  14746. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  14747. * Returns the AbstractMesh.
  14748. */
  14749. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  14750. result.x = this._pivotMatrix.m[12];
  14751. result.y = this._pivotMatrix.m[13];
  14752. result.z = this._pivotMatrix.m[14];
  14753. this.getPivotPointToRef(result);
  14754. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  14755. return this;
  14756. };
  14757. /**
  14758. * Defines the passed node as the parent of the current node.
  14759. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  14760. * Returns the TransformNode.
  14761. */
  14762. TransformNode.prototype.setParent = function (node) {
  14763. if (node === null) {
  14764. var rotation = BABYLON.Tmp.Quaternion[0];
  14765. var position = BABYLON.Tmp.Vector3[0];
  14766. var scale = BABYLON.Tmp.Vector3[1];
  14767. if (this.parent && this.parent.computeWorldMatrix) {
  14768. this.parent.computeWorldMatrix(true);
  14769. }
  14770. this.computeWorldMatrix(true);
  14771. this.getWorldMatrix().decompose(scale, rotation, position);
  14772. if (this.rotationQuaternion) {
  14773. this.rotationQuaternion.copyFrom(rotation);
  14774. }
  14775. else {
  14776. rotation.toEulerAnglesToRef(this.rotation);
  14777. }
  14778. this.scaling.x = scale.x;
  14779. this.scaling.y = scale.y;
  14780. this.scaling.z = scale.z;
  14781. this.position.x = position.x;
  14782. this.position.y = position.y;
  14783. this.position.z = position.z;
  14784. }
  14785. else {
  14786. var rotation = BABYLON.Tmp.Quaternion[0];
  14787. var position = BABYLON.Tmp.Vector3[0];
  14788. var scale = BABYLON.Tmp.Vector3[1];
  14789. var diffMatrix = BABYLON.Tmp.Matrix[0];
  14790. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  14791. this.computeWorldMatrix(true);
  14792. node.computeWorldMatrix(true);
  14793. node.getWorldMatrix().invertToRef(invParentMatrix);
  14794. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  14795. diffMatrix.decompose(scale, rotation, position);
  14796. if (this.rotationQuaternion) {
  14797. this.rotationQuaternion.copyFrom(rotation);
  14798. }
  14799. else {
  14800. rotation.toEulerAnglesToRef(this.rotation);
  14801. }
  14802. this.position.x = position.x;
  14803. this.position.y = position.y;
  14804. this.position.z = position.z;
  14805. this.scaling.x = scale.x;
  14806. this.scaling.y = scale.y;
  14807. this.scaling.z = scale.z;
  14808. }
  14809. this.parent = node;
  14810. return this;
  14811. };
  14812. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  14813. get: function () {
  14814. return this._nonUniformScaling;
  14815. },
  14816. enumerable: true,
  14817. configurable: true
  14818. });
  14819. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  14820. if (this._nonUniformScaling === value) {
  14821. return false;
  14822. }
  14823. this._nonUniformScaling = true;
  14824. return true;
  14825. };
  14826. /**
  14827. * Attach the current TransformNode to another TransformNode associated with a bone
  14828. * @param bone Bone affecting the TransformNode
  14829. * @param affectedTransformNode TransformNode associated with the bone
  14830. */
  14831. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  14832. this._transformToBoneReferal = affectedTransformNode;
  14833. this.parent = bone;
  14834. if (bone.getWorldMatrix().determinant() < 0) {
  14835. this.scalingDeterminant *= -1;
  14836. }
  14837. return this;
  14838. };
  14839. TransformNode.prototype.detachFromBone = function () {
  14840. if (!this.parent) {
  14841. return this;
  14842. }
  14843. if (this.parent.getWorldMatrix().determinant() < 0) {
  14844. this.scalingDeterminant *= -1;
  14845. }
  14846. this._transformToBoneReferal = null;
  14847. this.parent = null;
  14848. return this;
  14849. };
  14850. /**
  14851. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  14852. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14853. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14854. * The passed axis is also normalized.
  14855. * Returns the AbstractMesh.
  14856. */
  14857. TransformNode.prototype.rotate = function (axis, amount, space) {
  14858. axis.normalize();
  14859. if (!this.rotationQuaternion) {
  14860. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14861. this.rotation = BABYLON.Vector3.Zero();
  14862. }
  14863. var rotationQuaternion;
  14864. if (!space || space === BABYLON.Space.LOCAL) {
  14865. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14866. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  14867. }
  14868. else {
  14869. if (this.parent) {
  14870. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  14871. invertParentWorldMatrix.invert();
  14872. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  14873. }
  14874. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  14875. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14876. }
  14877. return this;
  14878. };
  14879. /**
  14880. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  14881. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  14882. * The passed axis is also normalized.
  14883. * Returns the AbstractMesh.
  14884. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  14885. */
  14886. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  14887. axis.normalize();
  14888. if (!this.rotationQuaternion) {
  14889. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  14890. this.rotation.copyFromFloats(0, 0, 0);
  14891. }
  14892. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14893. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14894. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14895. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14896. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14897. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14898. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14899. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14900. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14901. return this;
  14902. };
  14903. /**
  14904. * Translates the mesh along the axis vector for the passed distance in the given space.
  14905. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14906. * Returns the AbstractMesh.
  14907. */
  14908. TransformNode.prototype.translate = function (axis, distance, space) {
  14909. var displacementVector = axis.scale(distance);
  14910. if (!space || space === BABYLON.Space.LOCAL) {
  14911. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14912. this.setPositionWithLocalVector(tempV3);
  14913. }
  14914. else {
  14915. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14916. }
  14917. return this;
  14918. };
  14919. /**
  14920. * Adds a rotation step to the mesh current rotation.
  14921. * x, y, z are Euler angles expressed in radians.
  14922. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14923. * This means this rotation is made in the mesh local space only.
  14924. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14925. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14926. * ```javascript
  14927. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14928. * ```
  14929. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14930. * 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.
  14931. * Returns the AbstractMesh.
  14932. */
  14933. TransformNode.prototype.addRotation = function (x, y, z) {
  14934. var rotationQuaternion;
  14935. if (this.rotationQuaternion) {
  14936. rotationQuaternion = this.rotationQuaternion;
  14937. }
  14938. else {
  14939. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14940. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14941. }
  14942. var accumulation = BABYLON.Tmp.Quaternion[0];
  14943. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14944. rotationQuaternion.multiplyInPlace(accumulation);
  14945. if (!this.rotationQuaternion) {
  14946. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14947. }
  14948. return this;
  14949. };
  14950. /**
  14951. * Computes the mesh World matrix and returns it.
  14952. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14953. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14954. * If the parameter `force`is set to `true`, the actual computation is done.
  14955. * Returns the mesh World Matrix.
  14956. */
  14957. TransformNode.prototype.computeWorldMatrix = function (force) {
  14958. if (this._isWorldMatrixFrozen) {
  14959. return this._worldMatrix;
  14960. }
  14961. if (!force && this.isSynchronized(true)) {
  14962. return this._worldMatrix;
  14963. }
  14964. this._cache.position.copyFrom(this.position);
  14965. this._cache.scaling.copyFrom(this.scaling);
  14966. this._cache.pivotMatrixUpdated = false;
  14967. this._cache.billboardMode = this.billboardMode;
  14968. this._currentRenderId = this.getScene().getRenderId();
  14969. this._isDirty = false;
  14970. // Scaling
  14971. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14972. // Rotation
  14973. //rotate, if quaternion is set and rotation was used
  14974. if (this.rotationQuaternion) {
  14975. var len = this.rotation.length();
  14976. if (len) {
  14977. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14978. this.rotation.copyFromFloats(0, 0, 0);
  14979. }
  14980. }
  14981. if (this.rotationQuaternion) {
  14982. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14983. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14984. }
  14985. else {
  14986. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14987. this._cache.rotation.copyFrom(this.rotation);
  14988. }
  14989. // Translation
  14990. var camera = this.getScene().activeCamera;
  14991. if (this.infiniteDistance && !this.parent && camera) {
  14992. var cameraWorldMatrix = camera.getWorldMatrix();
  14993. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14994. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14995. }
  14996. else {
  14997. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14998. }
  14999. // Composing transformations
  15000. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  15001. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15002. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  15003. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  15004. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  15005. // Need to decompose each rotation here
  15006. var currentPosition = BABYLON.Tmp.Vector3[3];
  15007. if (this.parent && this.parent.getWorldMatrix) {
  15008. if (this._transformToBoneReferal) {
  15009. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15010. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  15011. }
  15012. else {
  15013. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  15014. }
  15015. }
  15016. else {
  15017. currentPosition.copyFrom(this.position);
  15018. }
  15019. currentPosition.subtractInPlace(camera.globalPosition);
  15020. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  15021. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  15022. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  15023. }
  15024. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  15025. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  15026. }
  15027. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  15028. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  15029. }
  15030. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  15031. }
  15032. else {
  15033. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  15034. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  15035. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  15036. }
  15037. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  15038. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  15039. }
  15040. // Local world
  15041. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  15042. // Parent
  15043. if (this.parent && this.parent.getWorldMatrix) {
  15044. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  15045. if (this._transformToBoneReferal) {
  15046. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15047. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  15048. }
  15049. else {
  15050. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  15051. }
  15052. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  15053. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  15054. this._worldMatrix.copyFrom(this._localWorld);
  15055. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  15056. }
  15057. else {
  15058. if (this._transformToBoneReferal) {
  15059. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  15060. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  15061. }
  15062. else {
  15063. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  15064. }
  15065. }
  15066. this._markSyncedWithParent();
  15067. }
  15068. else {
  15069. this._worldMatrix.copyFrom(this._localWorld);
  15070. }
  15071. // Post multiply inverse of pivotMatrix
  15072. if (this._postMultiplyPivotMatrix) {
  15073. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  15074. }
  15075. // Normal matrix
  15076. if (this.scaling.isNonUniform) {
  15077. this._updateNonUniformScalingState(true);
  15078. }
  15079. else if (this.parent && this.parent._nonUniformScaling) {
  15080. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  15081. }
  15082. else {
  15083. this._updateNonUniformScalingState(false);
  15084. }
  15085. this._afterComputeWorldMatrix();
  15086. // Absolute position
  15087. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  15088. // Callbacks
  15089. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  15090. if (!this._poseMatrix) {
  15091. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  15092. }
  15093. // Cache the determinant
  15094. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  15095. return this._worldMatrix;
  15096. };
  15097. TransformNode.prototype._afterComputeWorldMatrix = function () {
  15098. };
  15099. /**
  15100. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  15101. * @param func: callback function to add
  15102. *
  15103. * Returns the TransformNode.
  15104. */
  15105. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  15106. this.onAfterWorldMatrixUpdateObservable.add(func);
  15107. return this;
  15108. };
  15109. /**
  15110. * Removes a registered callback function.
  15111. * Returns the TransformNode.
  15112. */
  15113. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  15114. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  15115. return this;
  15116. };
  15117. /**
  15118. * Clone the current transform node
  15119. * Returns the new transform node
  15120. * @param name Name of the new clone
  15121. * @param newParent New parent for the clone
  15122. * @param doNotCloneChildren Do not clone children hierarchy
  15123. */
  15124. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15125. var _this = this;
  15126. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  15127. result.name = name;
  15128. result.id = name;
  15129. if (newParent) {
  15130. result.parent = newParent;
  15131. }
  15132. if (!doNotCloneChildren) {
  15133. // Children
  15134. var directDescendants = this.getDescendants(true);
  15135. for (var index = 0; index < directDescendants.length; index++) {
  15136. var child = directDescendants[index];
  15137. if (child.clone) {
  15138. child.clone(name + "." + child.name, result);
  15139. }
  15140. }
  15141. }
  15142. return result;
  15143. };
  15144. TransformNode.prototype.serialize = function (currentSerializationObject) {
  15145. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  15146. serializationObject.type = this.getClassName();
  15147. // Parent
  15148. if (this.parent) {
  15149. serializationObject.parentId = this.parent.id;
  15150. }
  15151. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  15152. serializationObject.tags = BABYLON.Tags.GetTags(this);
  15153. }
  15154. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  15155. serializationObject.isEnabled = this.isEnabled();
  15156. // Parent
  15157. if (this.parent) {
  15158. serializationObject.parentId = this.parent.id;
  15159. }
  15160. return serializationObject;
  15161. };
  15162. // Statics
  15163. /**
  15164. * Returns a new TransformNode object parsed from the source provided.
  15165. * The parameter `parsedMesh` is the source.
  15166. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  15167. */
  15168. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  15169. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  15170. if (BABYLON.Tags) {
  15171. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  15172. }
  15173. if (parsedTransformNode.localMatrix) {
  15174. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  15175. }
  15176. else if (parsedTransformNode.pivotMatrix) {
  15177. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  15178. }
  15179. transformNode.setEnabled(parsedTransformNode.isEnabled);
  15180. // Parent
  15181. if (parsedTransformNode.parentId) {
  15182. transformNode._waitingParentId = parsedTransformNode.parentId;
  15183. }
  15184. return transformNode;
  15185. };
  15186. /**
  15187. * Disposes the TransformNode.
  15188. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15189. * Returns nothing.
  15190. */
  15191. TransformNode.prototype.dispose = function (doNotRecurse) {
  15192. // Animations
  15193. this.getScene().stopAnimation(this);
  15194. // Remove from scene
  15195. this.getScene().removeTransformNode(this);
  15196. if (!doNotRecurse) {
  15197. // Children
  15198. var objects = this.getDescendants(true);
  15199. for (var index = 0; index < objects.length; index++) {
  15200. objects[index].dispose();
  15201. }
  15202. }
  15203. else {
  15204. var childMeshes = this.getChildMeshes(true);
  15205. for (index = 0; index < childMeshes.length; index++) {
  15206. var child = childMeshes[index];
  15207. child.parent = null;
  15208. child.computeWorldMatrix(true);
  15209. }
  15210. }
  15211. this.onAfterWorldMatrixUpdateObservable.clear();
  15212. _super.prototype.dispose.call(this);
  15213. };
  15214. // Statics
  15215. TransformNode.BILLBOARDMODE_NONE = 0;
  15216. TransformNode.BILLBOARDMODE_X = 1;
  15217. TransformNode.BILLBOARDMODE_Y = 2;
  15218. TransformNode.BILLBOARDMODE_Z = 4;
  15219. TransformNode.BILLBOARDMODE_ALL = 7;
  15220. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  15221. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  15222. __decorate([
  15223. BABYLON.serializeAsVector3()
  15224. ], TransformNode.prototype, "_rotation", void 0);
  15225. __decorate([
  15226. BABYLON.serializeAsQuaternion()
  15227. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  15228. __decorate([
  15229. BABYLON.serializeAsVector3()
  15230. ], TransformNode.prototype, "_scaling", void 0);
  15231. __decorate([
  15232. BABYLON.serialize()
  15233. ], TransformNode.prototype, "billboardMode", void 0);
  15234. __decorate([
  15235. BABYLON.serialize()
  15236. ], TransformNode.prototype, "scalingDeterminant", void 0);
  15237. __decorate([
  15238. BABYLON.serialize()
  15239. ], TransformNode.prototype, "infiniteDistance", void 0);
  15240. __decorate([
  15241. BABYLON.serializeAsVector3()
  15242. ], TransformNode.prototype, "position", void 0);
  15243. return TransformNode;
  15244. }(BABYLON.Node));
  15245. BABYLON.TransformNode = TransformNode;
  15246. })(BABYLON || (BABYLON = {}));
  15247. //# sourceMappingURL=babylon.transformNode.js.map
  15248. var BABYLON;
  15249. (function (BABYLON) {
  15250. var AbstractMesh = /** @class */ (function (_super) {
  15251. __extends(AbstractMesh, _super);
  15252. // Constructor
  15253. function AbstractMesh(name, scene) {
  15254. if (scene === void 0) { scene = null; }
  15255. var _this = _super.call(this, name, scene, false) || this;
  15256. _this._facetNb = 0; // facet number
  15257. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  15258. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  15259. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  15260. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  15261. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  15262. _this._subDiv = {
  15263. max: 1,
  15264. X: 1,
  15265. Y: 1,
  15266. Z: 1
  15267. };
  15268. _this._facetDepthSort = false; // is the facet depth sort to be computed
  15269. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  15270. // Events
  15271. /**
  15272. * An event triggered when this mesh collides with another one
  15273. * @type {BABYLON.Observable}
  15274. */
  15275. _this.onCollideObservable = new BABYLON.Observable();
  15276. /**
  15277. * An event triggered when the collision's position changes
  15278. * @type {BABYLON.Observable}
  15279. */
  15280. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  15281. /**
  15282. * An event triggered when material is changed
  15283. * @type {BABYLON.Observable}
  15284. */
  15285. _this.onMaterialChangedObservable = new BABYLON.Observable();
  15286. // Properties
  15287. _this.definedFacingForward = true; // orientation for POV movement & rotation
  15288. /**
  15289. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  15290. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  15291. * or
  15292. * 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.
  15293. * for more info check WebGl documentations
  15294. */
  15295. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  15296. /**
  15297. * 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:
  15298. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  15299. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  15300. * 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.
  15301. */
  15302. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  15303. /**
  15304. * 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.
  15305. * The default value is -1 which means don't break the query and wait till the result.
  15306. */
  15307. _this.occlusionRetryCount = -1;
  15308. _this._occlusionInternalRetryCounter = 0;
  15309. _this._isOccluded = false;
  15310. _this._isOcclusionQueryInProgress = false;
  15311. _this.visibility = 1.0;
  15312. _this.alphaIndex = Number.MAX_VALUE;
  15313. _this.isVisible = true;
  15314. _this.isPickable = true;
  15315. _this.showBoundingBox = false;
  15316. _this.showSubMeshesBoundingBox = false;
  15317. _this.isBlocker = false;
  15318. _this.enablePointerMoveEvents = false;
  15319. _this.renderingGroupId = 0;
  15320. _this._receiveShadows = false;
  15321. _this.renderOutline = false;
  15322. _this.outlineColor = BABYLON.Color3.Red();
  15323. _this.outlineWidth = 0.02;
  15324. _this.renderOverlay = false;
  15325. _this.overlayColor = BABYLON.Color3.Red();
  15326. _this.overlayAlpha = 0.5;
  15327. _this._hasVertexAlpha = false;
  15328. _this._useVertexColors = true;
  15329. _this._computeBonesUsingShaders = true;
  15330. _this._numBoneInfluencers = 4;
  15331. _this._applyFog = true;
  15332. _this.useOctreeForRenderingSelection = true;
  15333. _this.useOctreeForPicking = true;
  15334. _this.useOctreeForCollisions = true;
  15335. _this._layerMask = 0x0FFFFFFF;
  15336. /**
  15337. * True if the mesh must be rendered in any case.
  15338. */
  15339. _this.alwaysSelectAsActiveMesh = false;
  15340. /**
  15341. * This scene's action manager
  15342. * @type {BABYLON.ActionManager}
  15343. */
  15344. _this.actionManager = null;
  15345. // Physics
  15346. _this.physicsImpostor = null;
  15347. // Collisions
  15348. _this._checkCollisions = false;
  15349. _this._collisionMask = -1;
  15350. _this._collisionGroup = -1;
  15351. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15352. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  15353. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15354. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  15355. // Edges
  15356. _this.edgesWidth = 1;
  15357. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  15358. // Cache
  15359. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  15360. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  15361. _this._isDisposed = false;
  15362. _this._renderId = 0;
  15363. _this._intersectionsInProgress = new Array();
  15364. _this._unIndexed = false;
  15365. _this._lightSources = new Array();
  15366. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15367. if (collidedMesh === void 0) { collidedMesh = null; }
  15368. //TODO move this to the collision coordinator!
  15369. if (_this.getScene().workerCollisions)
  15370. newPosition.multiplyInPlace(_this._collider._radius);
  15371. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  15372. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  15373. _this.position.addInPlace(_this._diffPositionForCollisions);
  15374. }
  15375. if (collidedMesh) {
  15376. _this.onCollideObservable.notifyObservers(collidedMesh);
  15377. }
  15378. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  15379. };
  15380. _this.getScene().addMesh(_this);
  15381. _this._resyncLightSources();
  15382. return _this;
  15383. }
  15384. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  15385. get: function () {
  15386. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  15387. },
  15388. enumerable: true,
  15389. configurable: true
  15390. });
  15391. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  15392. get: function () {
  15393. return BABYLON.TransformNode.BILLBOARDMODE_X;
  15394. },
  15395. enumerable: true,
  15396. configurable: true
  15397. });
  15398. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  15399. get: function () {
  15400. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  15401. },
  15402. enumerable: true,
  15403. configurable: true
  15404. });
  15405. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  15406. get: function () {
  15407. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  15408. },
  15409. enumerable: true,
  15410. configurable: true
  15411. });
  15412. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  15413. get: function () {
  15414. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  15415. },
  15416. enumerable: true,
  15417. configurable: true
  15418. });
  15419. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  15420. /**
  15421. * Read-only : the number of facets in the mesh
  15422. */
  15423. get: function () {
  15424. return this._facetNb;
  15425. },
  15426. enumerable: true,
  15427. configurable: true
  15428. });
  15429. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  15430. /**
  15431. * The number (integer) of subdivisions per axis in the partioning space
  15432. */
  15433. get: function () {
  15434. return this._partitioningSubdivisions;
  15435. },
  15436. set: function (nb) {
  15437. this._partitioningSubdivisions = nb;
  15438. },
  15439. enumerable: true,
  15440. configurable: true
  15441. });
  15442. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  15443. /**
  15444. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  15445. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  15446. */
  15447. get: function () {
  15448. return this._partitioningBBoxRatio;
  15449. },
  15450. set: function (ratio) {
  15451. this._partitioningBBoxRatio = ratio;
  15452. },
  15453. enumerable: true,
  15454. configurable: true
  15455. });
  15456. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  15457. /**
  15458. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  15459. * Works only for updatable meshes.
  15460. * Doesn't work with multi-materials.
  15461. */
  15462. get: function () {
  15463. return this._facetDepthSort;
  15464. },
  15465. set: function (sort) {
  15466. this._facetDepthSort = sort;
  15467. },
  15468. enumerable: true,
  15469. configurable: true
  15470. });
  15471. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  15472. /**
  15473. * The location (Vector3) where the facet depth sort must be computed from.
  15474. * By default, the active camera position.
  15475. * Used only when facet depth sort is enabled.
  15476. */
  15477. get: function () {
  15478. return this._facetDepthSortFrom;
  15479. },
  15480. set: function (location) {
  15481. this._facetDepthSortFrom = location;
  15482. },
  15483. enumerable: true,
  15484. configurable: true
  15485. });
  15486. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  15487. /**
  15488. * Read-only boolean : is the feature facetData enabled ?
  15489. */
  15490. get: function () {
  15491. return this._facetDataEnabled;
  15492. },
  15493. enumerable: true,
  15494. configurable: true
  15495. });
  15496. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  15497. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  15498. return false;
  15499. }
  15500. this._markSubMeshesAsMiscDirty();
  15501. return true;
  15502. };
  15503. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  15504. set: function (callback) {
  15505. if (this._onCollideObserver) {
  15506. this.onCollideObservable.remove(this._onCollideObserver);
  15507. }
  15508. this._onCollideObserver = this.onCollideObservable.add(callback);
  15509. },
  15510. enumerable: true,
  15511. configurable: true
  15512. });
  15513. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  15514. set: function (callback) {
  15515. if (this._onCollisionPositionChangeObserver) {
  15516. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  15517. }
  15518. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  15519. },
  15520. enumerable: true,
  15521. configurable: true
  15522. });
  15523. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  15524. /**
  15525. * 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.
  15526. */
  15527. get: function () {
  15528. return this._isOccluded;
  15529. },
  15530. set: function (value) {
  15531. this._isOccluded = value;
  15532. },
  15533. enumerable: true,
  15534. configurable: true
  15535. });
  15536. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  15537. /**
  15538. * Flag to check the progress status of the query
  15539. */
  15540. get: function () {
  15541. return this._isOcclusionQueryInProgress;
  15542. },
  15543. enumerable: true,
  15544. configurable: true
  15545. });
  15546. Object.defineProperty(AbstractMesh.prototype, "material", {
  15547. get: function () {
  15548. return this._material;
  15549. },
  15550. set: function (value) {
  15551. if (this._material === value) {
  15552. return;
  15553. }
  15554. this._material = value;
  15555. if (this.onMaterialChangedObservable.hasObservers) {
  15556. this.onMaterialChangedObservable.notifyObservers(this);
  15557. }
  15558. if (!this.subMeshes) {
  15559. return;
  15560. }
  15561. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15562. var subMesh = _a[_i];
  15563. subMesh.setEffect(null);
  15564. }
  15565. },
  15566. enumerable: true,
  15567. configurable: true
  15568. });
  15569. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  15570. get: function () {
  15571. return this._receiveShadows;
  15572. },
  15573. set: function (value) {
  15574. if (this._receiveShadows === value) {
  15575. return;
  15576. }
  15577. this._receiveShadows = value;
  15578. this._markSubMeshesAsLightDirty();
  15579. },
  15580. enumerable: true,
  15581. configurable: true
  15582. });
  15583. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  15584. get: function () {
  15585. return this._hasVertexAlpha;
  15586. },
  15587. set: function (value) {
  15588. if (this._hasVertexAlpha === value) {
  15589. return;
  15590. }
  15591. this._hasVertexAlpha = value;
  15592. this._markSubMeshesAsAttributesDirty();
  15593. },
  15594. enumerable: true,
  15595. configurable: true
  15596. });
  15597. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  15598. get: function () {
  15599. return this._useVertexColors;
  15600. },
  15601. set: function (value) {
  15602. if (this._useVertexColors === value) {
  15603. return;
  15604. }
  15605. this._useVertexColors = value;
  15606. this._markSubMeshesAsAttributesDirty();
  15607. },
  15608. enumerable: true,
  15609. configurable: true
  15610. });
  15611. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  15612. get: function () {
  15613. return this._computeBonesUsingShaders;
  15614. },
  15615. set: function (value) {
  15616. if (this._computeBonesUsingShaders === value) {
  15617. return;
  15618. }
  15619. this._computeBonesUsingShaders = value;
  15620. this._markSubMeshesAsAttributesDirty();
  15621. },
  15622. enumerable: true,
  15623. configurable: true
  15624. });
  15625. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  15626. get: function () {
  15627. return this._numBoneInfluencers;
  15628. },
  15629. set: function (value) {
  15630. if (this._numBoneInfluencers === value) {
  15631. return;
  15632. }
  15633. this._numBoneInfluencers = value;
  15634. this._markSubMeshesAsAttributesDirty();
  15635. },
  15636. enumerable: true,
  15637. configurable: true
  15638. });
  15639. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  15640. get: function () {
  15641. return this._applyFog;
  15642. },
  15643. set: function (value) {
  15644. if (this._applyFog === value) {
  15645. return;
  15646. }
  15647. this._applyFog = value;
  15648. this._markSubMeshesAsMiscDirty();
  15649. },
  15650. enumerable: true,
  15651. configurable: true
  15652. });
  15653. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  15654. get: function () {
  15655. return this._layerMask;
  15656. },
  15657. set: function (value) {
  15658. if (value === this._layerMask) {
  15659. return;
  15660. }
  15661. this._layerMask = value;
  15662. this._resyncLightSources();
  15663. },
  15664. enumerable: true,
  15665. configurable: true
  15666. });
  15667. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  15668. get: function () {
  15669. return this._collisionMask;
  15670. },
  15671. set: function (mask) {
  15672. this._collisionMask = !isNaN(mask) ? mask : -1;
  15673. },
  15674. enumerable: true,
  15675. configurable: true
  15676. });
  15677. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  15678. get: function () {
  15679. return this._collisionGroup;
  15680. },
  15681. set: function (mask) {
  15682. this._collisionGroup = !isNaN(mask) ? mask : -1;
  15683. },
  15684. enumerable: true,
  15685. configurable: true
  15686. });
  15687. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  15688. get: function () {
  15689. return null;
  15690. },
  15691. enumerable: true,
  15692. configurable: true
  15693. });
  15694. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  15695. get: function () {
  15696. return this._skeleton;
  15697. },
  15698. set: function (value) {
  15699. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  15700. this._skeleton._unregisterMeshWithPoseMatrix(this);
  15701. }
  15702. if (value && value.needInitialSkinMatrix) {
  15703. value._registerMeshWithPoseMatrix(this);
  15704. }
  15705. this._skeleton = value;
  15706. if (!this._skeleton) {
  15707. this._bonesTransformMatrices = null;
  15708. }
  15709. this._markSubMeshesAsAttributesDirty();
  15710. },
  15711. enumerable: true,
  15712. configurable: true
  15713. });
  15714. /**
  15715. * Boolean : true if the mesh has been disposed.
  15716. */
  15717. AbstractMesh.prototype.isDisposed = function () {
  15718. return this._isDisposed;
  15719. };
  15720. /**
  15721. * Returns the string "AbstractMesh"
  15722. */
  15723. AbstractMesh.prototype.getClassName = function () {
  15724. return "AbstractMesh";
  15725. };
  15726. /**
  15727. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  15728. */
  15729. AbstractMesh.prototype.toString = function (fullDetails) {
  15730. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  15731. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  15732. if (this._skeleton) {
  15733. ret += ", skeleton: " + this._skeleton.name;
  15734. }
  15735. if (fullDetails) {
  15736. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  15737. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  15738. }
  15739. return ret;
  15740. };
  15741. AbstractMesh.prototype._rebuild = function () {
  15742. if (this._occlusionQuery) {
  15743. this._occlusionQuery = null;
  15744. }
  15745. if (this._edgesRenderer) {
  15746. this._edgesRenderer._rebuild();
  15747. }
  15748. if (!this.subMeshes) {
  15749. return;
  15750. }
  15751. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15752. var subMesh = _a[_i];
  15753. subMesh._rebuild();
  15754. }
  15755. };
  15756. AbstractMesh.prototype._resyncLightSources = function () {
  15757. this._lightSources.length = 0;
  15758. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  15759. var light = _a[_i];
  15760. if (!light.isEnabled()) {
  15761. continue;
  15762. }
  15763. if (light.canAffectMesh(this)) {
  15764. this._lightSources.push(light);
  15765. }
  15766. }
  15767. this._markSubMeshesAsLightDirty();
  15768. };
  15769. AbstractMesh.prototype._resyncLighSource = function (light) {
  15770. var isIn = light.isEnabled() && light.canAffectMesh(this);
  15771. var index = this._lightSources.indexOf(light);
  15772. if (index === -1) {
  15773. if (!isIn) {
  15774. return;
  15775. }
  15776. this._lightSources.push(light);
  15777. }
  15778. else {
  15779. if (isIn) {
  15780. return;
  15781. }
  15782. this._lightSources.splice(index, 1);
  15783. }
  15784. this._markSubMeshesAsLightDirty();
  15785. };
  15786. AbstractMesh.prototype._removeLightSource = function (light) {
  15787. var index = this._lightSources.indexOf(light);
  15788. if (index === -1) {
  15789. return;
  15790. }
  15791. this._lightSources.splice(index, 1);
  15792. };
  15793. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  15794. if (!this.subMeshes) {
  15795. return;
  15796. }
  15797. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15798. var subMesh = _a[_i];
  15799. if (subMesh._materialDefines) {
  15800. func(subMesh._materialDefines);
  15801. }
  15802. }
  15803. };
  15804. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  15805. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  15806. };
  15807. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  15808. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  15809. };
  15810. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  15811. if (!this.subMeshes) {
  15812. return;
  15813. }
  15814. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  15815. var subMesh = _a[_i];
  15816. var material = subMesh.getMaterial();
  15817. if (material) {
  15818. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  15819. }
  15820. }
  15821. };
  15822. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  15823. /**
  15824. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15825. * Default : (1.0, 1.0, 1.0)
  15826. */
  15827. get: function () {
  15828. return this._scaling;
  15829. },
  15830. /**
  15831. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15832. * Default : (1.0, 1.0, 1.0)
  15833. */
  15834. set: function (newScaling) {
  15835. this._scaling = newScaling;
  15836. if (this.physicsImpostor) {
  15837. this.physicsImpostor.forceUpdate();
  15838. }
  15839. },
  15840. enumerable: true,
  15841. configurable: true
  15842. });
  15843. // Methods
  15844. /**
  15845. * Disables the mesh edger rendering mode.
  15846. * Returns the AbstractMesh.
  15847. */
  15848. AbstractMesh.prototype.disableEdgesRendering = function () {
  15849. if (this._edgesRenderer) {
  15850. this._edgesRenderer.dispose();
  15851. this._edgesRenderer = null;
  15852. }
  15853. return this;
  15854. };
  15855. /**
  15856. * Enables the edge rendering mode on the mesh.
  15857. * This mode makes the mesh edges visible.
  15858. * Returns the AbstractMesh.
  15859. */
  15860. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  15861. if (epsilon === void 0) { epsilon = 0.95; }
  15862. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  15863. this.disableEdgesRendering();
  15864. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  15865. return this;
  15866. };
  15867. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  15868. /**
  15869. * Returns true if the mesh is blocked. Used by the class Mesh.
  15870. * Returns the boolean `false` by default.
  15871. */
  15872. get: function () {
  15873. return false;
  15874. },
  15875. enumerable: true,
  15876. configurable: true
  15877. });
  15878. /**
  15879. * Returns the mesh itself by default, used by the class Mesh.
  15880. * Returned type : AbstractMesh
  15881. */
  15882. AbstractMesh.prototype.getLOD = function (camera) {
  15883. return this;
  15884. };
  15885. /**
  15886. * Returns 0 by default, used by the class Mesh.
  15887. * Returns an integer.
  15888. */
  15889. AbstractMesh.prototype.getTotalVertices = function () {
  15890. return 0;
  15891. };
  15892. /**
  15893. * Returns null by default, used by the class Mesh.
  15894. * Returned type : integer array
  15895. */
  15896. AbstractMesh.prototype.getIndices = function () {
  15897. return null;
  15898. };
  15899. /**
  15900. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15901. * Returned type : float array or Float32Array
  15902. */
  15903. AbstractMesh.prototype.getVerticesData = function (kind) {
  15904. return null;
  15905. };
  15906. /**
  15907. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15908. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15909. * The `data` are either a numeric array either a Float32Array.
  15910. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15911. * 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).
  15912. * Note that a new underlying VertexBuffer object is created each call.
  15913. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15914. *
  15915. * Possible `kind` values :
  15916. * - BABYLON.VertexBuffer.PositionKind
  15917. * - BABYLON.VertexBuffer.UVKind
  15918. * - BABYLON.VertexBuffer.UV2Kind
  15919. * - BABYLON.VertexBuffer.UV3Kind
  15920. * - BABYLON.VertexBuffer.UV4Kind
  15921. * - BABYLON.VertexBuffer.UV5Kind
  15922. * - BABYLON.VertexBuffer.UV6Kind
  15923. * - BABYLON.VertexBuffer.ColorKind
  15924. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15925. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15926. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15927. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15928. *
  15929. * Returns the Mesh.
  15930. */
  15931. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15932. return this;
  15933. };
  15934. /**
  15935. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15936. * If the mesh has no geometry, it is simply returned as it is.
  15937. * The `data` are either a numeric array either a Float32Array.
  15938. * No new underlying VertexBuffer object is created.
  15939. * 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.
  15940. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15941. *
  15942. * Possible `kind` values :
  15943. * - BABYLON.VertexBuffer.PositionKind
  15944. * - BABYLON.VertexBuffer.UVKind
  15945. * - BABYLON.VertexBuffer.UV2Kind
  15946. * - BABYLON.VertexBuffer.UV3Kind
  15947. * - BABYLON.VertexBuffer.UV4Kind
  15948. * - BABYLON.VertexBuffer.UV5Kind
  15949. * - BABYLON.VertexBuffer.UV6Kind
  15950. * - BABYLON.VertexBuffer.ColorKind
  15951. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15952. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15953. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15954. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15955. *
  15956. * Returns the Mesh.
  15957. */
  15958. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15959. return this;
  15960. };
  15961. /**
  15962. * Sets the mesh indices.
  15963. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15964. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15965. * This method creates a new index buffer each call.
  15966. * Returns the Mesh.
  15967. */
  15968. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15969. return this;
  15970. };
  15971. /** Returns false by default, used by the class Mesh.
  15972. * Returns a boolean
  15973. */
  15974. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15975. return false;
  15976. };
  15977. /**
  15978. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15979. * Returns a BoundingInfo
  15980. */
  15981. AbstractMesh.prototype.getBoundingInfo = function () {
  15982. if (this._masterMesh) {
  15983. return this._masterMesh.getBoundingInfo();
  15984. }
  15985. if (!this._boundingInfo) {
  15986. // this._boundingInfo is being created here
  15987. this._updateBoundingInfo();
  15988. }
  15989. // cannot be null.
  15990. return this._boundingInfo;
  15991. };
  15992. /**
  15993. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15994. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15995. */
  15996. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15997. if (includeDescendants === void 0) { includeDescendants = true; }
  15998. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15999. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  16000. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  16001. if (maxDimension === 0) {
  16002. return this;
  16003. }
  16004. var scale = 1 / maxDimension;
  16005. this.scaling.scaleInPlace(scale);
  16006. return this;
  16007. };
  16008. /**
  16009. * Sets a mesh new object BoundingInfo.
  16010. * Returns the AbstractMesh.
  16011. */
  16012. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  16013. this._boundingInfo = boundingInfo;
  16014. return this;
  16015. };
  16016. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  16017. get: function () {
  16018. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  16019. },
  16020. enumerable: true,
  16021. configurable: true
  16022. });
  16023. AbstractMesh.prototype._preActivate = function () {
  16024. };
  16025. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  16026. };
  16027. AbstractMesh.prototype._activate = function (renderId) {
  16028. this._renderId = renderId;
  16029. };
  16030. /**
  16031. * Returns the latest update of the World matrix
  16032. * Returns a Matrix.
  16033. */
  16034. AbstractMesh.prototype.getWorldMatrix = function () {
  16035. if (this._masterMesh) {
  16036. return this._masterMesh.getWorldMatrix();
  16037. }
  16038. return _super.prototype.getWorldMatrix.call(this);
  16039. };
  16040. /**
  16041. * Returns the latest update of the World matrix determinant.
  16042. */
  16043. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  16044. if (this._masterMesh) {
  16045. return this._masterMesh._getWorldMatrixDeterminant();
  16046. }
  16047. return _super.prototype._getWorldMatrixDeterminant.call(this);
  16048. };
  16049. // ================================== Point of View Movement =================================
  16050. /**
  16051. * Perform relative position change from the point of view of behind the front of the mesh.
  16052. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16053. * Supports definition of mesh facing forward or backward.
  16054. * @param {number} amountRight
  16055. * @param {number} amountUp
  16056. * @param {number} amountForward
  16057. *
  16058. * Returns the AbstractMesh.
  16059. */
  16060. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  16061. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  16062. return this;
  16063. };
  16064. /**
  16065. * Calculate relative position change from the point of view of behind the front of the mesh.
  16066. * This is performed taking into account the meshes current rotation, so you do not have to care.
  16067. * Supports definition of mesh facing forward or backward.
  16068. * @param {number} amountRight
  16069. * @param {number} amountUp
  16070. * @param {number} amountForward
  16071. *
  16072. * Returns a new Vector3.
  16073. */
  16074. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  16075. var rotMatrix = new BABYLON.Matrix();
  16076. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16077. rotQuaternion.toRotationMatrix(rotMatrix);
  16078. var translationDelta = BABYLON.Vector3.Zero();
  16079. var defForwardMult = this.definedFacingForward ? -1 : 1;
  16080. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  16081. return translationDelta;
  16082. };
  16083. // ================================== Point of View Rotation =================================
  16084. /**
  16085. * Perform relative rotation change from the point of view of behind the front of the mesh.
  16086. * Supports definition of mesh facing forward or backward.
  16087. * @param {number} flipBack
  16088. * @param {number} twirlClockwise
  16089. * @param {number} tiltRight
  16090. *
  16091. * Returns the AbstractMesh.
  16092. */
  16093. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16094. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  16095. return this;
  16096. };
  16097. /**
  16098. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  16099. * Supports definition of mesh facing forward or backward.
  16100. * @param {number} flipBack
  16101. * @param {number} twirlClockwise
  16102. * @param {number} tiltRight
  16103. *
  16104. * Returns a new Vector3.
  16105. */
  16106. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  16107. var defForwardMult = this.definedFacingForward ? 1 : -1;
  16108. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  16109. };
  16110. /**
  16111. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  16112. * @param includeDescendants Include bounding info from descendants as well (true by default).
  16113. */
  16114. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  16115. if (includeDescendants === void 0) { includeDescendants = true; }
  16116. this.computeWorldMatrix(true);
  16117. var min;
  16118. var max;
  16119. var boundingInfo = this.getBoundingInfo();
  16120. if (!this.subMeshes) {
  16121. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16122. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  16123. }
  16124. else {
  16125. min = boundingInfo.boundingBox.minimumWorld;
  16126. max = boundingInfo.boundingBox.maximumWorld;
  16127. }
  16128. if (includeDescendants) {
  16129. var descendants = this.getDescendants(false);
  16130. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  16131. var descendant = descendants_1[_i];
  16132. var childMesh = descendant;
  16133. childMesh.computeWorldMatrix(true);
  16134. //make sure we have the needed params to get mix and max
  16135. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  16136. continue;
  16137. }
  16138. var childBoundingInfo = childMesh.getBoundingInfo();
  16139. var boundingBox = childBoundingInfo.boundingBox;
  16140. var minBox = boundingBox.minimumWorld;
  16141. var maxBox = boundingBox.maximumWorld;
  16142. BABYLON.Tools.CheckExtends(minBox, min, max);
  16143. BABYLON.Tools.CheckExtends(maxBox, min, max);
  16144. }
  16145. }
  16146. return {
  16147. min: min,
  16148. max: max
  16149. };
  16150. };
  16151. /**
  16152. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  16153. * Returns the AbstractMesh.
  16154. */
  16155. AbstractMesh.prototype._updateBoundingInfo = function () {
  16156. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  16157. this._boundingInfo.update(this.worldMatrixFromCache);
  16158. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  16159. return this;
  16160. };
  16161. /**
  16162. * Update a mesh's children BoundingInfo objects only.
  16163. * Returns the AbstractMesh.
  16164. */
  16165. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  16166. if (!this.subMeshes) {
  16167. return this;
  16168. }
  16169. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  16170. var subMesh = this.subMeshes[subIndex];
  16171. if (!subMesh.IsGlobal) {
  16172. subMesh.updateBoundingInfo(matrix);
  16173. }
  16174. }
  16175. return this;
  16176. };
  16177. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  16178. // Bounding info
  16179. this._updateBoundingInfo();
  16180. };
  16181. /**
  16182. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  16183. * A mesh is in the frustum if its bounding box intersects the frustum.
  16184. * Boolean returned.
  16185. */
  16186. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  16187. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  16188. };
  16189. /**
  16190. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  16191. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  16192. * Boolean returned.
  16193. */
  16194. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16195. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  16196. ;
  16197. };
  16198. /**
  16199. * True if the mesh intersects another mesh or a SolidParticle object.
  16200. * 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)
  16201. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  16202. * Returns a boolean.
  16203. */
  16204. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  16205. if (precise === void 0) { precise = false; }
  16206. if (!this._boundingInfo || !mesh._boundingInfo) {
  16207. return false;
  16208. }
  16209. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  16210. return true;
  16211. }
  16212. if (includeDescendants) {
  16213. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  16214. var child = _a[_i];
  16215. if (child.intersectsMesh(mesh, precise, true)) {
  16216. return true;
  16217. }
  16218. }
  16219. }
  16220. return false;
  16221. };
  16222. /**
  16223. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  16224. * Returns a boolean.
  16225. */
  16226. AbstractMesh.prototype.intersectsPoint = function (point) {
  16227. if (!this._boundingInfo) {
  16228. return false;
  16229. }
  16230. return this._boundingInfo.intersectsPoint(point);
  16231. };
  16232. AbstractMesh.prototype.getPhysicsImpostor = function () {
  16233. return this.physicsImpostor;
  16234. };
  16235. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  16236. if (camera === void 0) { camera = null; }
  16237. if (!camera) {
  16238. camera = this.getScene().activeCamera;
  16239. }
  16240. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  16241. };
  16242. /**
  16243. * Returns the distance from the mesh to the active camera.
  16244. * Returns a float.
  16245. */
  16246. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  16247. if (camera === void 0) { camera = null; }
  16248. if (!camera) {
  16249. camera = this.getScene().activeCamera;
  16250. }
  16251. return this.absolutePosition.subtract(camera.position).length();
  16252. };
  16253. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  16254. if (!this.physicsImpostor) {
  16255. return this;
  16256. }
  16257. this.physicsImpostor.applyImpulse(force, contactPoint);
  16258. return this;
  16259. };
  16260. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  16261. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  16262. return this;
  16263. }
  16264. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  16265. mainPivot: pivot1,
  16266. connectedPivot: pivot2,
  16267. nativeParams: options
  16268. });
  16269. return this;
  16270. };
  16271. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  16272. // Collisions
  16273. /**
  16274. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  16275. * Default `false`.
  16276. */
  16277. get: function () {
  16278. return this._checkCollisions;
  16279. },
  16280. set: function (collisionEnabled) {
  16281. this._checkCollisions = collisionEnabled;
  16282. if (this.getScene().workerCollisions) {
  16283. this.getScene().collisionCoordinator.onMeshUpdated(this);
  16284. }
  16285. },
  16286. enumerable: true,
  16287. configurable: true
  16288. });
  16289. Object.defineProperty(AbstractMesh.prototype, "collider", {
  16290. /**
  16291. * Gets Collider object used to compute collisions (not physics)
  16292. */
  16293. get: function () {
  16294. return this._collider;
  16295. },
  16296. enumerable: true,
  16297. configurable: true
  16298. });
  16299. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  16300. var globalPosition = this.getAbsolutePosition();
  16301. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  16302. if (!this._collider) {
  16303. this._collider = new BABYLON.Collider();
  16304. }
  16305. this._collider._radius = this.ellipsoid;
  16306. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  16307. return this;
  16308. };
  16309. // Submeshes octree
  16310. /**
  16311. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  16312. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  16313. * Returns an Octree of submeshes.
  16314. */
  16315. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  16316. if (maxCapacity === void 0) { maxCapacity = 64; }
  16317. if (maxDepth === void 0) { maxDepth = 2; }
  16318. if (!this._submeshesOctree) {
  16319. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  16320. }
  16321. this.computeWorldMatrix(true);
  16322. var boundingInfo = this.getBoundingInfo();
  16323. // Update octree
  16324. var bbox = boundingInfo.boundingBox;
  16325. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  16326. return this._submeshesOctree;
  16327. };
  16328. // Collisions
  16329. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  16330. this._generatePointsArray();
  16331. if (!this._positions) {
  16332. return this;
  16333. }
  16334. // Transformation
  16335. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  16336. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  16337. subMesh._lastColliderWorldVertices = [];
  16338. subMesh._trianglePlanes = [];
  16339. var start = subMesh.verticesStart;
  16340. var end = (subMesh.verticesStart + subMesh.verticesCount);
  16341. for (var i = start; i < end; i++) {
  16342. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  16343. }
  16344. }
  16345. // Collide
  16346. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  16347. if (collider.collisionFound) {
  16348. collider.collidedMesh = this;
  16349. }
  16350. return this;
  16351. };
  16352. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  16353. var subMeshes;
  16354. var len;
  16355. // Octrees
  16356. if (this._submeshesOctree && this.useOctreeForCollisions) {
  16357. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  16358. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  16359. len = intersections.length;
  16360. subMeshes = intersections.data;
  16361. }
  16362. else {
  16363. subMeshes = this.subMeshes;
  16364. len = subMeshes.length;
  16365. }
  16366. for (var index = 0; index < len; index++) {
  16367. var subMesh = subMeshes[index];
  16368. // Bounding test
  16369. if (len > 1 && !subMesh._checkCollision(collider))
  16370. continue;
  16371. this._collideForSubMesh(subMesh, transformMatrix, collider);
  16372. }
  16373. return this;
  16374. };
  16375. AbstractMesh.prototype._checkCollision = function (collider) {
  16376. // Bounding box test
  16377. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  16378. return this;
  16379. // Transformation matrix
  16380. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  16381. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  16382. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  16383. return this;
  16384. };
  16385. // Picking
  16386. AbstractMesh.prototype._generatePointsArray = function () {
  16387. return false;
  16388. };
  16389. /**
  16390. * Checks if the passed Ray intersects with the mesh.
  16391. * Returns an object PickingInfo.
  16392. */
  16393. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  16394. var pickingInfo = new BABYLON.PickingInfo();
  16395. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  16396. return pickingInfo;
  16397. }
  16398. if (!this._generatePointsArray()) {
  16399. return pickingInfo;
  16400. }
  16401. var intersectInfo = null;
  16402. // Octrees
  16403. var subMeshes;
  16404. var len;
  16405. if (this._submeshesOctree && this.useOctreeForPicking) {
  16406. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  16407. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  16408. len = intersections.length;
  16409. subMeshes = intersections.data;
  16410. }
  16411. else {
  16412. subMeshes = this.subMeshes;
  16413. len = subMeshes.length;
  16414. }
  16415. for (var index = 0; index < len; index++) {
  16416. var subMesh = subMeshes[index];
  16417. // Bounding test
  16418. if (len > 1 && !subMesh.canIntersects(ray))
  16419. continue;
  16420. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  16421. if (currentIntersectInfo) {
  16422. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  16423. intersectInfo = currentIntersectInfo;
  16424. intersectInfo.subMeshId = index;
  16425. if (fastCheck) {
  16426. break;
  16427. }
  16428. }
  16429. }
  16430. }
  16431. if (intersectInfo) {
  16432. // Get picked point
  16433. var world = this.getWorldMatrix();
  16434. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  16435. var direction = ray.direction.clone();
  16436. direction = direction.scale(intersectInfo.distance);
  16437. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  16438. var pickedPoint = worldOrigin.add(worldDirection);
  16439. // Return result
  16440. pickingInfo.hit = true;
  16441. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  16442. pickingInfo.pickedPoint = pickedPoint;
  16443. pickingInfo.pickedMesh = this;
  16444. pickingInfo.bu = intersectInfo.bu || 0;
  16445. pickingInfo.bv = intersectInfo.bv || 0;
  16446. pickingInfo.faceId = intersectInfo.faceId;
  16447. pickingInfo.subMeshId = intersectInfo.subMeshId;
  16448. return pickingInfo;
  16449. }
  16450. return pickingInfo;
  16451. };
  16452. /**
  16453. * Clones the mesh, used by the class Mesh.
  16454. * Just returns `null` for an AbstractMesh.
  16455. */
  16456. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16457. return null;
  16458. };
  16459. /**
  16460. * Disposes all the mesh submeshes.
  16461. * Returns the AbstractMesh.
  16462. */
  16463. AbstractMesh.prototype.releaseSubMeshes = function () {
  16464. if (this.subMeshes) {
  16465. while (this.subMeshes.length) {
  16466. this.subMeshes[0].dispose();
  16467. }
  16468. }
  16469. else {
  16470. this.subMeshes = new Array();
  16471. }
  16472. return this;
  16473. };
  16474. /**
  16475. * Disposes the AbstractMesh.
  16476. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16477. * Returns nothing.
  16478. */
  16479. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16480. var _this = this;
  16481. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16482. var index;
  16483. // Action manager
  16484. if (this.actionManager !== undefined && this.actionManager !== null) {
  16485. this.actionManager.dispose();
  16486. this.actionManager = null;
  16487. }
  16488. // Skeleton
  16489. this.skeleton = null;
  16490. // Physics
  16491. if (this.physicsImpostor) {
  16492. this.physicsImpostor.dispose();
  16493. }
  16494. // Intersections in progress
  16495. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  16496. var other = this._intersectionsInProgress[index];
  16497. var pos = other._intersectionsInProgress.indexOf(this);
  16498. other._intersectionsInProgress.splice(pos, 1);
  16499. }
  16500. this._intersectionsInProgress = [];
  16501. // Lights
  16502. var lights = this.getScene().lights;
  16503. lights.forEach(function (light) {
  16504. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  16505. if (meshIndex !== -1) {
  16506. light.includedOnlyMeshes.splice(meshIndex, 1);
  16507. }
  16508. meshIndex = light.excludedMeshes.indexOf(_this);
  16509. if (meshIndex !== -1) {
  16510. light.excludedMeshes.splice(meshIndex, 1);
  16511. }
  16512. // Shadow generators
  16513. var generator = light.getShadowGenerator();
  16514. if (generator) {
  16515. var shadowMap = generator.getShadowMap();
  16516. if (shadowMap && shadowMap.renderList) {
  16517. meshIndex = shadowMap.renderList.indexOf(_this);
  16518. if (meshIndex !== -1) {
  16519. shadowMap.renderList.splice(meshIndex, 1);
  16520. }
  16521. }
  16522. }
  16523. });
  16524. // Edges
  16525. if (this._edgesRenderer) {
  16526. this._edgesRenderer.dispose();
  16527. this._edgesRenderer = null;
  16528. }
  16529. // SubMeshes
  16530. if (this.getClassName() !== "InstancedMesh") {
  16531. this.releaseSubMeshes();
  16532. }
  16533. // Octree
  16534. var sceneOctree = this.getScene().selectionOctree;
  16535. if (sceneOctree !== undefined && sceneOctree !== null) {
  16536. var index = sceneOctree.dynamicContent.indexOf(this);
  16537. if (index !== -1) {
  16538. sceneOctree.dynamicContent.splice(index, 1);
  16539. }
  16540. }
  16541. // Query
  16542. var engine = this.getScene().getEngine();
  16543. if (this._occlusionQuery) {
  16544. this._isOcclusionQueryInProgress = false;
  16545. engine.deleteQuery(this._occlusionQuery);
  16546. this._occlusionQuery = null;
  16547. }
  16548. // Engine
  16549. engine.wipeCaches();
  16550. // Remove from scene
  16551. this.getScene().removeMesh(this);
  16552. if (disposeMaterialAndTextures) {
  16553. if (this.material) {
  16554. this.material.dispose(false, true);
  16555. }
  16556. }
  16557. if (!doNotRecurse) {
  16558. // Particles
  16559. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  16560. if (this.getScene().particleSystems[index].emitter === this) {
  16561. this.getScene().particleSystems[index].dispose();
  16562. index--;
  16563. }
  16564. }
  16565. }
  16566. // facet data
  16567. if (this._facetDataEnabled) {
  16568. this.disableFacetData();
  16569. }
  16570. this.onAfterWorldMatrixUpdateObservable.clear();
  16571. this.onCollideObservable.clear();
  16572. this.onCollisionPositionChangeObservable.clear();
  16573. this._isDisposed = true;
  16574. _super.prototype.dispose.call(this, doNotRecurse);
  16575. };
  16576. /**
  16577. * Adds the passed mesh as a child to the current mesh.
  16578. * Returns the AbstractMesh.
  16579. */
  16580. AbstractMesh.prototype.addChild = function (mesh) {
  16581. mesh.setParent(this);
  16582. return this;
  16583. };
  16584. /**
  16585. * Removes the passed mesh from the current mesh children list.
  16586. * Returns the AbstractMesh.
  16587. */
  16588. AbstractMesh.prototype.removeChild = function (mesh) {
  16589. mesh.setParent(null);
  16590. return this;
  16591. };
  16592. // Facet data
  16593. /**
  16594. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  16595. * Returns the AbstractMesh.
  16596. */
  16597. AbstractMesh.prototype._initFacetData = function () {
  16598. if (!this._facetNormals) {
  16599. this._facetNormals = new Array();
  16600. }
  16601. if (!this._facetPositions) {
  16602. this._facetPositions = new Array();
  16603. }
  16604. if (!this._facetPartitioning) {
  16605. this._facetPartitioning = new Array();
  16606. }
  16607. this._facetNb = (this.getIndices().length / 3) | 0;
  16608. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  16609. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  16610. for (var f = 0; f < this._facetNb; f++) {
  16611. this._facetNormals[f] = BABYLON.Vector3.Zero();
  16612. this._facetPositions[f] = BABYLON.Vector3.Zero();
  16613. }
  16614. this._facetDataEnabled = true;
  16615. return this;
  16616. };
  16617. /**
  16618. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  16619. * This method can be called within the render loop.
  16620. * 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.
  16621. * Returns the AbstractMesh.
  16622. */
  16623. AbstractMesh.prototype.updateFacetData = function () {
  16624. if (!this._facetDataEnabled) {
  16625. this._initFacetData();
  16626. }
  16627. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16628. var indices = this.getIndices();
  16629. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16630. var bInfo = this.getBoundingInfo();
  16631. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  16632. // init arrays, matrix and sort function on first call
  16633. this._facetDepthSortEnabled = true;
  16634. if (indices instanceof Uint16Array) {
  16635. this._depthSortedIndices = new Uint16Array(indices);
  16636. }
  16637. else if (indices instanceof Uint32Array) {
  16638. this._depthSortedIndices = new Uint32Array(indices);
  16639. }
  16640. else {
  16641. var needs32bits = false;
  16642. for (var i = 0; i < indices.length; i++) {
  16643. if (indices[i] > 65535) {
  16644. needs32bits = true;
  16645. break;
  16646. }
  16647. }
  16648. if (needs32bits) {
  16649. this._depthSortedIndices = new Uint32Array(indices);
  16650. }
  16651. else {
  16652. this._depthSortedIndices = new Uint16Array(indices);
  16653. }
  16654. }
  16655. this._facetDepthSortFunction = function (f1, f2) {
  16656. return (f2.sqDistance - f1.sqDistance);
  16657. };
  16658. if (!this._facetDepthSortFrom) {
  16659. var camera = this.getScene().activeCamera;
  16660. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  16661. }
  16662. this._depthSortedFacets = [];
  16663. for (var f = 0; f < this._facetNb; f++) {
  16664. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  16665. this._depthSortedFacets.push(depthSortedFacet);
  16666. }
  16667. this._invertedMatrix = BABYLON.Matrix.Identity();
  16668. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  16669. }
  16670. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  16671. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  16672. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  16673. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  16674. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  16675. this._subDiv.max = this._partitioningSubdivisions;
  16676. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  16677. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  16678. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  16679. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  16680. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  16681. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  16682. // set the parameters for ComputeNormals()
  16683. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  16684. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  16685. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  16686. this._facetParameters.bInfo = bInfo;
  16687. this._facetParameters.bbSize = this._bbSize;
  16688. this._facetParameters.subDiv = this._subDiv;
  16689. this._facetParameters.ratio = this.partitioningBBoxRatio;
  16690. this._facetParameters.depthSort = this._facetDepthSort;
  16691. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16692. this.computeWorldMatrix(true);
  16693. this._worldMatrix.invertToRef(this._invertedMatrix);
  16694. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  16695. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  16696. }
  16697. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  16698. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  16699. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  16700. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  16701. var l = (this._depthSortedIndices.length / 3) | 0;
  16702. for (var f = 0; f < l; f++) {
  16703. var sind = this._depthSortedFacets[f].ind;
  16704. this._depthSortedIndices[f * 3] = indices[sind];
  16705. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  16706. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  16707. }
  16708. this.updateIndices(this._depthSortedIndices);
  16709. }
  16710. return this;
  16711. };
  16712. /**
  16713. * Returns the facetLocalNormals array.
  16714. * The normals are expressed in the mesh local space.
  16715. */
  16716. AbstractMesh.prototype.getFacetLocalNormals = function () {
  16717. if (!this._facetNormals) {
  16718. this.updateFacetData();
  16719. }
  16720. return this._facetNormals;
  16721. };
  16722. /**
  16723. * Returns the facetLocalPositions array.
  16724. * The facet positions are expressed in the mesh local space.
  16725. */
  16726. AbstractMesh.prototype.getFacetLocalPositions = function () {
  16727. if (!this._facetPositions) {
  16728. this.updateFacetData();
  16729. }
  16730. return this._facetPositions;
  16731. };
  16732. /**
  16733. * Returns the facetLocalPartioning array.
  16734. */
  16735. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  16736. if (!this._facetPartitioning) {
  16737. this.updateFacetData();
  16738. }
  16739. return this._facetPartitioning;
  16740. };
  16741. /**
  16742. * Returns the i-th facet position in the world system.
  16743. * This method allocates a new Vector3 per call.
  16744. */
  16745. AbstractMesh.prototype.getFacetPosition = function (i) {
  16746. var pos = BABYLON.Vector3.Zero();
  16747. this.getFacetPositionToRef(i, pos);
  16748. return pos;
  16749. };
  16750. /**
  16751. * Sets the reference Vector3 with the i-th facet position in the world system.
  16752. * Returns the AbstractMesh.
  16753. */
  16754. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  16755. var localPos = (this.getFacetLocalPositions())[i];
  16756. var world = this.getWorldMatrix();
  16757. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  16758. return this;
  16759. };
  16760. /**
  16761. * Returns the i-th facet normal in the world system.
  16762. * This method allocates a new Vector3 per call.
  16763. */
  16764. AbstractMesh.prototype.getFacetNormal = function (i) {
  16765. var norm = BABYLON.Vector3.Zero();
  16766. this.getFacetNormalToRef(i, norm);
  16767. return norm;
  16768. };
  16769. /**
  16770. * Sets the reference Vector3 with the i-th facet normal in the world system.
  16771. * Returns the AbstractMesh.
  16772. */
  16773. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  16774. var localNorm = (this.getFacetLocalNormals())[i];
  16775. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  16776. return this;
  16777. };
  16778. /**
  16779. * 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).
  16780. */
  16781. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  16782. var bInfo = this.getBoundingInfo();
  16783. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  16784. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  16785. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  16786. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  16787. return null;
  16788. }
  16789. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  16790. };
  16791. /**
  16792. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  16793. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  16794. * 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.
  16795. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16796. * 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.
  16797. */
  16798. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  16799. if (checkFace === void 0) { checkFace = false; }
  16800. if (facing === void 0) { facing = true; }
  16801. var world = this.getWorldMatrix();
  16802. var invMat = BABYLON.Tmp.Matrix[5];
  16803. world.invertToRef(invMat);
  16804. var invVect = BABYLON.Tmp.Vector3[8];
  16805. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  16806. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  16807. if (projected) {
  16808. // tranform the local computed projected vector to world coordinates
  16809. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  16810. }
  16811. return closest;
  16812. };
  16813. /**
  16814. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  16815. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  16816. * 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.
  16817. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  16818. * 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.
  16819. */
  16820. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  16821. if (checkFace === void 0) { checkFace = false; }
  16822. if (facing === void 0) { facing = true; }
  16823. var closest = null;
  16824. var tmpx = 0.0;
  16825. var tmpy = 0.0;
  16826. var tmpz = 0.0;
  16827. var d = 0.0; // tmp dot facet normal * facet position
  16828. var t0 = 0.0;
  16829. var projx = 0.0;
  16830. var projy = 0.0;
  16831. var projz = 0.0;
  16832. // Get all the facets in the same partitioning block than (x, y, z)
  16833. var facetPositions = this.getFacetLocalPositions();
  16834. var facetNormals = this.getFacetLocalNormals();
  16835. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  16836. if (!facetsInBlock) {
  16837. return null;
  16838. }
  16839. // Get the closest facet to (x, y, z)
  16840. var shortest = Number.MAX_VALUE; // init distance vars
  16841. var tmpDistance = shortest;
  16842. var fib; // current facet in the block
  16843. var norm; // current facet normal
  16844. var p0; // current facet barycenter position
  16845. // loop on all the facets in the current partitioning block
  16846. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  16847. fib = facetsInBlock[idx];
  16848. norm = facetNormals[fib];
  16849. p0 = facetPositions[fib];
  16850. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  16851. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  16852. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  16853. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  16854. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  16855. projx = x + norm.x * t0;
  16856. projy = y + norm.y * t0;
  16857. projz = z + norm.z * t0;
  16858. tmpx = projx - x;
  16859. tmpy = projy - y;
  16860. tmpz = projz - z;
  16861. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  16862. if (tmpDistance < shortest) {
  16863. shortest = tmpDistance;
  16864. closest = fib;
  16865. if (projected) {
  16866. projected.x = projx;
  16867. projected.y = projy;
  16868. projected.z = projz;
  16869. }
  16870. }
  16871. }
  16872. }
  16873. return closest;
  16874. };
  16875. /**
  16876. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  16877. */
  16878. AbstractMesh.prototype.getFacetDataParameters = function () {
  16879. return this._facetParameters;
  16880. };
  16881. /**
  16882. * Disables the feature FacetData and frees the related memory.
  16883. * Returns the AbstractMesh.
  16884. */
  16885. AbstractMesh.prototype.disableFacetData = function () {
  16886. if (this._facetDataEnabled) {
  16887. this._facetDataEnabled = false;
  16888. this._facetPositions = new Array();
  16889. this._facetNormals = new Array();
  16890. this._facetPartitioning = new Array();
  16891. this._facetParameters = null;
  16892. this._depthSortedIndices = new Uint32Array(0);
  16893. }
  16894. return this;
  16895. };
  16896. /**
  16897. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16898. * Returns the mesh.
  16899. */
  16900. AbstractMesh.prototype.updateIndices = function (indices) {
  16901. return this;
  16902. };
  16903. /**
  16904. * The mesh Geometry. Actually used by the Mesh object.
  16905. * Returns a blank geometry object.
  16906. */
  16907. /**
  16908. * Creates new normals data for the mesh.
  16909. * @param updatable.
  16910. */
  16911. AbstractMesh.prototype.createNormals = function (updatable) {
  16912. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16913. var indices = this.getIndices();
  16914. var normals;
  16915. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16916. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16917. }
  16918. else {
  16919. normals = [];
  16920. }
  16921. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16922. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16923. };
  16924. /**
  16925. * Align the mesh with a normal.
  16926. * Returns the mesh.
  16927. */
  16928. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16929. if (!upDirection) {
  16930. upDirection = BABYLON.Axis.Y;
  16931. }
  16932. var axisX = BABYLON.Tmp.Vector3[0];
  16933. var axisZ = BABYLON.Tmp.Vector3[1];
  16934. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16935. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16936. if (this.rotationQuaternion) {
  16937. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16938. }
  16939. else {
  16940. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16941. }
  16942. return this;
  16943. };
  16944. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16945. var engine = this.getEngine();
  16946. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16947. this._isOccluded = false;
  16948. return;
  16949. }
  16950. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16951. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16952. if (isOcclusionQueryAvailable) {
  16953. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16954. this._isOcclusionQueryInProgress = false;
  16955. this._occlusionInternalRetryCounter = 0;
  16956. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16957. }
  16958. else {
  16959. this._occlusionInternalRetryCounter++;
  16960. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16961. this._isOcclusionQueryInProgress = false;
  16962. this._occlusionInternalRetryCounter = 0;
  16963. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16964. // if strict continue the last state of the object.
  16965. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16966. }
  16967. else {
  16968. return;
  16969. }
  16970. }
  16971. }
  16972. var scene = this.getScene();
  16973. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16974. if (!this._occlusionQuery) {
  16975. this._occlusionQuery = engine.createQuery();
  16976. }
  16977. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16978. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16979. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16980. this._isOcclusionQueryInProgress = true;
  16981. };
  16982. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16983. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16984. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16985. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16986. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16987. return AbstractMesh;
  16988. }(BABYLON.TransformNode));
  16989. BABYLON.AbstractMesh = AbstractMesh;
  16990. })(BABYLON || (BABYLON = {}));
  16991. //# sourceMappingURL=babylon.abstractMesh.js.map
  16992. var BABYLON;
  16993. (function (BABYLON) {
  16994. var Light = /** @class */ (function (_super) {
  16995. __extends(Light, _super);
  16996. /**
  16997. * Creates a Light object in the scene.
  16998. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16999. */
  17000. function Light(name, scene) {
  17001. var _this = _super.call(this, name, scene) || this;
  17002. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  17003. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  17004. _this.intensity = 1.0;
  17005. _this.range = Number.MAX_VALUE;
  17006. /**
  17007. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  17008. * of light.
  17009. */
  17010. _this._photometricScale = 1.0;
  17011. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  17012. _this._radius = 0.00001;
  17013. _this.renderPriority = 0;
  17014. /**
  17015. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  17016. * the current shadow generator.
  17017. */
  17018. _this.shadowEnabled = true;
  17019. _this._excludeWithLayerMask = 0;
  17020. _this._includeOnlyWithLayerMask = 0;
  17021. _this._lightmapMode = 0;
  17022. _this._excludedMeshesIds = new Array();
  17023. _this._includedOnlyMeshesIds = new Array();
  17024. _this.getScene().addLight(_this);
  17025. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  17026. _this._buildUniformLayout();
  17027. _this.includedOnlyMeshes = new Array();
  17028. _this.excludedMeshes = new Array();
  17029. _this._resyncMeshes();
  17030. return _this;
  17031. }
  17032. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  17033. /**
  17034. * If every light affecting the material is in this lightmapMode,
  17035. * material.lightmapTexture adds or multiplies
  17036. * (depends on material.useLightmapAsShadowmap)
  17037. * after every other light calculations.
  17038. */
  17039. get: function () {
  17040. return Light._LIGHTMAP_DEFAULT;
  17041. },
  17042. enumerable: true,
  17043. configurable: true
  17044. });
  17045. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  17046. /**
  17047. * material.lightmapTexture as only diffuse lighting from this light
  17048. * adds only specular lighting from this light
  17049. * adds dynamic shadows
  17050. */
  17051. get: function () {
  17052. return Light._LIGHTMAP_SPECULAR;
  17053. },
  17054. enumerable: true,
  17055. configurable: true
  17056. });
  17057. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  17058. /**
  17059. * material.lightmapTexture as only lighting
  17060. * no light calculation from this light
  17061. * only adds dynamic shadows from this light
  17062. */
  17063. get: function () {
  17064. return Light._LIGHTMAP_SHADOWSONLY;
  17065. },
  17066. enumerable: true,
  17067. configurable: true
  17068. });
  17069. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  17070. /**
  17071. * Each light type uses the default quantity according to its type:
  17072. * point/spot lights use luminous intensity
  17073. * directional lights use illuminance
  17074. */
  17075. get: function () {
  17076. return Light._INTENSITYMODE_AUTOMATIC;
  17077. },
  17078. enumerable: true,
  17079. configurable: true
  17080. });
  17081. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  17082. /**
  17083. * lumen (lm)
  17084. */
  17085. get: function () {
  17086. return Light._INTENSITYMODE_LUMINOUSPOWER;
  17087. },
  17088. enumerable: true,
  17089. configurable: true
  17090. });
  17091. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  17092. /**
  17093. * candela (lm/sr)
  17094. */
  17095. get: function () {
  17096. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  17097. },
  17098. enumerable: true,
  17099. configurable: true
  17100. });
  17101. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  17102. /**
  17103. * lux (lm/m^2)
  17104. */
  17105. get: function () {
  17106. return Light._INTENSITYMODE_ILLUMINANCE;
  17107. },
  17108. enumerable: true,
  17109. configurable: true
  17110. });
  17111. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  17112. /**
  17113. * nit (cd/m^2)
  17114. */
  17115. get: function () {
  17116. return Light._INTENSITYMODE_LUMINANCE;
  17117. },
  17118. enumerable: true,
  17119. configurable: true
  17120. });
  17121. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  17122. /**
  17123. * Light type const id of the point light.
  17124. */
  17125. get: function () {
  17126. return Light._LIGHTTYPEID_POINTLIGHT;
  17127. },
  17128. enumerable: true,
  17129. configurable: true
  17130. });
  17131. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  17132. /**
  17133. * Light type const id of the directional light.
  17134. */
  17135. get: function () {
  17136. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  17137. },
  17138. enumerable: true,
  17139. configurable: true
  17140. });
  17141. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  17142. /**
  17143. * Light type const id of the spot light.
  17144. */
  17145. get: function () {
  17146. return Light._LIGHTTYPEID_SPOTLIGHT;
  17147. },
  17148. enumerable: true,
  17149. configurable: true
  17150. });
  17151. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  17152. /**
  17153. * Light type const id of the hemispheric light.
  17154. */
  17155. get: function () {
  17156. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  17157. },
  17158. enumerable: true,
  17159. configurable: true
  17160. });
  17161. Object.defineProperty(Light.prototype, "intensityMode", {
  17162. /**
  17163. * Gets the photometric scale used to interpret the intensity.
  17164. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17165. */
  17166. get: function () {
  17167. return this._intensityMode;
  17168. },
  17169. /**
  17170. * Sets the photometric scale used to interpret the intensity.
  17171. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  17172. */
  17173. set: function (value) {
  17174. this._intensityMode = value;
  17175. this._computePhotometricScale();
  17176. },
  17177. enumerable: true,
  17178. configurable: true
  17179. });
  17180. ;
  17181. ;
  17182. Object.defineProperty(Light.prototype, "radius", {
  17183. /**
  17184. * Gets the light radius used by PBR Materials to simulate soft area lights.
  17185. */
  17186. get: function () {
  17187. return this._radius;
  17188. },
  17189. /**
  17190. * sets the light radius used by PBR Materials to simulate soft area lights.
  17191. */
  17192. set: function (value) {
  17193. this._radius = value;
  17194. this._computePhotometricScale();
  17195. },
  17196. enumerable: true,
  17197. configurable: true
  17198. });
  17199. ;
  17200. ;
  17201. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  17202. get: function () {
  17203. return this._includedOnlyMeshes;
  17204. },
  17205. set: function (value) {
  17206. this._includedOnlyMeshes = value;
  17207. this._hookArrayForIncludedOnly(value);
  17208. },
  17209. enumerable: true,
  17210. configurable: true
  17211. });
  17212. Object.defineProperty(Light.prototype, "excludedMeshes", {
  17213. get: function () {
  17214. return this._excludedMeshes;
  17215. },
  17216. set: function (value) {
  17217. this._excludedMeshes = value;
  17218. this._hookArrayForExcluded(value);
  17219. },
  17220. enumerable: true,
  17221. configurable: true
  17222. });
  17223. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  17224. get: function () {
  17225. return this._excludeWithLayerMask;
  17226. },
  17227. set: function (value) {
  17228. this._excludeWithLayerMask = value;
  17229. this._resyncMeshes();
  17230. },
  17231. enumerable: true,
  17232. configurable: true
  17233. });
  17234. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  17235. get: function () {
  17236. return this._includeOnlyWithLayerMask;
  17237. },
  17238. set: function (value) {
  17239. this._includeOnlyWithLayerMask = value;
  17240. this._resyncMeshes();
  17241. },
  17242. enumerable: true,
  17243. configurable: true
  17244. });
  17245. Object.defineProperty(Light.prototype, "lightmapMode", {
  17246. get: function () {
  17247. return this._lightmapMode;
  17248. },
  17249. set: function (value) {
  17250. if (this._lightmapMode === value) {
  17251. return;
  17252. }
  17253. this._lightmapMode = value;
  17254. this._markMeshesAsLightDirty();
  17255. },
  17256. enumerable: true,
  17257. configurable: true
  17258. });
  17259. Light.prototype._buildUniformLayout = function () {
  17260. // Overridden
  17261. };
  17262. /**
  17263. * Returns the string "Light".
  17264. */
  17265. Light.prototype.getClassName = function () {
  17266. return "Light";
  17267. };
  17268. /**
  17269. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17270. */
  17271. Light.prototype.toString = function (fullDetails) {
  17272. var ret = "Name: " + this.name;
  17273. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  17274. if (this.animations) {
  17275. for (var i = 0; i < this.animations.length; i++) {
  17276. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17277. }
  17278. }
  17279. if (fullDetails) {
  17280. }
  17281. return ret;
  17282. };
  17283. /**
  17284. * Set the enabled state of this node.
  17285. * @param {boolean} value - the new enabled state
  17286. * @see isEnabled
  17287. */
  17288. Light.prototype.setEnabled = function (value) {
  17289. _super.prototype.setEnabled.call(this, value);
  17290. this._resyncMeshes();
  17291. };
  17292. /**
  17293. * Returns the Light associated shadow generator.
  17294. */
  17295. Light.prototype.getShadowGenerator = function () {
  17296. return this._shadowGenerator;
  17297. };
  17298. /**
  17299. * Returns a Vector3, the absolute light position in the World.
  17300. */
  17301. Light.prototype.getAbsolutePosition = function () {
  17302. return BABYLON.Vector3.Zero();
  17303. };
  17304. Light.prototype.transferToEffect = function (effect, lightIndex) {
  17305. };
  17306. Light.prototype._getWorldMatrix = function () {
  17307. return BABYLON.Matrix.Identity();
  17308. };
  17309. /**
  17310. * Boolean : True if the light will affect the passed mesh.
  17311. */
  17312. Light.prototype.canAffectMesh = function (mesh) {
  17313. if (!mesh) {
  17314. return true;
  17315. }
  17316. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  17317. return false;
  17318. }
  17319. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  17320. return false;
  17321. }
  17322. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  17323. return false;
  17324. }
  17325. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  17326. return false;
  17327. }
  17328. return true;
  17329. };
  17330. /**
  17331. * Returns the light World matrix.
  17332. */
  17333. Light.prototype.getWorldMatrix = function () {
  17334. this._currentRenderId = this.getScene().getRenderId();
  17335. var worldMatrix = this._getWorldMatrix();
  17336. if (this.parent && this.parent.getWorldMatrix) {
  17337. if (!this._parentedWorldMatrix) {
  17338. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  17339. }
  17340. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  17341. this._markSyncedWithParent();
  17342. return this._parentedWorldMatrix;
  17343. }
  17344. return worldMatrix;
  17345. };
  17346. /**
  17347. * Sort function to order lights for rendering.
  17348. * @param a First Light object to compare to second.
  17349. * @param b Second Light object to compare first.
  17350. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  17351. */
  17352. Light.compareLightsPriority = function (a, b) {
  17353. //shadow-casting lights have priority over non-shadow-casting lights
  17354. //the renderPrioirty is a secondary sort criterion
  17355. if (a.shadowEnabled !== b.shadowEnabled) {
  17356. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  17357. }
  17358. return b.renderPriority - a.renderPriority;
  17359. };
  17360. /**
  17361. * Disposes the light.
  17362. */
  17363. Light.prototype.dispose = function () {
  17364. if (this._shadowGenerator) {
  17365. this._shadowGenerator.dispose();
  17366. this._shadowGenerator = null;
  17367. }
  17368. // Animations
  17369. this.getScene().stopAnimation(this);
  17370. this._uniformBuffer.dispose();
  17371. // Remove from scene
  17372. this.getScene().removeLight(this);
  17373. _super.prototype.dispose.call(this);
  17374. };
  17375. /**
  17376. * Returns the light type ID (integer).
  17377. */
  17378. Light.prototype.getTypeID = function () {
  17379. return 0;
  17380. };
  17381. /**
  17382. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  17383. */
  17384. Light.prototype.getScaledIntensity = function () {
  17385. return this._photometricScale * this.intensity;
  17386. };
  17387. /**
  17388. * Returns a new Light object, named "name", from the current one.
  17389. */
  17390. Light.prototype.clone = function (name) {
  17391. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  17392. if (!constructor) {
  17393. return null;
  17394. }
  17395. return BABYLON.SerializationHelper.Clone(constructor, this);
  17396. };
  17397. /**
  17398. * Serializes the current light into a Serialization object.
  17399. * Returns the serialized object.
  17400. */
  17401. Light.prototype.serialize = function () {
  17402. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17403. // Type
  17404. serializationObject.type = this.getTypeID();
  17405. // Parent
  17406. if (this.parent) {
  17407. serializationObject.parentId = this.parent.id;
  17408. }
  17409. // Inclusion / exclusions
  17410. if (this.excludedMeshes.length > 0) {
  17411. serializationObject.excludedMeshesIds = [];
  17412. this.excludedMeshes.forEach(function (mesh) {
  17413. serializationObject.excludedMeshesIds.push(mesh.id);
  17414. });
  17415. }
  17416. if (this.includedOnlyMeshes.length > 0) {
  17417. serializationObject.includedOnlyMeshesIds = [];
  17418. this.includedOnlyMeshes.forEach(function (mesh) {
  17419. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  17420. });
  17421. }
  17422. // Animations
  17423. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17424. serializationObject.ranges = this.serializeAnimationRanges();
  17425. return serializationObject;
  17426. };
  17427. /**
  17428. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  17429. * This new light is named "name" and added to the passed scene.
  17430. */
  17431. Light.GetConstructorFromName = function (type, name, scene) {
  17432. switch (type) {
  17433. case 0:
  17434. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  17435. case 1:
  17436. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  17437. case 2:
  17438. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  17439. case 3:
  17440. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  17441. }
  17442. return null;
  17443. };
  17444. /**
  17445. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  17446. */
  17447. Light.Parse = function (parsedLight, scene) {
  17448. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  17449. if (!constructor) {
  17450. return null;
  17451. }
  17452. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  17453. // Inclusion / exclusions
  17454. if (parsedLight.excludedMeshesIds) {
  17455. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17456. }
  17457. if (parsedLight.includedOnlyMeshesIds) {
  17458. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17459. }
  17460. // Parent
  17461. if (parsedLight.parentId) {
  17462. light._waitingParentId = parsedLight.parentId;
  17463. }
  17464. // Animations
  17465. if (parsedLight.animations) {
  17466. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17467. var parsedAnimation = parsedLight.animations[animationIndex];
  17468. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17469. }
  17470. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  17471. }
  17472. if (parsedLight.autoAnimate) {
  17473. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  17474. }
  17475. return light;
  17476. };
  17477. Light.prototype._hookArrayForExcluded = function (array) {
  17478. var _this = this;
  17479. var oldPush = array.push;
  17480. array.push = function () {
  17481. var items = [];
  17482. for (var _i = 0; _i < arguments.length; _i++) {
  17483. items[_i] = arguments[_i];
  17484. }
  17485. var result = oldPush.apply(array, items);
  17486. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  17487. var item = items_1[_a];
  17488. item._resyncLighSource(_this);
  17489. }
  17490. return result;
  17491. };
  17492. var oldSplice = array.splice;
  17493. array.splice = function (index, deleteCount) {
  17494. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17495. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  17496. var item = deleted_1[_i];
  17497. item._resyncLighSource(_this);
  17498. }
  17499. return deleted;
  17500. };
  17501. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  17502. var item = array_1[_i];
  17503. item._resyncLighSource(this);
  17504. }
  17505. };
  17506. Light.prototype._hookArrayForIncludedOnly = function (array) {
  17507. var _this = this;
  17508. var oldPush = array.push;
  17509. array.push = function () {
  17510. var items = [];
  17511. for (var _i = 0; _i < arguments.length; _i++) {
  17512. items[_i] = arguments[_i];
  17513. }
  17514. var result = oldPush.apply(array, items);
  17515. _this._resyncMeshes();
  17516. return result;
  17517. };
  17518. var oldSplice = array.splice;
  17519. array.splice = function (index, deleteCount) {
  17520. var deleted = oldSplice.apply(array, [index, deleteCount]);
  17521. _this._resyncMeshes();
  17522. return deleted;
  17523. };
  17524. this._resyncMeshes();
  17525. };
  17526. Light.prototype._resyncMeshes = function () {
  17527. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17528. var mesh = _a[_i];
  17529. mesh._resyncLighSource(this);
  17530. }
  17531. };
  17532. Light.prototype._markMeshesAsLightDirty = function () {
  17533. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  17534. var mesh = _a[_i];
  17535. if (mesh._lightSources.indexOf(this) !== -1) {
  17536. mesh._markSubMeshesAsLightDirty();
  17537. }
  17538. }
  17539. };
  17540. /**
  17541. * Recomputes the cached photometric scale if needed.
  17542. */
  17543. Light.prototype._computePhotometricScale = function () {
  17544. this._photometricScale = this._getPhotometricScale();
  17545. this.getScene().resetCachedMaterial();
  17546. };
  17547. /**
  17548. * Returns the Photometric Scale according to the light type and intensity mode.
  17549. */
  17550. Light.prototype._getPhotometricScale = function () {
  17551. var photometricScale = 0.0;
  17552. var lightTypeID = this.getTypeID();
  17553. //get photometric mode
  17554. var photometricMode = this.intensityMode;
  17555. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  17556. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  17557. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  17558. }
  17559. else {
  17560. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  17561. }
  17562. }
  17563. //compute photometric scale
  17564. switch (lightTypeID) {
  17565. case Light.LIGHTTYPEID_POINTLIGHT:
  17566. case Light.LIGHTTYPEID_SPOTLIGHT:
  17567. switch (photometricMode) {
  17568. case Light.INTENSITYMODE_LUMINOUSPOWER:
  17569. photometricScale = 1.0 / (4.0 * Math.PI);
  17570. break;
  17571. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  17572. photometricScale = 1.0;
  17573. break;
  17574. case Light.INTENSITYMODE_LUMINANCE:
  17575. photometricScale = this.radius * this.radius;
  17576. break;
  17577. }
  17578. break;
  17579. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  17580. switch (photometricMode) {
  17581. case Light.INTENSITYMODE_ILLUMINANCE:
  17582. photometricScale = 1.0;
  17583. break;
  17584. case Light.INTENSITYMODE_LUMINANCE:
  17585. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  17586. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  17587. var apexAngleRadians = this.radius;
  17588. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  17589. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  17590. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  17591. photometricScale = solidAngle;
  17592. break;
  17593. }
  17594. break;
  17595. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  17596. // No fall off in hemisperic light.
  17597. photometricScale = 1.0;
  17598. break;
  17599. }
  17600. return photometricScale;
  17601. };
  17602. Light.prototype._reorderLightsInScene = function () {
  17603. var scene = this.getScene();
  17604. if (this._renderPriority != 0) {
  17605. scene.requireLightSorting = true;
  17606. }
  17607. this.getScene().sortLightsByPriority();
  17608. };
  17609. //lightmapMode Consts
  17610. Light._LIGHTMAP_DEFAULT = 0;
  17611. Light._LIGHTMAP_SPECULAR = 1;
  17612. Light._LIGHTMAP_SHADOWSONLY = 2;
  17613. // Intensity Mode Consts
  17614. Light._INTENSITYMODE_AUTOMATIC = 0;
  17615. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  17616. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  17617. Light._INTENSITYMODE_ILLUMINANCE = 3;
  17618. Light._INTENSITYMODE_LUMINANCE = 4;
  17619. // Light types ids const.
  17620. Light._LIGHTTYPEID_POINTLIGHT = 0;
  17621. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  17622. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  17623. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  17624. __decorate([
  17625. BABYLON.serializeAsColor3()
  17626. ], Light.prototype, "diffuse", void 0);
  17627. __decorate([
  17628. BABYLON.serializeAsColor3()
  17629. ], Light.prototype, "specular", void 0);
  17630. __decorate([
  17631. BABYLON.serialize()
  17632. ], Light.prototype, "intensity", void 0);
  17633. __decorate([
  17634. BABYLON.serialize()
  17635. ], Light.prototype, "range", void 0);
  17636. __decorate([
  17637. BABYLON.serialize()
  17638. ], Light.prototype, "intensityMode", null);
  17639. __decorate([
  17640. BABYLON.serialize()
  17641. ], Light.prototype, "radius", null);
  17642. __decorate([
  17643. BABYLON.serialize()
  17644. ], Light.prototype, "_renderPriority", void 0);
  17645. __decorate([
  17646. BABYLON.expandToProperty("_reorderLightsInScene")
  17647. ], Light.prototype, "renderPriority", void 0);
  17648. __decorate([
  17649. BABYLON.serialize()
  17650. ], Light.prototype, "shadowEnabled", void 0);
  17651. __decorate([
  17652. BABYLON.serialize("excludeWithLayerMask")
  17653. ], Light.prototype, "_excludeWithLayerMask", void 0);
  17654. __decorate([
  17655. BABYLON.serialize("includeOnlyWithLayerMask")
  17656. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  17657. __decorate([
  17658. BABYLON.serialize("lightmapMode")
  17659. ], Light.prototype, "_lightmapMode", void 0);
  17660. return Light;
  17661. }(BABYLON.Node));
  17662. BABYLON.Light = Light;
  17663. })(BABYLON || (BABYLON = {}));
  17664. //# sourceMappingURL=babylon.light.js.map
  17665. var BABYLON;
  17666. (function (BABYLON) {
  17667. var Camera = /** @class */ (function (_super) {
  17668. __extends(Camera, _super);
  17669. function Camera(name, position, scene) {
  17670. var _this = _super.call(this, name, scene) || this;
  17671. _this.upVector = BABYLON.Vector3.Up();
  17672. _this.orthoLeft = null;
  17673. _this.orthoRight = null;
  17674. _this.orthoBottom = null;
  17675. _this.orthoTop = null;
  17676. /**
  17677. * default : 0.8
  17678. * FOV is set in Radians.
  17679. */
  17680. _this.fov = 0.8;
  17681. _this.minZ = 1;
  17682. _this.maxZ = 10000.0;
  17683. _this.inertia = 0.9;
  17684. _this.mode = Camera.PERSPECTIVE_CAMERA;
  17685. _this.isIntermediate = false;
  17686. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  17687. /**
  17688. * Restricts the camera to viewing objects with the same layerMask.
  17689. * A camera with a layerMask of 1 will render meshes with no layerMask and meshes with a layerMask of 1.
  17690. */
  17691. _this.layerMask = 0x0FFFFFFF;
  17692. /**
  17693. * default : FOVMODE_VERTICAL_FIXED
  17694. * fovMode sets the camera frustum bounds to the viewport bounds.
  17695. */
  17696. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  17697. // Camera rig members
  17698. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  17699. _this._rigCameras = new Array();
  17700. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  17701. _this._skipRendering = false;
  17702. _this.customRenderTargets = new Array();
  17703. // Observables
  17704. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  17705. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  17706. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  17707. _this.onRestoreStateObservable = new BABYLON.Observable();
  17708. // Cache
  17709. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  17710. _this._projectionMatrix = new BABYLON.Matrix();
  17711. _this._doNotComputeProjectionMatrix = false;
  17712. _this._postProcesses = new Array();
  17713. _this._transformMatrix = BABYLON.Matrix.Zero();
  17714. _this._activeMeshes = new BABYLON.SmartArray(256);
  17715. _this._globalPosition = BABYLON.Vector3.Zero();
  17716. _this._refreshFrustumPlanes = true;
  17717. _this.getScene().addCamera(_this);
  17718. if (!_this.getScene().activeCamera) {
  17719. _this.getScene().activeCamera = _this;
  17720. }
  17721. _this.position = position;
  17722. return _this;
  17723. }
  17724. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  17725. get: function () {
  17726. return Camera._PERSPECTIVE_CAMERA;
  17727. },
  17728. enumerable: true,
  17729. configurable: true
  17730. });
  17731. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  17732. get: function () {
  17733. return Camera._ORTHOGRAPHIC_CAMERA;
  17734. },
  17735. enumerable: true,
  17736. configurable: true
  17737. });
  17738. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  17739. /**
  17740. * This is the default FOV mode for perspective cameras.
  17741. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  17742. *
  17743. */
  17744. get: function () {
  17745. return Camera._FOVMODE_VERTICAL_FIXED;
  17746. },
  17747. enumerable: true,
  17748. configurable: true
  17749. });
  17750. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  17751. /**
  17752. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  17753. *
  17754. */
  17755. get: function () {
  17756. return Camera._FOVMODE_HORIZONTAL_FIXED;
  17757. },
  17758. enumerable: true,
  17759. configurable: true
  17760. });
  17761. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  17762. get: function () {
  17763. return Camera._RIG_MODE_NONE;
  17764. },
  17765. enumerable: true,
  17766. configurable: true
  17767. });
  17768. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  17769. get: function () {
  17770. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  17771. },
  17772. enumerable: true,
  17773. configurable: true
  17774. });
  17775. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  17776. get: function () {
  17777. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  17783. get: function () {
  17784. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17785. },
  17786. enumerable: true,
  17787. configurable: true
  17788. });
  17789. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  17790. get: function () {
  17791. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  17792. },
  17793. enumerable: true,
  17794. configurable: true
  17795. });
  17796. Object.defineProperty(Camera, "RIG_MODE_VR", {
  17797. get: function () {
  17798. return Camera._RIG_MODE_VR;
  17799. },
  17800. enumerable: true,
  17801. configurable: true
  17802. });
  17803. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  17804. get: function () {
  17805. return Camera._RIG_MODE_WEBVR;
  17806. },
  17807. enumerable: true,
  17808. configurable: true
  17809. });
  17810. /**
  17811. * Store current camera state (fov, position, etc..)
  17812. */
  17813. Camera.prototype.storeState = function () {
  17814. this._stateStored = true;
  17815. this._storedFov = this.fov;
  17816. return this;
  17817. };
  17818. /**
  17819. * Restores the camera state values if it has been stored. You must call storeState() first
  17820. */
  17821. Camera.prototype._restoreStateValues = function () {
  17822. if (!this._stateStored) {
  17823. return false;
  17824. }
  17825. this.fov = this._storedFov;
  17826. return true;
  17827. };
  17828. /**
  17829. * Restored camera state. You must call storeState() first
  17830. */
  17831. Camera.prototype.restoreState = function () {
  17832. if (this._restoreStateValues()) {
  17833. this.onRestoreStateObservable.notifyObservers(this);
  17834. return true;
  17835. }
  17836. return false;
  17837. };
  17838. Camera.prototype.getClassName = function () {
  17839. return "Camera";
  17840. };
  17841. /**
  17842. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17843. */
  17844. Camera.prototype.toString = function (fullDetails) {
  17845. var ret = "Name: " + this.name;
  17846. ret += ", type: " + this.getClassName();
  17847. if (this.animations) {
  17848. for (var i = 0; i < this.animations.length; i++) {
  17849. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  17850. }
  17851. }
  17852. if (fullDetails) {
  17853. }
  17854. return ret;
  17855. };
  17856. Object.defineProperty(Camera.prototype, "globalPosition", {
  17857. get: function () {
  17858. return this._globalPosition;
  17859. },
  17860. enumerable: true,
  17861. configurable: true
  17862. });
  17863. Camera.prototype.getActiveMeshes = function () {
  17864. return this._activeMeshes;
  17865. };
  17866. Camera.prototype.isActiveMesh = function (mesh) {
  17867. return (this._activeMeshes.indexOf(mesh) !== -1);
  17868. };
  17869. //Cache
  17870. Camera.prototype._initCache = function () {
  17871. _super.prototype._initCache.call(this);
  17872. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17873. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17874. this._cache.mode = undefined;
  17875. this._cache.minZ = undefined;
  17876. this._cache.maxZ = undefined;
  17877. this._cache.fov = undefined;
  17878. this._cache.fovMode = undefined;
  17879. this._cache.aspectRatio = undefined;
  17880. this._cache.orthoLeft = undefined;
  17881. this._cache.orthoRight = undefined;
  17882. this._cache.orthoBottom = undefined;
  17883. this._cache.orthoTop = undefined;
  17884. this._cache.renderWidth = undefined;
  17885. this._cache.renderHeight = undefined;
  17886. };
  17887. Camera.prototype._updateCache = function (ignoreParentClass) {
  17888. if (!ignoreParentClass) {
  17889. _super.prototype._updateCache.call(this);
  17890. }
  17891. this._cache.position.copyFrom(this.position);
  17892. this._cache.upVector.copyFrom(this.upVector);
  17893. };
  17894. // Synchronized
  17895. Camera.prototype._isSynchronized = function () {
  17896. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  17897. };
  17898. Camera.prototype._isSynchronizedViewMatrix = function () {
  17899. if (!_super.prototype._isSynchronized.call(this))
  17900. return false;
  17901. return this._cache.position.equals(this.position)
  17902. && this._cache.upVector.equals(this.upVector)
  17903. && this.isSynchronizedWithParent();
  17904. };
  17905. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  17906. var check = this._cache.mode === this.mode
  17907. && this._cache.minZ === this.minZ
  17908. && this._cache.maxZ === this.maxZ;
  17909. if (!check) {
  17910. return false;
  17911. }
  17912. var engine = this.getEngine();
  17913. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17914. check = this._cache.fov === this.fov
  17915. && this._cache.fovMode === this.fovMode
  17916. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17917. }
  17918. else {
  17919. check = this._cache.orthoLeft === this.orthoLeft
  17920. && this._cache.orthoRight === this.orthoRight
  17921. && this._cache.orthoBottom === this.orthoBottom
  17922. && this._cache.orthoTop === this.orthoTop
  17923. && this._cache.renderWidth === engine.getRenderWidth()
  17924. && this._cache.renderHeight === engine.getRenderHeight();
  17925. }
  17926. return check;
  17927. };
  17928. // Controls
  17929. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17930. };
  17931. Camera.prototype.detachControl = function (element) {
  17932. };
  17933. Camera.prototype.update = function () {
  17934. this._checkInputs();
  17935. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17936. this._updateRigCameras();
  17937. }
  17938. };
  17939. Camera.prototype._checkInputs = function () {
  17940. this.onAfterCheckInputsObservable.notifyObservers(this);
  17941. };
  17942. Object.defineProperty(Camera.prototype, "rigCameras", {
  17943. get: function () {
  17944. return this._rigCameras;
  17945. },
  17946. enumerable: true,
  17947. configurable: true
  17948. });
  17949. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17950. get: function () {
  17951. return this._rigPostProcess;
  17952. },
  17953. enumerable: true,
  17954. configurable: true
  17955. });
  17956. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17957. // invalidate framebuffer
  17958. if (this._postProcesses.length > 0) {
  17959. this._postProcesses[0].markTextureDirty();
  17960. }
  17961. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17962. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17963. var cam = this._rigCameras[i];
  17964. var rigPostProcess = cam._rigPostProcess;
  17965. // for VR rig, there does not have to be a post process
  17966. if (rigPostProcess) {
  17967. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17968. if (isPass) {
  17969. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17970. cam.isIntermediate = this._postProcesses.length === 0;
  17971. }
  17972. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17973. rigPostProcess.markTextureDirty();
  17974. }
  17975. else {
  17976. cam._postProcesses = this._postProcesses.slice(0);
  17977. }
  17978. }
  17979. };
  17980. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17981. if (insertAt === void 0) { insertAt = null; }
  17982. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17983. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17984. return 0;
  17985. }
  17986. if (insertAt == null || insertAt < 0) {
  17987. this._postProcesses.push(postProcess);
  17988. }
  17989. else {
  17990. this._postProcesses.splice(insertAt, 0, postProcess);
  17991. }
  17992. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17993. return this._postProcesses.indexOf(postProcess);
  17994. };
  17995. Camera.prototype.detachPostProcess = function (postProcess) {
  17996. var idx = this._postProcesses.indexOf(postProcess);
  17997. if (idx !== -1) {
  17998. this._postProcesses.splice(idx, 1);
  17999. }
  18000. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  18001. };
  18002. Camera.prototype.getWorldMatrix = function () {
  18003. if (!this._worldMatrix) {
  18004. this._worldMatrix = BABYLON.Matrix.Identity();
  18005. }
  18006. var viewMatrix = this.getViewMatrix();
  18007. viewMatrix.invertToRef(this._worldMatrix);
  18008. return this._worldMatrix;
  18009. };
  18010. Camera.prototype._getViewMatrix = function () {
  18011. return BABYLON.Matrix.Identity();
  18012. };
  18013. Camera.prototype.getViewMatrix = function (force) {
  18014. if (!force && this._isSynchronizedViewMatrix()) {
  18015. return this._computedViewMatrix;
  18016. }
  18017. this.updateCache();
  18018. this._computedViewMatrix = this._getViewMatrix();
  18019. this._currentRenderId = this.getScene().getRenderId();
  18020. this._refreshFrustumPlanes = true;
  18021. if (!this.parent || !this.parent.getWorldMatrix) {
  18022. this._globalPosition.copyFrom(this.position);
  18023. }
  18024. else {
  18025. if (!this._worldMatrix) {
  18026. this._worldMatrix = BABYLON.Matrix.Identity();
  18027. }
  18028. this._computedViewMatrix.invertToRef(this._worldMatrix);
  18029. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  18030. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  18031. this._computedViewMatrix.invert();
  18032. this._markSyncedWithParent();
  18033. }
  18034. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  18035. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  18036. }
  18037. this.onViewMatrixChangedObservable.notifyObservers(this);
  18038. return this._computedViewMatrix;
  18039. };
  18040. Camera.prototype.freezeProjectionMatrix = function (projection) {
  18041. this._doNotComputeProjectionMatrix = true;
  18042. if (projection !== undefined) {
  18043. this._projectionMatrix = projection;
  18044. }
  18045. };
  18046. ;
  18047. Camera.prototype.unfreezeProjectionMatrix = function () {
  18048. this._doNotComputeProjectionMatrix = false;
  18049. };
  18050. ;
  18051. Camera.prototype.getProjectionMatrix = function (force) {
  18052. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  18053. return this._projectionMatrix;
  18054. }
  18055. // Cache
  18056. this._cache.mode = this.mode;
  18057. this._cache.minZ = this.minZ;
  18058. this._cache.maxZ = this.maxZ;
  18059. // Matrix
  18060. this._refreshFrustumPlanes = true;
  18061. var engine = this.getEngine();
  18062. var scene = this.getScene();
  18063. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  18064. this._cache.fov = this.fov;
  18065. this._cache.fovMode = this.fovMode;
  18066. this._cache.aspectRatio = engine.getAspectRatio(this);
  18067. if (this.minZ <= 0) {
  18068. this.minZ = 0.1;
  18069. }
  18070. if (scene.useRightHandedSystem) {
  18071. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18072. }
  18073. else {
  18074. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  18075. }
  18076. }
  18077. else {
  18078. var halfWidth = engine.getRenderWidth() / 2.0;
  18079. var halfHeight = engine.getRenderHeight() / 2.0;
  18080. if (scene.useRightHandedSystem) {
  18081. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18082. }
  18083. else {
  18084. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  18085. }
  18086. this._cache.orthoLeft = this.orthoLeft;
  18087. this._cache.orthoRight = this.orthoRight;
  18088. this._cache.orthoBottom = this.orthoBottom;
  18089. this._cache.orthoTop = this.orthoTop;
  18090. this._cache.renderWidth = engine.getRenderWidth();
  18091. this._cache.renderHeight = engine.getRenderHeight();
  18092. }
  18093. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  18094. return this._projectionMatrix;
  18095. };
  18096. Camera.prototype.getTranformationMatrix = function () {
  18097. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18098. return this._transformMatrix;
  18099. };
  18100. Camera.prototype.updateFrustumPlanes = function () {
  18101. if (!this._refreshFrustumPlanes) {
  18102. return;
  18103. }
  18104. this.getTranformationMatrix();
  18105. if (!this._frustumPlanes) {
  18106. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18107. }
  18108. else {
  18109. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18110. }
  18111. this._refreshFrustumPlanes = false;
  18112. };
  18113. Camera.prototype.isInFrustum = function (target) {
  18114. this.updateFrustumPlanes();
  18115. return target.isInFrustum(this._frustumPlanes);
  18116. };
  18117. Camera.prototype.isCompletelyInFrustum = function (target) {
  18118. this.updateFrustumPlanes();
  18119. return target.isCompletelyInFrustum(this._frustumPlanes);
  18120. };
  18121. Camera.prototype.getForwardRay = function (length, transform, origin) {
  18122. if (length === void 0) { length = 100; }
  18123. if (!transform) {
  18124. transform = this.getWorldMatrix();
  18125. }
  18126. if (!origin) {
  18127. origin = this.position;
  18128. }
  18129. var forward = new BABYLON.Vector3(0, 0, 1);
  18130. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  18131. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  18132. return new BABYLON.Ray(origin, direction, length);
  18133. };
  18134. Camera.prototype.dispose = function () {
  18135. // Observables
  18136. this.onViewMatrixChangedObservable.clear();
  18137. this.onProjectionMatrixChangedObservable.clear();
  18138. this.onAfterCheckInputsObservable.clear();
  18139. this.onRestoreStateObservable.clear();
  18140. // Inputs
  18141. if (this.inputs) {
  18142. this.inputs.clear();
  18143. }
  18144. // Animations
  18145. this.getScene().stopAnimation(this);
  18146. // Remove from scene
  18147. this.getScene().removeCamera(this);
  18148. while (this._rigCameras.length > 0) {
  18149. var camera = this._rigCameras.pop();
  18150. if (camera) {
  18151. camera.dispose();
  18152. }
  18153. }
  18154. // Postprocesses
  18155. if (this._rigPostProcess) {
  18156. this._rigPostProcess.dispose(this);
  18157. this._rigPostProcess = null;
  18158. this._postProcesses = [];
  18159. }
  18160. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18161. this._rigPostProcess = null;
  18162. this._postProcesses = [];
  18163. }
  18164. else {
  18165. var i = this._postProcesses.length;
  18166. while (--i >= 0) {
  18167. this._postProcesses[i].dispose(this);
  18168. }
  18169. }
  18170. // Render targets
  18171. var i = this.customRenderTargets.length;
  18172. while (--i >= 0) {
  18173. this.customRenderTargets[i].dispose();
  18174. }
  18175. this.customRenderTargets = [];
  18176. // Active Meshes
  18177. this._activeMeshes.dispose();
  18178. _super.prototype.dispose.call(this);
  18179. };
  18180. Object.defineProperty(Camera.prototype, "leftCamera", {
  18181. // ---- Camera rigs section ----
  18182. get: function () {
  18183. if (this._rigCameras.length < 1) {
  18184. return null;
  18185. }
  18186. return this._rigCameras[0];
  18187. },
  18188. enumerable: true,
  18189. configurable: true
  18190. });
  18191. Object.defineProperty(Camera.prototype, "rightCamera", {
  18192. get: function () {
  18193. if (this._rigCameras.length < 2) {
  18194. return null;
  18195. }
  18196. return this._rigCameras[1];
  18197. },
  18198. enumerable: true,
  18199. configurable: true
  18200. });
  18201. Camera.prototype.getLeftTarget = function () {
  18202. if (this._rigCameras.length < 1) {
  18203. return null;
  18204. }
  18205. return this._rigCameras[0].getTarget();
  18206. };
  18207. Camera.prototype.getRightTarget = function () {
  18208. if (this._rigCameras.length < 2) {
  18209. return null;
  18210. }
  18211. return this._rigCameras[1].getTarget();
  18212. };
  18213. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  18214. if (this.cameraRigMode === mode) {
  18215. return;
  18216. }
  18217. while (this._rigCameras.length > 0) {
  18218. var camera = this._rigCameras.pop();
  18219. if (camera) {
  18220. camera.dispose();
  18221. }
  18222. }
  18223. this.cameraRigMode = mode;
  18224. this._cameraRigParams = {};
  18225. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  18226. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  18227. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  18228. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  18229. // create the rig cameras, unless none
  18230. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  18231. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  18232. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  18233. if (leftCamera && rightCamera) {
  18234. this._rigCameras.push(leftCamera);
  18235. this._rigCameras.push(rightCamera);
  18236. }
  18237. }
  18238. switch (this.cameraRigMode) {
  18239. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  18240. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18241. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  18242. break;
  18243. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  18244. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  18245. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  18246. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  18247. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  18248. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  18249. break;
  18250. case Camera.RIG_MODE_VR:
  18251. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  18252. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  18253. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18254. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18255. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  18256. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  18257. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  18258. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  18259. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18260. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18261. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  18262. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  18263. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  18264. if (metrics.compensateDistortion) {
  18265. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  18266. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  18267. }
  18268. break;
  18269. case Camera.RIG_MODE_WEBVR:
  18270. if (rigParams.vrDisplay) {
  18271. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  18272. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  18273. //Left eye
  18274. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  18275. this._rigCameras[0].setCameraRigParameter("left", true);
  18276. //leaving this for future reference
  18277. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  18278. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  18279. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  18280. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18281. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18282. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18283. this._rigCameras[0].parent = this;
  18284. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  18285. //Right eye
  18286. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  18287. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  18288. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  18289. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  18290. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  18291. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  18292. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  18293. this._rigCameras[1].parent = this;
  18294. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  18295. if (Camera.UseAlternateWebVRRendering) {
  18296. this._rigCameras[1]._skipRendering = true;
  18297. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  18298. }
  18299. }
  18300. break;
  18301. }
  18302. this._cascadePostProcessesToRigCams();
  18303. this.update();
  18304. };
  18305. Camera.prototype._getVRProjectionMatrix = function () {
  18306. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  18307. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  18308. return this._projectionMatrix;
  18309. };
  18310. Camera.prototype._updateCameraRotationMatrix = function () {
  18311. //Here for WebVR
  18312. };
  18313. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  18314. //Here for WebVR
  18315. };
  18316. /**
  18317. * This function MUST be overwritten by the different WebVR cameras available.
  18318. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18319. */
  18320. Camera.prototype._getWebVRProjectionMatrix = function () {
  18321. return BABYLON.Matrix.Identity();
  18322. };
  18323. /**
  18324. * This function MUST be overwritten by the different WebVR cameras available.
  18325. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  18326. */
  18327. Camera.prototype._getWebVRViewMatrix = function () {
  18328. return BABYLON.Matrix.Identity();
  18329. };
  18330. Camera.prototype.setCameraRigParameter = function (name, value) {
  18331. if (!this._cameraRigParams) {
  18332. this._cameraRigParams = {};
  18333. }
  18334. this._cameraRigParams[name] = value;
  18335. //provisionnally:
  18336. if (name === "interaxialDistance") {
  18337. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  18338. }
  18339. };
  18340. /**
  18341. * needs to be overridden by children so sub has required properties to be copied
  18342. */
  18343. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  18344. return null;
  18345. };
  18346. /**
  18347. * May need to be overridden by children
  18348. */
  18349. Camera.prototype._updateRigCameras = function () {
  18350. for (var i = 0; i < this._rigCameras.length; i++) {
  18351. this._rigCameras[i].minZ = this.minZ;
  18352. this._rigCameras[i].maxZ = this.maxZ;
  18353. this._rigCameras[i].fov = this.fov;
  18354. }
  18355. // only update viewport when ANAGLYPH
  18356. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  18357. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  18358. }
  18359. };
  18360. Camera.prototype._setupInputs = function () {
  18361. };
  18362. Camera.prototype.serialize = function () {
  18363. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  18364. // Type
  18365. serializationObject.type = this.getClassName();
  18366. // Parent
  18367. if (this.parent) {
  18368. serializationObject.parentId = this.parent.id;
  18369. }
  18370. if (this.inputs) {
  18371. this.inputs.serialize(serializationObject);
  18372. }
  18373. // Animations
  18374. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  18375. serializationObject.ranges = this.serializeAnimationRanges();
  18376. return serializationObject;
  18377. };
  18378. Camera.prototype.clone = function (name) {
  18379. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  18380. };
  18381. Camera.prototype.getDirection = function (localAxis) {
  18382. var result = BABYLON.Vector3.Zero();
  18383. this.getDirectionToRef(localAxis, result);
  18384. return result;
  18385. };
  18386. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  18387. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18388. };
  18389. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  18390. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  18391. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  18392. switch (type) {
  18393. case "ArcRotateCamera":
  18394. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  18395. case "DeviceOrientationCamera":
  18396. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  18397. case "FollowCamera":
  18398. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  18399. case "ArcFollowCamera":
  18400. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  18401. case "GamepadCamera":
  18402. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18403. case "TouchCamera":
  18404. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  18405. case "VirtualJoysticksCamera":
  18406. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  18407. case "WebVRFreeCamera":
  18408. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18409. case "WebVRGamepadCamera":
  18410. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18411. case "VRDeviceOrientationFreeCamera":
  18412. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  18413. case "VRDeviceOrientationGamepadCamera":
  18414. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  18415. case "AnaglyphArcRotateCamera":
  18416. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18417. case "AnaglyphFreeCamera":
  18418. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18419. case "AnaglyphGamepadCamera":
  18420. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18421. case "AnaglyphUniversalCamera":
  18422. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  18423. case "StereoscopicArcRotateCamera":
  18424. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18425. case "StereoscopicFreeCamera":
  18426. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18427. case "StereoscopicGamepadCamera":
  18428. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18429. case "StereoscopicUniversalCamera":
  18430. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  18431. case "FreeCamera":// Forcing Universal here
  18432. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18433. default:// Universal Camera is the default value
  18434. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  18435. }
  18436. };
  18437. Camera.prototype.computeWorldMatrix = function () {
  18438. return this.getWorldMatrix();
  18439. };
  18440. Camera.Parse = function (parsedCamera, scene) {
  18441. var type = parsedCamera.type;
  18442. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  18443. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  18444. // Parent
  18445. if (parsedCamera.parentId) {
  18446. camera._waitingParentId = parsedCamera.parentId;
  18447. }
  18448. //If camera has an input manager, let it parse inputs settings
  18449. if (camera.inputs) {
  18450. camera.inputs.parse(parsedCamera);
  18451. camera._setupInputs();
  18452. }
  18453. if (camera.setPosition) {
  18454. camera.position.copyFromFloats(0, 0, 0);
  18455. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  18456. }
  18457. // Target
  18458. if (parsedCamera.target) {
  18459. if (camera.setTarget) {
  18460. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18461. }
  18462. }
  18463. // Apply 3d rig, when found
  18464. if (parsedCamera.cameraRigMode) {
  18465. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  18466. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  18467. }
  18468. // Animations
  18469. if (parsedCamera.animations) {
  18470. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18471. var parsedAnimation = parsedCamera.animations[animationIndex];
  18472. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  18473. }
  18474. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  18475. }
  18476. if (parsedCamera.autoAnimate) {
  18477. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  18478. }
  18479. return camera;
  18480. };
  18481. // Statics
  18482. Camera._PERSPECTIVE_CAMERA = 0;
  18483. Camera._ORTHOGRAPHIC_CAMERA = 1;
  18484. Camera._FOVMODE_VERTICAL_FIXED = 0;
  18485. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  18486. Camera._RIG_MODE_NONE = 0;
  18487. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  18488. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  18489. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  18490. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  18491. Camera._RIG_MODE_VR = 20;
  18492. Camera._RIG_MODE_WEBVR = 21;
  18493. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  18494. Camera.UseAlternateWebVRRendering = false;
  18495. __decorate([
  18496. BABYLON.serializeAsVector3()
  18497. ], Camera.prototype, "position", void 0);
  18498. __decorate([
  18499. BABYLON.serializeAsVector3()
  18500. ], Camera.prototype, "upVector", void 0);
  18501. __decorate([
  18502. BABYLON.serialize()
  18503. ], Camera.prototype, "orthoLeft", void 0);
  18504. __decorate([
  18505. BABYLON.serialize()
  18506. ], Camera.prototype, "orthoRight", void 0);
  18507. __decorate([
  18508. BABYLON.serialize()
  18509. ], Camera.prototype, "orthoBottom", void 0);
  18510. __decorate([
  18511. BABYLON.serialize()
  18512. ], Camera.prototype, "orthoTop", void 0);
  18513. __decorate([
  18514. BABYLON.serialize()
  18515. ], Camera.prototype, "fov", void 0);
  18516. __decorate([
  18517. BABYLON.serialize()
  18518. ], Camera.prototype, "minZ", void 0);
  18519. __decorate([
  18520. BABYLON.serialize()
  18521. ], Camera.prototype, "maxZ", void 0);
  18522. __decorate([
  18523. BABYLON.serialize()
  18524. ], Camera.prototype, "inertia", void 0);
  18525. __decorate([
  18526. BABYLON.serialize()
  18527. ], Camera.prototype, "mode", void 0);
  18528. __decorate([
  18529. BABYLON.serialize()
  18530. ], Camera.prototype, "layerMask", void 0);
  18531. __decorate([
  18532. BABYLON.serialize()
  18533. ], Camera.prototype, "fovMode", void 0);
  18534. __decorate([
  18535. BABYLON.serialize()
  18536. ], Camera.prototype, "cameraRigMode", void 0);
  18537. __decorate([
  18538. BABYLON.serialize()
  18539. ], Camera.prototype, "interaxialDistance", void 0);
  18540. __decorate([
  18541. BABYLON.serialize()
  18542. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  18543. return Camera;
  18544. }(BABYLON.Node));
  18545. BABYLON.Camera = Camera;
  18546. })(BABYLON || (BABYLON = {}));
  18547. //# sourceMappingURL=babylon.camera.js.map
  18548. var BABYLON;
  18549. (function (BABYLON) {
  18550. var RenderingManager = /** @class */ (function () {
  18551. function RenderingManager(scene) {
  18552. this._renderingGroups = new Array();
  18553. this._autoClearDepthStencil = {};
  18554. this._customOpaqueSortCompareFn = {};
  18555. this._customAlphaTestSortCompareFn = {};
  18556. this._customTransparentSortCompareFn = {};
  18557. this._renderinGroupInfo = null;
  18558. this._scene = scene;
  18559. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  18560. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  18561. }
  18562. }
  18563. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  18564. if (depth === void 0) { depth = true; }
  18565. if (stencil === void 0) { stencil = true; }
  18566. if (this._depthStencilBufferAlreadyCleaned) {
  18567. return;
  18568. }
  18569. this._scene.getEngine().clear(null, false, depth, stencil);
  18570. this._depthStencilBufferAlreadyCleaned = true;
  18571. };
  18572. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  18573. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  18574. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  18575. var info = null;
  18576. if (observable) {
  18577. if (!this._renderinGroupInfo) {
  18578. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  18579. }
  18580. info = this._renderinGroupInfo;
  18581. info.scene = this._scene;
  18582. info.camera = this._scene.activeCamera;
  18583. }
  18584. // Dispatch sprites
  18585. if (renderSprites) {
  18586. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  18587. var manager = this._scene.spriteManagers[index];
  18588. this.dispatchSprites(manager);
  18589. }
  18590. }
  18591. // Render
  18592. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18593. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  18594. var renderingGroup = this._renderingGroups[index];
  18595. if (!renderingGroup && !observable)
  18596. continue;
  18597. var renderingGroupMask = 0;
  18598. // Fire PRECLEAR stage
  18599. if (observable && info) {
  18600. renderingGroupMask = Math.pow(2, index);
  18601. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  18602. info.renderingGroupId = index;
  18603. observable.notifyObservers(info, renderingGroupMask);
  18604. }
  18605. // Clear depth/stencil if needed
  18606. if (RenderingManager.AUTOCLEAR) {
  18607. var autoClear = this._autoClearDepthStencil[index];
  18608. if (autoClear && autoClear.autoClear) {
  18609. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  18610. }
  18611. }
  18612. if (observable && info) {
  18613. // Fire PREOPAQUE stage
  18614. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  18615. observable.notifyObservers(info, renderingGroupMask);
  18616. // Fire PRETRANSPARENT stage
  18617. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  18618. observable.notifyObservers(info, renderingGroupMask);
  18619. }
  18620. if (renderingGroup)
  18621. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  18622. // Fire POSTTRANSPARENT stage
  18623. if (observable && info) {
  18624. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  18625. observable.notifyObservers(info, renderingGroupMask);
  18626. }
  18627. }
  18628. };
  18629. RenderingManager.prototype.reset = function () {
  18630. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18631. var renderingGroup = this._renderingGroups[index];
  18632. if (renderingGroup) {
  18633. renderingGroup.prepare();
  18634. }
  18635. }
  18636. };
  18637. RenderingManager.prototype.dispose = function () {
  18638. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  18639. var renderingGroup = this._renderingGroups[index];
  18640. if (renderingGroup) {
  18641. renderingGroup.dispose();
  18642. }
  18643. }
  18644. this._renderingGroups.length = 0;
  18645. };
  18646. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  18647. if (this._renderingGroups[renderingGroupId] === undefined) {
  18648. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  18649. }
  18650. };
  18651. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  18652. var renderingGroupId = spriteManager.renderingGroupId || 0;
  18653. this._prepareRenderingGroup(renderingGroupId);
  18654. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  18655. };
  18656. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  18657. var renderingGroupId = particleSystem.renderingGroupId || 0;
  18658. this._prepareRenderingGroup(renderingGroupId);
  18659. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  18660. };
  18661. /**
  18662. * @param subMesh The submesh to dispatch
  18663. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18664. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18665. */
  18666. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  18667. if (mesh === undefined) {
  18668. mesh = subMesh.getMesh();
  18669. }
  18670. var renderingGroupId = mesh.renderingGroupId || 0;
  18671. this._prepareRenderingGroup(renderingGroupId);
  18672. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  18673. };
  18674. /**
  18675. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18676. * This allowed control for front to back rendering or reversly depending of the special needs.
  18677. *
  18678. * @param renderingGroupId The rendering group id corresponding to its index
  18679. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18680. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18681. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18682. */
  18683. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18684. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18685. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18686. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18687. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  18688. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  18689. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  18690. if (this._renderingGroups[renderingGroupId]) {
  18691. var group = this._renderingGroups[renderingGroupId];
  18692. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  18693. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  18694. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  18695. }
  18696. };
  18697. /**
  18698. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18699. *
  18700. * @param renderingGroupId The rendering group id corresponding to its index
  18701. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18702. * @param depth Automatically clears depth between groups if true and autoClear is true.
  18703. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  18704. */
  18705. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  18706. if (depth === void 0) { depth = true; }
  18707. if (stencil === void 0) { stencil = true; }
  18708. this._autoClearDepthStencil[renderingGroupId] = {
  18709. autoClear: autoClearDepthStencil,
  18710. depth: depth,
  18711. stencil: stencil
  18712. };
  18713. };
  18714. /**
  18715. * The max id used for rendering groups (not included)
  18716. */
  18717. RenderingManager.MAX_RENDERINGGROUPS = 4;
  18718. /**
  18719. * The min id used for rendering groups (included)
  18720. */
  18721. RenderingManager.MIN_RENDERINGGROUPS = 0;
  18722. /**
  18723. * Used to globally prevent autoclearing scenes.
  18724. */
  18725. RenderingManager.AUTOCLEAR = true;
  18726. return RenderingManager;
  18727. }());
  18728. BABYLON.RenderingManager = RenderingManager;
  18729. })(BABYLON || (BABYLON = {}));
  18730. //# sourceMappingURL=babylon.renderingManager.js.map
  18731. var BABYLON;
  18732. (function (BABYLON) {
  18733. var RenderingGroup = /** @class */ (function () {
  18734. /**
  18735. * Creates a new rendering group.
  18736. * @param index The rendering group index
  18737. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  18738. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  18739. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  18740. */
  18741. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18742. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18743. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18744. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18745. this.index = index;
  18746. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  18747. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  18748. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  18749. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  18750. this._particleSystems = new BABYLON.SmartArray(256);
  18751. this._spriteManagers = new BABYLON.SmartArray(256);
  18752. this._edgesRenderers = new BABYLON.SmartArray(16);
  18753. this._scene = scene;
  18754. this.opaqueSortCompareFn = opaqueSortCompareFn;
  18755. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  18756. this.transparentSortCompareFn = transparentSortCompareFn;
  18757. }
  18758. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  18759. /**
  18760. * Set the opaque sort comparison function.
  18761. * If null the sub meshes will be render in the order they were created
  18762. */
  18763. set: function (value) {
  18764. this._opaqueSortCompareFn = value;
  18765. if (value) {
  18766. this._renderOpaque = this.renderOpaqueSorted;
  18767. }
  18768. else {
  18769. this._renderOpaque = RenderingGroup.renderUnsorted;
  18770. }
  18771. },
  18772. enumerable: true,
  18773. configurable: true
  18774. });
  18775. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  18776. /**
  18777. * Set the alpha test sort comparison function.
  18778. * If null the sub meshes will be render in the order they were created
  18779. */
  18780. set: function (value) {
  18781. this._alphaTestSortCompareFn = value;
  18782. if (value) {
  18783. this._renderAlphaTest = this.renderAlphaTestSorted;
  18784. }
  18785. else {
  18786. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  18787. }
  18788. },
  18789. enumerable: true,
  18790. configurable: true
  18791. });
  18792. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  18793. /**
  18794. * Set the transparent sort comparison function.
  18795. * If null the sub meshes will be render in the order they were created
  18796. */
  18797. set: function (value) {
  18798. if (value) {
  18799. this._transparentSortCompareFn = value;
  18800. }
  18801. else {
  18802. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  18803. }
  18804. this._renderTransparent = this.renderTransparentSorted;
  18805. },
  18806. enumerable: true,
  18807. configurable: true
  18808. });
  18809. /**
  18810. * Render all the sub meshes contained in the group.
  18811. * @param customRenderFunction Used to override the default render behaviour of the group.
  18812. * @returns true if rendered some submeshes.
  18813. */
  18814. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  18815. if (customRenderFunction) {
  18816. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  18817. return;
  18818. }
  18819. var engine = this._scene.getEngine();
  18820. // Depth only
  18821. if (this._depthOnlySubMeshes.length !== 0) {
  18822. engine.setColorWrite(false);
  18823. this._renderAlphaTest(this._depthOnlySubMeshes);
  18824. engine.setColorWrite(true);
  18825. }
  18826. // Opaque
  18827. if (this._opaqueSubMeshes.length !== 0) {
  18828. this._renderOpaque(this._opaqueSubMeshes);
  18829. }
  18830. // Alpha test
  18831. if (this._alphaTestSubMeshes.length !== 0) {
  18832. this._renderAlphaTest(this._alphaTestSubMeshes);
  18833. }
  18834. var stencilState = engine.getStencilBuffer();
  18835. engine.setStencilBuffer(false);
  18836. // Sprites
  18837. if (renderSprites) {
  18838. this._renderSprites();
  18839. }
  18840. // Particles
  18841. if (renderParticles) {
  18842. this._renderParticles(activeMeshes);
  18843. }
  18844. if (this.onBeforeTransparentRendering) {
  18845. this.onBeforeTransparentRendering();
  18846. }
  18847. // Transparent
  18848. if (this._transparentSubMeshes.length !== 0) {
  18849. this._renderTransparent(this._transparentSubMeshes);
  18850. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18851. }
  18852. // Set back stencil to false in case it changes before the edge renderer.
  18853. engine.setStencilBuffer(false);
  18854. // Edges
  18855. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18856. this._edgesRenderers.data[edgesRendererIndex].render();
  18857. }
  18858. // Restore Stencil state.
  18859. engine.setStencilBuffer(stencilState);
  18860. };
  18861. /**
  18862. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  18863. * @param subMeshes The submeshes to render
  18864. */
  18865. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  18866. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  18867. };
  18868. /**
  18869. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  18870. * @param subMeshes The submeshes to render
  18871. */
  18872. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  18873. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  18874. };
  18875. /**
  18876. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  18877. * @param subMeshes The submeshes to render
  18878. */
  18879. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  18880. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  18881. };
  18882. /**
  18883. * Renders the submeshes in a specified order.
  18884. * @param subMeshes The submeshes to sort before render
  18885. * @param sortCompareFn The comparison function use to sort
  18886. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  18887. * @param transparent Specifies to activate blending if true
  18888. */
  18889. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  18890. var subIndex = 0;
  18891. var subMesh;
  18892. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  18893. for (; subIndex < subMeshes.length; subIndex++) {
  18894. subMesh = subMeshes.data[subIndex];
  18895. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  18896. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  18897. }
  18898. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  18899. if (sortCompareFn) {
  18900. sortedArray.sort(sortCompareFn);
  18901. }
  18902. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  18903. subMesh = sortedArray[subIndex];
  18904. if (transparent) {
  18905. var material = subMesh.getMaterial();
  18906. if (material && material.needDepthPrePass) {
  18907. var engine = material.getScene().getEngine();
  18908. engine.setColorWrite(false);
  18909. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18910. subMesh.render(false);
  18911. engine.setColorWrite(true);
  18912. }
  18913. }
  18914. subMesh.render(transparent);
  18915. }
  18916. };
  18917. /**
  18918. * Renders the submeshes in the order they were dispatched (no sort applied).
  18919. * @param subMeshes The submeshes to render
  18920. */
  18921. RenderingGroup.renderUnsorted = function (subMeshes) {
  18922. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18923. var submesh = subMeshes.data[subIndex];
  18924. submesh.render(false);
  18925. }
  18926. };
  18927. /**
  18928. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18929. * are rendered back to front if in the same alpha index.
  18930. *
  18931. * @param a The first submesh
  18932. * @param b The second submesh
  18933. * @returns The result of the comparison
  18934. */
  18935. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18936. // Alpha index first
  18937. if (a._alphaIndex > b._alphaIndex) {
  18938. return 1;
  18939. }
  18940. if (a._alphaIndex < b._alphaIndex) {
  18941. return -1;
  18942. }
  18943. // Then distance to camera
  18944. return RenderingGroup.backToFrontSortCompare(a, b);
  18945. };
  18946. /**
  18947. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18948. * are rendered back to front.
  18949. *
  18950. * @param a The first submesh
  18951. * @param b The second submesh
  18952. * @returns The result of the comparison
  18953. */
  18954. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18955. // Then distance to camera
  18956. if (a._distanceToCamera < b._distanceToCamera) {
  18957. return 1;
  18958. }
  18959. if (a._distanceToCamera > b._distanceToCamera) {
  18960. return -1;
  18961. }
  18962. return 0;
  18963. };
  18964. /**
  18965. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18966. * are rendered front to back (prevent overdraw).
  18967. *
  18968. * @param a The first submesh
  18969. * @param b The second submesh
  18970. * @returns The result of the comparison
  18971. */
  18972. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18973. // Then distance to camera
  18974. if (a._distanceToCamera < b._distanceToCamera) {
  18975. return -1;
  18976. }
  18977. if (a._distanceToCamera > b._distanceToCamera) {
  18978. return 1;
  18979. }
  18980. return 0;
  18981. };
  18982. /**
  18983. * Resets the different lists of submeshes to prepare a new frame.
  18984. */
  18985. RenderingGroup.prototype.prepare = function () {
  18986. this._opaqueSubMeshes.reset();
  18987. this._transparentSubMeshes.reset();
  18988. this._alphaTestSubMeshes.reset();
  18989. this._depthOnlySubMeshes.reset();
  18990. this._particleSystems.reset();
  18991. this._spriteManagers.reset();
  18992. this._edgesRenderers.reset();
  18993. };
  18994. RenderingGroup.prototype.dispose = function () {
  18995. this._opaqueSubMeshes.dispose();
  18996. this._transparentSubMeshes.dispose();
  18997. this._alphaTestSubMeshes.dispose();
  18998. this._depthOnlySubMeshes.dispose();
  18999. this._particleSystems.dispose();
  19000. this._spriteManagers.dispose();
  19001. this._edgesRenderers.dispose();
  19002. };
  19003. /**
  19004. * Inserts the submesh in its correct queue depending on its material.
  19005. * @param subMesh The submesh to dispatch
  19006. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  19007. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  19008. */
  19009. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  19010. // Get mesh and materials if not provided
  19011. if (mesh === undefined) {
  19012. mesh = subMesh.getMesh();
  19013. }
  19014. if (material === undefined) {
  19015. material = subMesh.getMaterial();
  19016. }
  19017. if (material === null || material === undefined) {
  19018. return;
  19019. }
  19020. if (material.needAlphaBlendingForMesh(mesh)) {
  19021. this._transparentSubMeshes.push(subMesh);
  19022. }
  19023. else if (material.needAlphaTesting()) {
  19024. if (material.needDepthPrePass) {
  19025. this._depthOnlySubMeshes.push(subMesh);
  19026. }
  19027. this._alphaTestSubMeshes.push(subMesh);
  19028. }
  19029. else {
  19030. if (material.needDepthPrePass) {
  19031. this._depthOnlySubMeshes.push(subMesh);
  19032. }
  19033. this._opaqueSubMeshes.push(subMesh); // Opaque
  19034. }
  19035. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  19036. this._edgesRenderers.push(mesh._edgesRenderer);
  19037. }
  19038. };
  19039. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  19040. this._spriteManagers.push(spriteManager);
  19041. };
  19042. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  19043. this._particleSystems.push(particleSystem);
  19044. };
  19045. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  19046. if (this._particleSystems.length === 0) {
  19047. return;
  19048. }
  19049. // Particles
  19050. var activeCamera = this._scene.activeCamera;
  19051. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  19052. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  19053. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  19054. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  19055. continue;
  19056. }
  19057. var emitter = particleSystem.emitter;
  19058. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  19059. this._scene._activeParticles.addCount(particleSystem.render(), false);
  19060. }
  19061. }
  19062. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  19063. };
  19064. RenderingGroup.prototype._renderSprites = function () {
  19065. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  19066. return;
  19067. }
  19068. // Sprites
  19069. var activeCamera = this._scene.activeCamera;
  19070. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  19071. for (var id = 0; id < this._spriteManagers.length; id++) {
  19072. var spriteManager = this._spriteManagers.data[id];
  19073. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  19074. spriteManager.render();
  19075. }
  19076. }
  19077. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  19078. };
  19079. return RenderingGroup;
  19080. }());
  19081. BABYLON.RenderingGroup = RenderingGroup;
  19082. })(BABYLON || (BABYLON = {}));
  19083. //# sourceMappingURL=babylon.renderingGroup.js.map
  19084. var BABYLON;
  19085. (function (BABYLON) {
  19086. var ClickInfo = /** @class */ (function () {
  19087. function ClickInfo() {
  19088. this._singleClick = false;
  19089. this._doubleClick = false;
  19090. this._hasSwiped = false;
  19091. this._ignore = false;
  19092. }
  19093. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  19094. get: function () {
  19095. return this._singleClick;
  19096. },
  19097. set: function (b) {
  19098. this._singleClick = b;
  19099. },
  19100. enumerable: true,
  19101. configurable: true
  19102. });
  19103. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  19104. get: function () {
  19105. return this._doubleClick;
  19106. },
  19107. set: function (b) {
  19108. this._doubleClick = b;
  19109. },
  19110. enumerable: true,
  19111. configurable: true
  19112. });
  19113. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  19114. get: function () {
  19115. return this._hasSwiped;
  19116. },
  19117. set: function (b) {
  19118. this._hasSwiped = b;
  19119. },
  19120. enumerable: true,
  19121. configurable: true
  19122. });
  19123. Object.defineProperty(ClickInfo.prototype, "ignore", {
  19124. get: function () {
  19125. return this._ignore;
  19126. },
  19127. set: function (b) {
  19128. this._ignore = b;
  19129. },
  19130. enumerable: true,
  19131. configurable: true
  19132. });
  19133. return ClickInfo;
  19134. }());
  19135. /**
  19136. * This class is used by the onRenderingGroupObservable
  19137. */
  19138. var RenderingGroupInfo = /** @class */ (function () {
  19139. function RenderingGroupInfo() {
  19140. }
  19141. /**
  19142. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  19143. * This stage will be fired no matter what
  19144. */
  19145. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  19146. /**
  19147. * Called before opaque object are rendered.
  19148. * This stage will be fired only if there's 3D Opaque content to render
  19149. */
  19150. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  19151. /**
  19152. * Called after the opaque objects are rendered and before the transparent ones
  19153. * This stage will be fired only if there's 3D transparent content to render
  19154. */
  19155. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  19156. /**
  19157. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  19158. * This stage will be fired no matter what
  19159. */
  19160. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  19161. return RenderingGroupInfo;
  19162. }());
  19163. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  19164. /**
  19165. * Represents a scene to be rendered by the engine.
  19166. * @see http://doc.babylonjs.com/page.php?p=21911
  19167. */
  19168. var Scene = /** @class */ (function () {
  19169. /**
  19170. * @constructor
  19171. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  19172. */
  19173. function Scene(engine) {
  19174. // Members
  19175. this.autoClear = true;
  19176. this.autoClearDepthAndStencil = true;
  19177. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  19178. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  19179. this.forceWireframe = false;
  19180. this._forcePointsCloud = false;
  19181. this.forceShowBoundingBoxes = false;
  19182. this.animationsEnabled = true;
  19183. this.useConstantAnimationDeltaTime = false;
  19184. this.constantlyUpdateMeshUnderPointer = false;
  19185. this.hoverCursor = "pointer";
  19186. this.defaultCursor = "";
  19187. /**
  19188. * This is used to call preventDefault() on pointer down
  19189. * in order to block unwanted artifacts like system double clicks
  19190. */
  19191. this.preventDefaultOnPointerDown = true;
  19192. // Metadata
  19193. this.metadata = null;
  19194. /**
  19195. * An event triggered when the scene is disposed.
  19196. * @type {BABYLON.Observable}
  19197. */
  19198. this.onDisposeObservable = new BABYLON.Observable();
  19199. /**
  19200. * An event triggered before rendering the scene (right after animations and physics)
  19201. * @type {BABYLON.Observable}
  19202. */
  19203. this.onBeforeRenderObservable = new BABYLON.Observable();
  19204. /**
  19205. * An event triggered after rendering the scene
  19206. * @type {BABYLON.Observable}
  19207. */
  19208. this.onAfterRenderObservable = new BABYLON.Observable();
  19209. /**
  19210. * An event triggered before animating the scene
  19211. * @type {BABYLON.Observable}
  19212. */
  19213. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  19214. /**
  19215. * An event triggered after animations processing
  19216. * @type {BABYLON.Observable}
  19217. */
  19218. this.onAfterAnimationsObservable = new BABYLON.Observable();
  19219. /**
  19220. * An event triggered before draw calls are ready to be sent
  19221. * @type {BABYLON.Observable}
  19222. */
  19223. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  19224. /**
  19225. * An event triggered after draw calls have been sent
  19226. * @type {BABYLON.Observable}
  19227. */
  19228. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  19229. /**
  19230. * An event triggered when physic simulation is about to be run
  19231. * @type {BABYLON.Observable}
  19232. */
  19233. this.onBeforePhysicsObservable = new BABYLON.Observable();
  19234. /**
  19235. * An event triggered when physic simulation has been done
  19236. * @type {BABYLON.Observable}
  19237. */
  19238. this.onAfterPhysicsObservable = new BABYLON.Observable();
  19239. /**
  19240. * An event triggered when the scene is ready
  19241. * @type {BABYLON.Observable}
  19242. */
  19243. this.onReadyObservable = new BABYLON.Observable();
  19244. /**
  19245. * An event triggered before rendering a camera
  19246. * @type {BABYLON.Observable}
  19247. */
  19248. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  19249. /**
  19250. * An event triggered after rendering a camera
  19251. * @type {BABYLON.Observable}
  19252. */
  19253. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  19254. /**
  19255. * An event triggered when active meshes evaluation is about to start
  19256. * @type {BABYLON.Observable}
  19257. */
  19258. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19259. /**
  19260. * An event triggered when active meshes evaluation is done
  19261. * @type {BABYLON.Observable}
  19262. */
  19263. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  19264. /**
  19265. * An event triggered when particles rendering is about to start
  19266. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19267. * @type {BABYLON.Observable}
  19268. */
  19269. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  19270. /**
  19271. * An event triggered when particles rendering is done
  19272. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  19273. * @type {BABYLON.Observable}
  19274. */
  19275. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  19276. /**
  19277. * An event triggered when sprites rendering is about to start
  19278. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19279. * @type {BABYLON.Observable}
  19280. */
  19281. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  19282. /**
  19283. * An event triggered when sprites rendering is done
  19284. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  19285. * @type {BABYLON.Observable}
  19286. */
  19287. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  19288. /**
  19289. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  19290. * @type {BABYLON.Observable}
  19291. */
  19292. this.onDataLoadedObservable = new BABYLON.Observable();
  19293. /**
  19294. * An event triggered when a camera is created
  19295. * @type {BABYLON.Observable}
  19296. */
  19297. this.onNewCameraAddedObservable = new BABYLON.Observable();
  19298. /**
  19299. * An event triggered when a camera is removed
  19300. * @type {BABYLON.Observable}
  19301. */
  19302. this.onCameraRemovedObservable = new BABYLON.Observable();
  19303. /**
  19304. * An event triggered when a light is created
  19305. * @type {BABYLON.Observable}
  19306. */
  19307. this.onNewLightAddedObservable = new BABYLON.Observable();
  19308. /**
  19309. * An event triggered when a light is removed
  19310. * @type {BABYLON.Observable}
  19311. */
  19312. this.onLightRemovedObservable = new BABYLON.Observable();
  19313. /**
  19314. * An event triggered when a geometry is created
  19315. * @type {BABYLON.Observable}
  19316. */
  19317. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  19318. /**
  19319. * An event triggered when a geometry is removed
  19320. * @type {BABYLON.Observable}
  19321. */
  19322. this.onGeometryRemovedObservable = new BABYLON.Observable();
  19323. /**
  19324. * An event triggered when a transform node is created
  19325. * @type {BABYLON.Observable}
  19326. */
  19327. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  19328. /**
  19329. * An event triggered when a transform node is removed
  19330. * @type {BABYLON.Observable}
  19331. */
  19332. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  19333. /**
  19334. * An event triggered when a mesh is created
  19335. * @type {BABYLON.Observable}
  19336. */
  19337. this.onNewMeshAddedObservable = new BABYLON.Observable();
  19338. /**
  19339. * An event triggered when a mesh is removed
  19340. * @type {BABYLON.Observable}
  19341. */
  19342. this.onMeshRemovedObservable = new BABYLON.Observable();
  19343. /**
  19344. * An event triggered when render targets are about to be rendered
  19345. * Can happen multiple times per frame.
  19346. * @type {BABYLON.Observable}
  19347. */
  19348. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  19349. /**
  19350. * An event triggered when render targets were rendered.
  19351. * Can happen multiple times per frame.
  19352. * @type {BABYLON.Observable}
  19353. */
  19354. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  19355. /**
  19356. * An event triggered before calculating deterministic simulation step
  19357. * @type {BABYLON.Observable}
  19358. */
  19359. this.onBeforeStepObservable = new BABYLON.Observable();
  19360. /**
  19361. * An event triggered after calculating deterministic simulation step
  19362. * @type {BABYLON.Observable}
  19363. */
  19364. this.onAfterStepObservable = new BABYLON.Observable();
  19365. /**
  19366. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  19367. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  19368. * 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)
  19369. */
  19370. this.onRenderingGroupObservable = new BABYLON.Observable();
  19371. // Animations
  19372. this.animations = [];
  19373. /**
  19374. * 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).
  19375. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  19376. */
  19377. this.onPrePointerObservable = new BABYLON.Observable();
  19378. /**
  19379. * Observable event triggered each time an input event is received from the rendering canvas
  19380. */
  19381. this.onPointerObservable = new BABYLON.Observable();
  19382. this._meshPickProceed = false;
  19383. this._currentPickResult = null;
  19384. this._previousPickResult = null;
  19385. this._totalPointersPressed = 0;
  19386. this._doubleClickOccured = false;
  19387. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  19388. this.cameraToUseForPointers = null;
  19389. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  19390. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  19391. this._startingPointerTime = 0;
  19392. this._previousStartingPointerTime = 0;
  19393. // Deterministic lockstep
  19394. this._timeAccumulator = 0;
  19395. this._currentStepId = 0;
  19396. this._currentInternalStep = 0;
  19397. // Keyboard
  19398. /**
  19399. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  19400. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  19401. */
  19402. this.onPreKeyboardObservable = new BABYLON.Observable();
  19403. /**
  19404. * Observable event triggered each time an keyboard event is received from the hosting window
  19405. */
  19406. this.onKeyboardObservable = new BABYLON.Observable();
  19407. // Coordinate system
  19408. /**
  19409. * use right-handed coordinate system on this scene.
  19410. * @type {boolean}
  19411. */
  19412. this._useRightHandedSystem = false;
  19413. // Fog
  19414. this._fogEnabled = true;
  19415. this._fogMode = Scene.FOGMODE_NONE;
  19416. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  19417. this.fogDensity = 0.1;
  19418. this.fogStart = 0;
  19419. this.fogEnd = 1000.0;
  19420. // Lights
  19421. /**
  19422. * is shadow enabled on this scene.
  19423. * @type {boolean}
  19424. */
  19425. this._shadowsEnabled = true;
  19426. /**
  19427. * is light enabled on this scene.
  19428. * @type {boolean}
  19429. */
  19430. this._lightsEnabled = true;
  19431. /**
  19432. * All of the lights added to this scene.
  19433. * @see BABYLON.Light
  19434. * @type {BABYLON.Light[]}
  19435. */
  19436. this.lights = new Array();
  19437. // Cameras
  19438. /** All of the cameras added to this scene. */
  19439. this.cameras = new Array();
  19440. /** All of the active cameras added to this scene. */
  19441. this.activeCameras = new Array();
  19442. // Meshes
  19443. /**
  19444. * All of the tranform nodes added to this scene.
  19445. * @see BABYLON.TransformNode
  19446. * @type {BABYLON.TransformNode[]}
  19447. */
  19448. this.transformNodes = new Array();
  19449. /**
  19450. * All of the (abstract) meshes added to this scene.
  19451. * @see BABYLON.AbstractMesh
  19452. * @type {BABYLON.AbstractMesh[]}
  19453. */
  19454. this.meshes = new Array();
  19455. /**
  19456. * All of the animation groups added to this scene.
  19457. * @see BABYLON.AnimationGroup
  19458. * @type {BABYLON.AnimationGroup[]}
  19459. */
  19460. this.animationGroups = new Array();
  19461. // Geometries
  19462. this._geometries = new Array();
  19463. this.materials = new Array();
  19464. this.multiMaterials = new Array();
  19465. // Textures
  19466. this._texturesEnabled = true;
  19467. this.textures = new Array();
  19468. // Particles
  19469. this.particlesEnabled = true;
  19470. this.particleSystems = new Array();
  19471. // Sprites
  19472. this.spritesEnabled = true;
  19473. this.spriteManagers = new Array();
  19474. // Layers
  19475. this.layers = new Array();
  19476. this.highlightLayers = new Array();
  19477. // Skeletons
  19478. this._skeletonsEnabled = true;
  19479. this.skeletons = new Array();
  19480. // Morph targets
  19481. this.morphTargetManagers = new Array();
  19482. // Lens flares
  19483. this.lensFlaresEnabled = true;
  19484. this.lensFlareSystems = new Array();
  19485. // Collisions
  19486. this.collisionsEnabled = true;
  19487. /** Defines the gravity applied to this scene */
  19488. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  19489. // Postprocesses
  19490. this.postProcesses = new Array();
  19491. this.postProcessesEnabled = true;
  19492. // Customs render targets
  19493. this.renderTargetsEnabled = true;
  19494. this.dumpNextRenderTargets = false;
  19495. this.customRenderTargets = new Array();
  19496. // Imported meshes
  19497. this.importedMeshesFiles = new Array();
  19498. // Probes
  19499. this.probesEnabled = true;
  19500. this.reflectionProbes = new Array();
  19501. this._actionManagers = new Array();
  19502. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  19503. // Procedural textures
  19504. this.proceduralTexturesEnabled = true;
  19505. this._proceduralTextures = new Array();
  19506. this.soundTracks = new Array();
  19507. this._audioEnabled = true;
  19508. this._headphone = false;
  19509. // Performance counters
  19510. this._totalVertices = new BABYLON.PerfCounter();
  19511. this._activeIndices = new BABYLON.PerfCounter();
  19512. this._activeParticles = new BABYLON.PerfCounter();
  19513. this._activeBones = new BABYLON.PerfCounter();
  19514. this._animationTime = 0;
  19515. this.animationTimeScale = 1;
  19516. this._renderId = 0;
  19517. this._executeWhenReadyTimeoutId = -1;
  19518. this._intermediateRendering = false;
  19519. this._viewUpdateFlag = -1;
  19520. this._projectionUpdateFlag = -1;
  19521. this._alternateViewUpdateFlag = -1;
  19522. this._alternateProjectionUpdateFlag = -1;
  19523. this._toBeDisposed = new BABYLON.SmartArray(256);
  19524. this._activeRequests = new Array();
  19525. this._pendingData = new Array();
  19526. this._isDisposed = false;
  19527. this.dispatchAllSubMeshesOfActiveMeshes = false;
  19528. this._activeMeshes = new BABYLON.SmartArray(256);
  19529. this._processedMaterials = new BABYLON.SmartArray(256);
  19530. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  19531. this._activeParticleSystems = new BABYLON.SmartArray(256);
  19532. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  19533. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  19534. this._activeAnimatables = new Array();
  19535. this._transformMatrix = BABYLON.Matrix.Zero();
  19536. this._useAlternateCameraConfiguration = false;
  19537. this._alternateRendering = false;
  19538. this.requireLightSorting = false;
  19539. this._activeMeshesFrozen = false;
  19540. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  19541. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  19542. this._engine.scenes.push(this);
  19543. this._uid = null;
  19544. this._renderingManager = new BABYLON.RenderingManager(this);
  19545. this.postProcessManager = new BABYLON.PostProcessManager(this);
  19546. if (BABYLON.OutlineRenderer) {
  19547. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  19548. }
  19549. if (BABYLON.Tools.IsWindowObjectExist()) {
  19550. this.attachControl();
  19551. }
  19552. //simplification queue
  19553. if (BABYLON.SimplificationQueue) {
  19554. this.simplificationQueue = new BABYLON.SimplificationQueue();
  19555. }
  19556. //collision coordinator initialization. For now legacy per default.
  19557. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  19558. // Uniform Buffer
  19559. this._createUbo();
  19560. // Default Image processing definition.
  19561. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  19562. }
  19563. Object.defineProperty(Scene, "FOGMODE_NONE", {
  19564. /** The fog is deactivated */
  19565. get: function () {
  19566. return Scene._FOGMODE_NONE;
  19567. },
  19568. enumerable: true,
  19569. configurable: true
  19570. });
  19571. Object.defineProperty(Scene, "FOGMODE_EXP", {
  19572. /** The fog density is following an exponential function */
  19573. get: function () {
  19574. return Scene._FOGMODE_EXP;
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  19580. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  19581. get: function () {
  19582. return Scene._FOGMODE_EXP2;
  19583. },
  19584. enumerable: true,
  19585. configurable: true
  19586. });
  19587. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  19588. /** The fog density is following a linear function. */
  19589. get: function () {
  19590. return Scene._FOGMODE_LINEAR;
  19591. },
  19592. enumerable: true,
  19593. configurable: true
  19594. });
  19595. Object.defineProperty(Scene.prototype, "environmentTexture", {
  19596. /**
  19597. * Texture used in all pbr material as the reflection texture.
  19598. * As in the majority of the scene they are the same (exception for multi room and so on),
  19599. * this is easier to reference from here than from all the materials.
  19600. */
  19601. get: function () {
  19602. return this._environmentTexture;
  19603. },
  19604. /**
  19605. * Texture used in all pbr material as the reflection texture.
  19606. * As in the majority of the scene they are the same (exception for multi room and so on),
  19607. * this is easier to set here than in all the materials.
  19608. */
  19609. set: function (value) {
  19610. if (this._environmentTexture === value) {
  19611. return;
  19612. }
  19613. this._environmentTexture = value;
  19614. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19615. },
  19616. enumerable: true,
  19617. configurable: true
  19618. });
  19619. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  19620. /**
  19621. * Default image processing configuration used either in the rendering
  19622. * Forward main pass or through the imageProcessingPostProcess if present.
  19623. * As in the majority of the scene they are the same (exception for multi camera),
  19624. * this is easier to reference from here than from all the materials and post process.
  19625. *
  19626. * No setter as we it is a shared configuration, you can set the values instead.
  19627. */
  19628. get: function () {
  19629. return this._imageProcessingConfiguration;
  19630. },
  19631. enumerable: true,
  19632. configurable: true
  19633. });
  19634. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  19635. get: function () {
  19636. return this._forcePointsCloud;
  19637. },
  19638. set: function (value) {
  19639. if (this._forcePointsCloud === value) {
  19640. return;
  19641. }
  19642. this._forcePointsCloud = value;
  19643. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19644. },
  19645. enumerable: true,
  19646. configurable: true
  19647. });
  19648. Object.defineProperty(Scene.prototype, "onDispose", {
  19649. /** A function to be executed when this scene is disposed. */
  19650. set: function (callback) {
  19651. if (this._onDisposeObserver) {
  19652. this.onDisposeObservable.remove(this._onDisposeObserver);
  19653. }
  19654. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  19655. },
  19656. enumerable: true,
  19657. configurable: true
  19658. });
  19659. Object.defineProperty(Scene.prototype, "beforeRender", {
  19660. /** A function to be executed before rendering this scene */
  19661. set: function (callback) {
  19662. if (this._onBeforeRenderObserver) {
  19663. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  19664. }
  19665. if (callback) {
  19666. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  19667. }
  19668. },
  19669. enumerable: true,
  19670. configurable: true
  19671. });
  19672. Object.defineProperty(Scene.prototype, "afterRender", {
  19673. /** A function to be executed after rendering this scene */
  19674. set: function (callback) {
  19675. if (this._onAfterRenderObserver) {
  19676. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  19677. }
  19678. if (callback) {
  19679. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  19680. }
  19681. },
  19682. enumerable: true,
  19683. configurable: true
  19684. });
  19685. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  19686. set: function (callback) {
  19687. if (this._onBeforeCameraRenderObserver) {
  19688. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  19689. }
  19690. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  19691. },
  19692. enumerable: true,
  19693. configurable: true
  19694. });
  19695. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  19696. set: function (callback) {
  19697. if (this._onAfterCameraRenderObserver) {
  19698. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  19699. }
  19700. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  19701. },
  19702. enumerable: true,
  19703. configurable: true
  19704. });
  19705. Object.defineProperty(Scene.prototype, "gamepadManager", {
  19706. get: function () {
  19707. if (!this._gamepadManager) {
  19708. this._gamepadManager = new BABYLON.GamepadManager(this);
  19709. }
  19710. return this._gamepadManager;
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  19716. get: function () {
  19717. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  19723. get: function () {
  19724. return this._useRightHandedSystem;
  19725. },
  19726. set: function (value) {
  19727. if (this._useRightHandedSystem === value) {
  19728. return;
  19729. }
  19730. this._useRightHandedSystem = value;
  19731. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19732. },
  19733. enumerable: true,
  19734. configurable: true
  19735. });
  19736. Scene.prototype.setStepId = function (newStepId) {
  19737. this._currentStepId = newStepId;
  19738. };
  19739. ;
  19740. Scene.prototype.getStepId = function () {
  19741. return this._currentStepId;
  19742. };
  19743. ;
  19744. Scene.prototype.getInternalStep = function () {
  19745. return this._currentInternalStep;
  19746. };
  19747. ;
  19748. Object.defineProperty(Scene.prototype, "fogEnabled", {
  19749. get: function () {
  19750. return this._fogEnabled;
  19751. },
  19752. /**
  19753. * is fog enabled on this scene.
  19754. */
  19755. set: function (value) {
  19756. if (this._fogEnabled === value) {
  19757. return;
  19758. }
  19759. this._fogEnabled = value;
  19760. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(Scene.prototype, "fogMode", {
  19766. get: function () {
  19767. return this._fogMode;
  19768. },
  19769. set: function (value) {
  19770. if (this._fogMode === value) {
  19771. return;
  19772. }
  19773. this._fogMode = value;
  19774. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  19775. },
  19776. enumerable: true,
  19777. configurable: true
  19778. });
  19779. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  19780. get: function () {
  19781. return this._shadowsEnabled;
  19782. },
  19783. set: function (value) {
  19784. if (this._shadowsEnabled === value) {
  19785. return;
  19786. }
  19787. this._shadowsEnabled = value;
  19788. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19789. },
  19790. enumerable: true,
  19791. configurable: true
  19792. });
  19793. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  19794. get: function () {
  19795. return this._lightsEnabled;
  19796. },
  19797. set: function (value) {
  19798. if (this._lightsEnabled === value) {
  19799. return;
  19800. }
  19801. this._lightsEnabled = value;
  19802. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  19803. },
  19804. enumerable: true,
  19805. configurable: true
  19806. });
  19807. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  19808. /** The default material used on meshes when no material is affected */
  19809. get: function () {
  19810. if (!this._defaultMaterial) {
  19811. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  19812. }
  19813. return this._defaultMaterial;
  19814. },
  19815. /** The default material used on meshes when no material is affected */
  19816. set: function (value) {
  19817. this._defaultMaterial = value;
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  19823. get: function () {
  19824. return this._texturesEnabled;
  19825. },
  19826. set: function (value) {
  19827. if (this._texturesEnabled === value) {
  19828. return;
  19829. }
  19830. this._texturesEnabled = value;
  19831. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19832. },
  19833. enumerable: true,
  19834. configurable: true
  19835. });
  19836. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  19837. get: function () {
  19838. return this._skeletonsEnabled;
  19839. },
  19840. set: function (value) {
  19841. if (this._skeletonsEnabled === value) {
  19842. return;
  19843. }
  19844. this._skeletonsEnabled = value;
  19845. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  19846. },
  19847. enumerable: true,
  19848. configurable: true
  19849. });
  19850. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  19851. get: function () {
  19852. if (!this._postProcessRenderPipelineManager) {
  19853. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  19854. }
  19855. return this._postProcessRenderPipelineManager;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  19861. get: function () {
  19862. if (!this._mainSoundTrack) {
  19863. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  19864. }
  19865. return this._mainSoundTrack;
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  19871. get: function () {
  19872. return this._alternateRendering;
  19873. },
  19874. enumerable: true,
  19875. configurable: true
  19876. });
  19877. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  19878. get: function () {
  19879. return this._frustumPlanes;
  19880. },
  19881. enumerable: true,
  19882. configurable: true
  19883. });
  19884. Object.defineProperty(Scene.prototype, "debugLayer", {
  19885. // Properties
  19886. get: function () {
  19887. if (!this._debugLayer) {
  19888. this._debugLayer = new BABYLON.DebugLayer(this);
  19889. }
  19890. return this._debugLayer;
  19891. },
  19892. enumerable: true,
  19893. configurable: true
  19894. });
  19895. Object.defineProperty(Scene.prototype, "workerCollisions", {
  19896. get: function () {
  19897. return this._workerCollisions;
  19898. },
  19899. set: function (enabled) {
  19900. if (!BABYLON.CollisionCoordinatorLegacy) {
  19901. return;
  19902. }
  19903. enabled = (enabled && !!Worker);
  19904. this._workerCollisions = enabled;
  19905. if (this.collisionCoordinator) {
  19906. this.collisionCoordinator.destroy();
  19907. }
  19908. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19909. this.collisionCoordinator.init(this);
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19915. get: function () {
  19916. return this._selectionOctree;
  19917. },
  19918. enumerable: true,
  19919. configurable: true
  19920. });
  19921. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19922. /**
  19923. * The mesh that is currently under the pointer.
  19924. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19925. */
  19926. get: function () {
  19927. return this._pointerOverMesh;
  19928. },
  19929. enumerable: true,
  19930. configurable: true
  19931. });
  19932. Object.defineProperty(Scene.prototype, "pointerX", {
  19933. /**
  19934. * Current on-screen X position of the pointer
  19935. * @return {number} X position of the pointer
  19936. */
  19937. get: function () {
  19938. return this._pointerX;
  19939. },
  19940. enumerable: true,
  19941. configurable: true
  19942. });
  19943. Object.defineProperty(Scene.prototype, "pointerY", {
  19944. /**
  19945. * Current on-screen Y position of the pointer
  19946. * @return {number} Y position of the pointer
  19947. */
  19948. get: function () {
  19949. return this._pointerY;
  19950. },
  19951. enumerable: true,
  19952. configurable: true
  19953. });
  19954. Scene.prototype.getCachedMaterial = function () {
  19955. return this._cachedMaterial;
  19956. };
  19957. Scene.prototype.getCachedEffect = function () {
  19958. return this._cachedEffect;
  19959. };
  19960. Scene.prototype.getCachedVisibility = function () {
  19961. return this._cachedVisibility;
  19962. };
  19963. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19964. if (visibility === void 0) { visibility = 1; }
  19965. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19966. };
  19967. Scene.prototype.getBoundingBoxRenderer = function () {
  19968. if (!this._boundingBoxRenderer) {
  19969. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19970. }
  19971. return this._boundingBoxRenderer;
  19972. };
  19973. Scene.prototype.getOutlineRenderer = function () {
  19974. return this._outlineRenderer;
  19975. };
  19976. Scene.prototype.getEngine = function () {
  19977. return this._engine;
  19978. };
  19979. Scene.prototype.getTotalVertices = function () {
  19980. return this._totalVertices.current;
  19981. };
  19982. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19983. get: function () {
  19984. return this._totalVertices;
  19985. },
  19986. enumerable: true,
  19987. configurable: true
  19988. });
  19989. Scene.prototype.getActiveIndices = function () {
  19990. return this._activeIndices.current;
  19991. };
  19992. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19993. get: function () {
  19994. return this._activeIndices;
  19995. },
  19996. enumerable: true,
  19997. configurable: true
  19998. });
  19999. Scene.prototype.getActiveParticles = function () {
  20000. return this._activeParticles.current;
  20001. };
  20002. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  20003. get: function () {
  20004. return this._activeParticles;
  20005. },
  20006. enumerable: true,
  20007. configurable: true
  20008. });
  20009. Scene.prototype.getActiveBones = function () {
  20010. return this._activeBones.current;
  20011. };
  20012. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  20013. get: function () {
  20014. return this._activeBones;
  20015. },
  20016. enumerable: true,
  20017. configurable: true
  20018. });
  20019. // Stats
  20020. Scene.prototype.getInterFramePerfCounter = function () {
  20021. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20022. return 0;
  20023. };
  20024. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  20025. get: function () {
  20026. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20027. return null;
  20028. },
  20029. enumerable: true,
  20030. configurable: true
  20031. });
  20032. Scene.prototype.getLastFrameDuration = function () {
  20033. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  20034. return 0;
  20035. };
  20036. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  20037. get: function () {
  20038. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  20039. return null;
  20040. },
  20041. enumerable: true,
  20042. configurable: true
  20043. });
  20044. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  20045. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  20046. return 0;
  20047. };
  20048. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  20049. get: function () {
  20050. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20051. return null;
  20052. },
  20053. enumerable: true,
  20054. configurable: true
  20055. });
  20056. Scene.prototype.getActiveMeshes = function () {
  20057. return this._activeMeshes;
  20058. };
  20059. Scene.prototype.getRenderTargetsDuration = function () {
  20060. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  20061. return 0;
  20062. };
  20063. Scene.prototype.getRenderDuration = function () {
  20064. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  20065. return 0;
  20066. };
  20067. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  20068. get: function () {
  20069. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20070. return null;
  20071. },
  20072. enumerable: true,
  20073. configurable: true
  20074. });
  20075. Scene.prototype.getParticlesDuration = function () {
  20076. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  20077. return 0;
  20078. };
  20079. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  20080. get: function () {
  20081. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  20082. return null;
  20083. },
  20084. enumerable: true,
  20085. configurable: true
  20086. });
  20087. Scene.prototype.getSpritesDuration = function () {
  20088. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  20089. return 0;
  20090. };
  20091. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  20092. get: function () {
  20093. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  20094. return null;
  20095. },
  20096. enumerable: true,
  20097. configurable: true
  20098. });
  20099. Scene.prototype.getAnimationRatio = function () {
  20100. return this._animationRatio;
  20101. };
  20102. Scene.prototype.getRenderId = function () {
  20103. return this._renderId;
  20104. };
  20105. Scene.prototype.incrementRenderId = function () {
  20106. this._renderId++;
  20107. };
  20108. Scene.prototype._updatePointerPosition = function (evt) {
  20109. var canvasRect = this._engine.getRenderingCanvasClientRect();
  20110. if (!canvasRect) {
  20111. return;
  20112. }
  20113. this._pointerX = evt.clientX - canvasRect.left;
  20114. this._pointerY = evt.clientY - canvasRect.top;
  20115. this._unTranslatedPointerX = this._pointerX;
  20116. this._unTranslatedPointerY = this._pointerY;
  20117. };
  20118. Scene.prototype._createUbo = function () {
  20119. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20120. this._sceneUbo.addUniform("viewProjection", 16);
  20121. this._sceneUbo.addUniform("view", 16);
  20122. };
  20123. Scene.prototype._createAlternateUbo = function () {
  20124. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  20125. this._alternateSceneUbo.addUniform("viewProjection", 16);
  20126. this._alternateSceneUbo.addUniform("view", 16);
  20127. };
  20128. // Pointers handling
  20129. /**
  20130. * Use this method to simulate a pointer move on a mesh
  20131. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20132. */
  20133. Scene.prototype.simulatePointerMove = function (pickResult) {
  20134. var evt = new PointerEvent("pointermove");
  20135. return this._processPointerMove(pickResult, evt);
  20136. };
  20137. Scene.prototype._processPointerMove = function (pickResult, evt) {
  20138. var canvas = this._engine.getRenderingCanvas();
  20139. if (!canvas) {
  20140. return this;
  20141. }
  20142. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20143. this.setPointerOverSprite(null);
  20144. this.setPointerOverMesh(pickResult.pickedMesh);
  20145. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  20146. if (this._pointerOverMesh.actionManager.hoverCursor) {
  20147. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  20148. }
  20149. else {
  20150. canvas.style.cursor = this.hoverCursor;
  20151. }
  20152. }
  20153. else {
  20154. canvas.style.cursor = this.defaultCursor;
  20155. }
  20156. }
  20157. else {
  20158. this.setPointerOverMesh(null);
  20159. // Sprites
  20160. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  20161. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20162. this.setPointerOverSprite(pickResult.pickedSprite);
  20163. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  20164. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  20165. }
  20166. else {
  20167. canvas.style.cursor = this.hoverCursor;
  20168. }
  20169. }
  20170. else {
  20171. this.setPointerOverSprite(null);
  20172. // Restore pointer
  20173. canvas.style.cursor = this.defaultCursor;
  20174. }
  20175. }
  20176. if (pickResult) {
  20177. if (this.onPointerMove) {
  20178. this.onPointerMove(evt, pickResult);
  20179. }
  20180. if (this.onPointerObservable.hasObservers()) {
  20181. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20182. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20183. this.onPointerObservable.notifyObservers(pi, type);
  20184. }
  20185. }
  20186. return this;
  20187. };
  20188. /**
  20189. * Use this method to simulate a pointer down on a mesh
  20190. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20191. */
  20192. Scene.prototype.simulatePointerDown = function (pickResult) {
  20193. var evt = new PointerEvent("pointerdown");
  20194. return this._processPointerDown(pickResult, evt);
  20195. };
  20196. Scene.prototype._processPointerDown = function (pickResult, evt) {
  20197. var _this = this;
  20198. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  20199. this._pickedDownMesh = pickResult.pickedMesh;
  20200. var actionManager = pickResult.pickedMesh.actionManager;
  20201. if (actionManager) {
  20202. if (actionManager.hasPickTriggers) {
  20203. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20204. switch (evt.button) {
  20205. case 0:
  20206. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20207. break;
  20208. case 1:
  20209. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20210. break;
  20211. case 2:
  20212. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20213. break;
  20214. }
  20215. }
  20216. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  20217. window.setTimeout(function () {
  20218. 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);
  20219. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  20220. if (_this._totalPointersPressed !== 0 &&
  20221. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  20222. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  20223. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  20224. _this._startingPointerTime = 0;
  20225. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20226. }
  20227. }
  20228. }, Scene.LongPressDelay);
  20229. }
  20230. }
  20231. }
  20232. if (pickResult) {
  20233. if (this.onPointerDown) {
  20234. this.onPointerDown(evt, pickResult);
  20235. }
  20236. if (this.onPointerObservable.hasObservers()) {
  20237. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20238. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20239. this.onPointerObservable.notifyObservers(pi, type);
  20240. }
  20241. }
  20242. return this;
  20243. };
  20244. /**
  20245. * Use this method to simulate a pointer up on a mesh
  20246. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  20247. */
  20248. Scene.prototype.simulatePointerUp = function (pickResult) {
  20249. var evt = new PointerEvent("pointerup");
  20250. var clickInfo = new ClickInfo();
  20251. clickInfo.singleClick = true;
  20252. clickInfo.ignore = true;
  20253. return this._processPointerUp(pickResult, evt, clickInfo);
  20254. };
  20255. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  20256. if (pickResult && pickResult && pickResult.pickedMesh) {
  20257. this._pickedUpMesh = pickResult.pickedMesh;
  20258. if (this._pickedDownMesh === this._pickedUpMesh) {
  20259. if (this.onPointerPick) {
  20260. this.onPointerPick(evt, pickResult);
  20261. }
  20262. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  20263. var type = BABYLON.PointerEventTypes.POINTERPICK;
  20264. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20265. this.onPointerObservable.notifyObservers(pi, type);
  20266. }
  20267. }
  20268. if (pickResult.pickedMesh.actionManager) {
  20269. if (clickInfo.ignore) {
  20270. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20271. }
  20272. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  20273. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20274. }
  20275. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20276. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  20277. }
  20278. }
  20279. }
  20280. if (this._pickedDownMesh &&
  20281. this._pickedDownMesh.actionManager &&
  20282. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  20283. this._pickedDownMesh !== this._pickedUpMesh) {
  20284. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  20285. }
  20286. if (this.onPointerUp) {
  20287. this.onPointerUp(evt, pickResult);
  20288. }
  20289. if (this.onPointerObservable.hasObservers()) {
  20290. if (!clickInfo.ignore) {
  20291. if (!clickInfo.hasSwiped) {
  20292. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20293. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20294. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20295. this.onPointerObservable.notifyObservers(pi, type);
  20296. }
  20297. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20298. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20299. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20300. this.onPointerObservable.notifyObservers(pi, type);
  20301. }
  20302. }
  20303. }
  20304. else {
  20305. var type = BABYLON.PointerEventTypes.POINTERUP;
  20306. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  20307. this.onPointerObservable.notifyObservers(pi, type);
  20308. }
  20309. }
  20310. return this;
  20311. };
  20312. /**
  20313. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  20314. * @param attachUp defines if you want to attach events to pointerup
  20315. * @param attachDown defines if you want to attach events to pointerdown
  20316. * @param attachMove defines if you want to attach events to pointermove
  20317. */
  20318. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  20319. var _this = this;
  20320. if (attachUp === void 0) { attachUp = true; }
  20321. if (attachDown === void 0) { attachDown = true; }
  20322. if (attachMove === void 0) { attachMove = true; }
  20323. this._initActionManager = function (act, clickInfo) {
  20324. if (!_this._meshPickProceed) {
  20325. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20326. _this._currentPickResult = pickResult;
  20327. if (pickResult) {
  20328. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  20329. }
  20330. _this._meshPickProceed = true;
  20331. }
  20332. return act;
  20333. };
  20334. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  20335. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  20336. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  20337. btn !== _this._previousButtonPressed) {
  20338. _this._doubleClickOccured = false;
  20339. clickInfo.singleClick = true;
  20340. clickInfo.ignore = false;
  20341. cb(clickInfo, _this._currentPickResult);
  20342. }
  20343. };
  20344. this._initClickEvent = function (obs1, obs2, evt, cb) {
  20345. var clickInfo = new ClickInfo();
  20346. _this._currentPickResult = null;
  20347. var act = null;
  20348. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  20349. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  20350. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20351. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  20352. act = _this._initActionManager(act, clickInfo);
  20353. if (act)
  20354. checkPicking = act.hasPickTriggers;
  20355. }
  20356. if (checkPicking) {
  20357. var btn = evt.button;
  20358. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  20359. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  20360. if (!clickInfo.hasSwiped) {
  20361. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  20362. if (!checkSingleClickImmediately) {
  20363. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  20364. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20365. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20366. act = _this._initActionManager(act, clickInfo);
  20367. if (act)
  20368. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20369. }
  20370. }
  20371. if (checkSingleClickImmediately) {
  20372. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  20373. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  20374. btn !== _this._previousButtonPressed) {
  20375. clickInfo.singleClick = true;
  20376. cb(clickInfo, _this._currentPickResult);
  20377. }
  20378. }
  20379. else {
  20380. // wait that no double click has been raised during the double click delay
  20381. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20382. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  20383. }
  20384. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  20385. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  20386. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  20387. act = _this._initActionManager(act, clickInfo);
  20388. if (act)
  20389. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  20390. }
  20391. if (checkDoubleClick) {
  20392. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  20393. if (btn === _this._previousButtonPressed &&
  20394. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  20395. !_this._doubleClickOccured) {
  20396. // pointer has not moved for 2 clicks, it's a double click
  20397. if (!clickInfo.hasSwiped &&
  20398. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  20399. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  20400. _this._previousStartingPointerTime = 0;
  20401. _this._doubleClickOccured = true;
  20402. clickInfo.doubleClick = true;
  20403. clickInfo.ignore = false;
  20404. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  20405. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20406. }
  20407. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20408. cb(clickInfo, _this._currentPickResult);
  20409. }
  20410. else {
  20411. _this._doubleClickOccured = false;
  20412. _this._previousStartingPointerTime = _this._startingPointerTime;
  20413. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20414. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20415. _this._previousButtonPressed = btn;
  20416. if (Scene.ExclusiveDoubleClickMode) {
  20417. if (_this._previousDelayedSimpleClickTimeout) {
  20418. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  20419. }
  20420. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  20421. cb(clickInfo, _this._previousPickResult);
  20422. }
  20423. else {
  20424. cb(clickInfo, _this._currentPickResult);
  20425. }
  20426. }
  20427. }
  20428. else {
  20429. _this._doubleClickOccured = false;
  20430. _this._previousStartingPointerTime = _this._startingPointerTime;
  20431. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  20432. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  20433. _this._previousButtonPressed = btn;
  20434. }
  20435. }
  20436. }
  20437. }
  20438. clickInfo.ignore = true;
  20439. cb(clickInfo, _this._currentPickResult);
  20440. };
  20441. this._spritePredicate = function (sprite) {
  20442. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  20443. };
  20444. this._onPointerMove = function (evt) {
  20445. _this._updatePointerPosition(evt);
  20446. // PreObservable support
  20447. if (_this.onPrePointerObservable.hasObservers()) {
  20448. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  20449. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20450. _this.onPrePointerObservable.notifyObservers(pi, type);
  20451. if (pi.skipOnPointerObservable) {
  20452. return;
  20453. }
  20454. }
  20455. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20456. return;
  20457. }
  20458. if (!_this.pointerMovePredicate) {
  20459. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  20460. }
  20461. // Meshes
  20462. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  20463. _this._processPointerMove(pickResult, evt);
  20464. };
  20465. this._onPointerDown = function (evt) {
  20466. _this._totalPointersPressed++;
  20467. _this._pickedDownMesh = null;
  20468. _this._meshPickProceed = false;
  20469. _this._updatePointerPosition(evt);
  20470. if (_this.preventDefaultOnPointerDown && canvas) {
  20471. evt.preventDefault();
  20472. canvas.focus();
  20473. }
  20474. // PreObservable support
  20475. if (_this.onPrePointerObservable.hasObservers()) {
  20476. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  20477. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20478. _this.onPrePointerObservable.notifyObservers(pi, type);
  20479. if (pi.skipOnPointerObservable) {
  20480. return;
  20481. }
  20482. }
  20483. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20484. return;
  20485. }
  20486. _this._startingPointerPosition.x = _this._pointerX;
  20487. _this._startingPointerPosition.y = _this._pointerY;
  20488. _this._startingPointerTime = new Date().getTime();
  20489. if (!_this.pointerDownPredicate) {
  20490. _this.pointerDownPredicate = function (mesh) {
  20491. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20492. };
  20493. }
  20494. // Meshes
  20495. _this._pickedDownMesh = null;
  20496. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  20497. _this._processPointerDown(pickResult, evt);
  20498. // Sprites
  20499. _this._pickedDownSprite = null;
  20500. if (_this.spriteManagers.length > 0) {
  20501. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20502. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  20503. if (pickResult.pickedSprite.actionManager) {
  20504. _this._pickedDownSprite = pickResult.pickedSprite;
  20505. switch (evt.button) {
  20506. case 0:
  20507. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20508. break;
  20509. case 1:
  20510. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20511. break;
  20512. case 2:
  20513. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20514. break;
  20515. }
  20516. if (pickResult.pickedSprite.actionManager) {
  20517. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  20518. }
  20519. }
  20520. }
  20521. }
  20522. };
  20523. this._onPointerUp = function (evt) {
  20524. if (_this._totalPointersPressed === 0) {
  20525. return; // So we need to test it the pointer down was pressed before.
  20526. }
  20527. _this._totalPointersPressed--;
  20528. _this._pickedUpMesh = null;
  20529. _this._meshPickProceed = false;
  20530. _this._updatePointerPosition(evt);
  20531. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  20532. // PreObservable support
  20533. if (_this.onPrePointerObservable.hasObservers()) {
  20534. if (!clickInfo.ignore) {
  20535. if (!clickInfo.hasSwiped) {
  20536. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  20537. var type = BABYLON.PointerEventTypes.POINTERTAP;
  20538. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20539. _this.onPrePointerObservable.notifyObservers(pi, type);
  20540. if (pi.skipOnPointerObservable) {
  20541. return;
  20542. }
  20543. }
  20544. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  20545. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  20546. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20547. _this.onPrePointerObservable.notifyObservers(pi, type);
  20548. if (pi.skipOnPointerObservable) {
  20549. return;
  20550. }
  20551. }
  20552. }
  20553. }
  20554. else {
  20555. var type = BABYLON.PointerEventTypes.POINTERUP;
  20556. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  20557. _this.onPrePointerObservable.notifyObservers(pi, type);
  20558. if (pi.skipOnPointerObservable) {
  20559. return;
  20560. }
  20561. }
  20562. }
  20563. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  20564. return;
  20565. }
  20566. if (!_this.pointerUpPredicate) {
  20567. _this.pointerUpPredicate = function (mesh) {
  20568. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  20569. };
  20570. }
  20571. // Meshes
  20572. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  20573. _this._initActionManager(null, clickInfo);
  20574. }
  20575. if (!pickResult) {
  20576. pickResult = _this._currentPickResult;
  20577. }
  20578. _this._processPointerUp(pickResult, evt, clickInfo);
  20579. // Sprites
  20580. if (_this.spriteManagers.length > 0) {
  20581. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  20582. if (spritePickResult) {
  20583. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  20584. if (spritePickResult.pickedSprite.actionManager) {
  20585. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20586. if (spritePickResult.pickedSprite.actionManager) {
  20587. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  20588. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  20589. }
  20590. }
  20591. }
  20592. }
  20593. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  20594. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  20595. }
  20596. }
  20597. }
  20598. _this._previousPickResult = _this._currentPickResult;
  20599. });
  20600. };
  20601. this._onKeyDown = function (evt) {
  20602. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  20603. if (_this.onPreKeyboardObservable.hasObservers()) {
  20604. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20605. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20606. if (pi.skipOnPointerObservable) {
  20607. return;
  20608. }
  20609. }
  20610. if (_this.onKeyboardObservable.hasObservers()) {
  20611. var pi = new BABYLON.KeyboardInfo(type, evt);
  20612. _this.onKeyboardObservable.notifyObservers(pi, type);
  20613. }
  20614. if (_this.actionManager) {
  20615. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20616. }
  20617. };
  20618. this._onKeyUp = function (evt) {
  20619. var type = BABYLON.KeyboardEventTypes.KEYUP;
  20620. if (_this.onPreKeyboardObservable.hasObservers()) {
  20621. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  20622. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  20623. if (pi.skipOnPointerObservable) {
  20624. return;
  20625. }
  20626. }
  20627. if (_this.onKeyboardObservable.hasObservers()) {
  20628. var pi = new BABYLON.KeyboardInfo(type, evt);
  20629. _this.onKeyboardObservable.notifyObservers(pi, type);
  20630. }
  20631. if (_this.actionManager) {
  20632. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  20633. }
  20634. };
  20635. var engine = this.getEngine();
  20636. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  20637. if (!canvas) {
  20638. return;
  20639. }
  20640. canvas.addEventListener("keydown", _this._onKeyDown, false);
  20641. canvas.addEventListener("keyup", _this._onKeyUp, false);
  20642. });
  20643. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  20644. if (!canvas) {
  20645. return;
  20646. }
  20647. canvas.removeEventListener("keydown", _this._onKeyDown);
  20648. canvas.removeEventListener("keyup", _this._onKeyUp);
  20649. });
  20650. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20651. var canvas = this._engine.getRenderingCanvas();
  20652. if (!canvas) {
  20653. return;
  20654. }
  20655. if (attachMove) {
  20656. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  20657. // Wheel
  20658. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  20659. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  20660. }
  20661. if (attachDown) {
  20662. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  20663. }
  20664. if (attachUp) {
  20665. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  20666. }
  20667. canvas.tabIndex = 1;
  20668. };
  20669. Scene.prototype.detachControl = function () {
  20670. var engine = this.getEngine();
  20671. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  20672. var canvas = engine.getRenderingCanvas();
  20673. if (!canvas) {
  20674. return;
  20675. }
  20676. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  20677. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  20678. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  20679. if (this._onCanvasBlurObserver) {
  20680. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  20681. }
  20682. if (this._onCanvasFocusObserver) {
  20683. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  20684. }
  20685. // Wheel
  20686. canvas.removeEventListener('mousewheel', this._onPointerMove);
  20687. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  20688. // Keyboard
  20689. canvas.removeEventListener("keydown", this._onKeyDown);
  20690. canvas.removeEventListener("keyup", this._onKeyUp);
  20691. // Observables
  20692. this.onKeyboardObservable.clear();
  20693. this.onPreKeyboardObservable.clear();
  20694. this.onPointerObservable.clear();
  20695. this.onPrePointerObservable.clear();
  20696. };
  20697. /**
  20698. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  20699. * Delay loaded resources are not taking in account
  20700. * @return true if all required resources are ready
  20701. */
  20702. Scene.prototype.isReady = function () {
  20703. if (this._isDisposed) {
  20704. return false;
  20705. }
  20706. if (this._pendingData.length > 0) {
  20707. return false;
  20708. }
  20709. var index;
  20710. var engine = this.getEngine();
  20711. // Geometries
  20712. for (index = 0; index < this._geometries.length; index++) {
  20713. var geometry = this._geometries[index];
  20714. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20715. return false;
  20716. }
  20717. }
  20718. // Meshes
  20719. for (index = 0; index < this.meshes.length; index++) {
  20720. var mesh = this.meshes[index];
  20721. if (!mesh.isEnabled()) {
  20722. continue;
  20723. }
  20724. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  20725. continue;
  20726. }
  20727. if (!mesh.isReady()) {
  20728. return false;
  20729. }
  20730. // Highlight layers
  20731. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  20732. for (var _i = 0, _a = this.highlightLayers; _i < _a.length; _i++) {
  20733. var layer = _a[_i];
  20734. if (!layer.hasMesh(mesh)) {
  20735. continue;
  20736. }
  20737. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  20738. var subMesh = _c[_b];
  20739. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  20740. return false;
  20741. }
  20742. }
  20743. }
  20744. }
  20745. return true;
  20746. };
  20747. Scene.prototype.resetCachedMaterial = function () {
  20748. this._cachedMaterial = null;
  20749. this._cachedEffect = null;
  20750. this._cachedVisibility = null;
  20751. };
  20752. Scene.prototype.registerBeforeRender = function (func) {
  20753. this.onBeforeRenderObservable.add(func);
  20754. };
  20755. Scene.prototype.unregisterBeforeRender = function (func) {
  20756. this.onBeforeRenderObservable.removeCallback(func);
  20757. };
  20758. Scene.prototype.registerAfterRender = function (func) {
  20759. this.onAfterRenderObservable.add(func);
  20760. };
  20761. Scene.prototype.unregisterAfterRender = function (func) {
  20762. this.onAfterRenderObservable.removeCallback(func);
  20763. };
  20764. Scene.prototype._executeOnceBeforeRender = function (func) {
  20765. var _this = this;
  20766. var execFunc = function () {
  20767. func();
  20768. setTimeout(function () {
  20769. _this.unregisterBeforeRender(execFunc);
  20770. });
  20771. };
  20772. this.registerBeforeRender(execFunc);
  20773. };
  20774. /**
  20775. * The provided function will run before render once and will be disposed afterwards.
  20776. * A timeout delay can be provided so that the function will be executed in N ms.
  20777. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  20778. * @param func The function to be executed.
  20779. * @param timeout optional delay in ms
  20780. */
  20781. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  20782. var _this = this;
  20783. if (timeout !== undefined) {
  20784. setTimeout(function () {
  20785. _this._executeOnceBeforeRender(func);
  20786. }, timeout);
  20787. }
  20788. else {
  20789. this._executeOnceBeforeRender(func);
  20790. }
  20791. };
  20792. Scene.prototype._addPendingData = function (data) {
  20793. this._pendingData.push(data);
  20794. };
  20795. Scene.prototype._removePendingData = function (data) {
  20796. var wasLoading = this.isLoading;
  20797. var index = this._pendingData.indexOf(data);
  20798. if (index !== -1) {
  20799. this._pendingData.splice(index, 1);
  20800. }
  20801. if (wasLoading && !this.isLoading) {
  20802. this.onDataLoadedObservable.notifyObservers(this);
  20803. }
  20804. };
  20805. Scene.prototype.getWaitingItemsCount = function () {
  20806. return this._pendingData.length;
  20807. };
  20808. Object.defineProperty(Scene.prototype, "isLoading", {
  20809. get: function () {
  20810. return this._pendingData.length > 0;
  20811. },
  20812. enumerable: true,
  20813. configurable: true
  20814. });
  20815. /**
  20816. * Registers a function to be executed when the scene is ready.
  20817. * @param {Function} func - the function to be executed.
  20818. */
  20819. Scene.prototype.executeWhenReady = function (func) {
  20820. var _this = this;
  20821. this.onReadyObservable.add(func);
  20822. if (this._executeWhenReadyTimeoutId !== -1) {
  20823. return;
  20824. }
  20825. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20826. _this._checkIsReady();
  20827. }, 150);
  20828. };
  20829. Scene.prototype._checkIsReady = function () {
  20830. var _this = this;
  20831. if (this.isReady()) {
  20832. this.onReadyObservable.notifyObservers(this);
  20833. this.onReadyObservable.clear();
  20834. this._executeWhenReadyTimeoutId = -1;
  20835. return;
  20836. }
  20837. this._executeWhenReadyTimeoutId = setTimeout(function () {
  20838. _this._checkIsReady();
  20839. }, 150);
  20840. };
  20841. // Animations
  20842. /**
  20843. * Will start the animation sequence of a given target
  20844. * @param target - the target
  20845. * @param {number} from - from which frame should animation start
  20846. * @param {number} to - till which frame should animation run.
  20847. * @param {boolean} [loop] - should the animation loop
  20848. * @param {number} [speedRatio] - the speed in which to run the animation
  20849. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  20850. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  20851. * Returns {BABYLON.Animatable} the animatable object created for this animation
  20852. * See BABYLON.Animatable
  20853. */
  20854. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  20855. if (speedRatio === void 0) { speedRatio = 1.0; }
  20856. if (from > to && speedRatio > 0) {
  20857. speedRatio *= -1;
  20858. }
  20859. this.stopAnimation(target);
  20860. if (!animatable) {
  20861. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  20862. }
  20863. // Local animations
  20864. if (target.animations) {
  20865. animatable.appendAnimations(target, target.animations);
  20866. }
  20867. // Children animations
  20868. if (target.getAnimatables) {
  20869. var animatables = target.getAnimatables();
  20870. for (var index = 0; index < animatables.length; index++) {
  20871. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  20872. }
  20873. }
  20874. animatable.reset();
  20875. return animatable;
  20876. };
  20877. /**
  20878. * Begin a new animation on a given node
  20879. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20880. * @param {BABYLON.Animation[]} defines the list of animations to start
  20881. * @param {number} from defines the initial value
  20882. * @param {number} to defines the final value
  20883. * @param {boolean} loop defines if you want animation to loop (off by default)
  20884. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20885. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20886. * @returns the list of created animatables
  20887. */
  20888. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20889. if (speedRatio === undefined) {
  20890. speedRatio = 1.0;
  20891. }
  20892. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  20893. return animatable;
  20894. };
  20895. /**
  20896. * Begin a new animation on a given node and its hierarchy
  20897. * @param {BABYLON.Node} node defines the root node where the animation will take place
  20898. * @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.
  20899. * @param {BABYLON.Animation[]} defines the list of animations to start
  20900. * @param {number} from defines the initial value
  20901. * @param {number} to defines the final value
  20902. * @param {boolean} loop defines if you want animation to loop (off by default)
  20903. * @param {number} speedRatio defines the speed ratio to apply to all animations
  20904. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  20905. * @returns the list of animatables created for all nodes
  20906. */
  20907. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  20908. var children = target.getDescendants(directDescendantsOnly);
  20909. var result = [];
  20910. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  20911. var child = children_1[_i];
  20912. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  20913. }
  20914. return result;
  20915. };
  20916. Scene.prototype.getAnimatableByTarget = function (target) {
  20917. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20918. if (this._activeAnimatables[index].target === target) {
  20919. return this._activeAnimatables[index];
  20920. }
  20921. }
  20922. return null;
  20923. };
  20924. Object.defineProperty(Scene.prototype, "animatables", {
  20925. get: function () {
  20926. return this._activeAnimatables;
  20927. },
  20928. enumerable: true,
  20929. configurable: true
  20930. });
  20931. /**
  20932. * Will stop the animation of the given target
  20933. * @param target - the target
  20934. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  20935. * @see beginAnimation
  20936. */
  20937. Scene.prototype.stopAnimation = function (target, animationName) {
  20938. var animatable = this.getAnimatableByTarget(target);
  20939. if (animatable) {
  20940. animatable.stop(animationName);
  20941. }
  20942. };
  20943. /**
  20944. * Stops and removes all animations that have been applied to the scene
  20945. */
  20946. Scene.prototype.stopAllAnimations = function () {
  20947. if (this._activeAnimatables) {
  20948. for (var i = 0; i < this._activeAnimatables.length; i++) {
  20949. this._activeAnimatables[i].stop();
  20950. }
  20951. this._activeAnimatables = [];
  20952. }
  20953. };
  20954. Scene.prototype._animate = function () {
  20955. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  20956. return;
  20957. }
  20958. // Getting time
  20959. var now = BABYLON.Tools.Now;
  20960. if (!this._animationTimeLast) {
  20961. if (this._pendingData.length > 0) {
  20962. return;
  20963. }
  20964. this._animationTimeLast = now;
  20965. }
  20966. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  20967. this._animationTime += deltaTime;
  20968. this._animationTimeLast = now;
  20969. for (var index = 0; index < this._activeAnimatables.length; index++) {
  20970. this._activeAnimatables[index]._animate(this._animationTime);
  20971. }
  20972. };
  20973. // Matrix
  20974. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20975. this._useAlternateCameraConfiguration = active;
  20976. };
  20977. Scene.prototype.getViewMatrix = function () {
  20978. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20979. };
  20980. Scene.prototype.getProjectionMatrix = function () {
  20981. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20982. };
  20983. Scene.prototype.getTransformMatrix = function () {
  20984. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20985. };
  20986. Scene.prototype.setTransformMatrix = function (view, projection) {
  20987. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20988. return;
  20989. }
  20990. this._viewUpdateFlag = view.updateFlag;
  20991. this._projectionUpdateFlag = projection.updateFlag;
  20992. this._viewMatrix = view;
  20993. this._projectionMatrix = projection;
  20994. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20995. // Update frustum
  20996. if (!this._frustumPlanes) {
  20997. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20998. }
  20999. else {
  21000. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  21001. }
  21002. if (this.activeCamera && this.activeCamera._alternateCamera) {
  21003. var otherCamera = this.activeCamera._alternateCamera;
  21004. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  21005. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  21006. }
  21007. if (this._sceneUbo.useUbo) {
  21008. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  21009. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  21010. this._sceneUbo.update();
  21011. }
  21012. };
  21013. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  21014. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  21015. return;
  21016. }
  21017. this._alternateViewUpdateFlag = view.updateFlag;
  21018. this._alternateProjectionUpdateFlag = projection.updateFlag;
  21019. this._alternateViewMatrix = view;
  21020. this._alternateProjectionMatrix = projection;
  21021. if (!this._alternateTransformMatrix) {
  21022. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  21023. }
  21024. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  21025. if (!this._alternateSceneUbo) {
  21026. this._createAlternateUbo();
  21027. }
  21028. if (this._alternateSceneUbo.useUbo) {
  21029. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  21030. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  21031. this._alternateSceneUbo.update();
  21032. }
  21033. };
  21034. Scene.prototype.getSceneUniformBuffer = function () {
  21035. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  21036. };
  21037. // Methods
  21038. Scene.prototype.getUniqueId = function () {
  21039. var result = Scene._uniqueIdCounter;
  21040. Scene._uniqueIdCounter++;
  21041. return result;
  21042. };
  21043. Scene.prototype.addMesh = function (newMesh) {
  21044. this.meshes.push(newMesh);
  21045. //notify the collision coordinator
  21046. if (this.collisionCoordinator) {
  21047. this.collisionCoordinator.onMeshAdded(newMesh);
  21048. }
  21049. newMesh._resyncLightSources();
  21050. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  21051. };
  21052. Scene.prototype.removeMesh = function (toRemove) {
  21053. var index = this.meshes.indexOf(toRemove);
  21054. if (index !== -1) {
  21055. // Remove from the scene if mesh found
  21056. this.meshes.splice(index, 1);
  21057. }
  21058. this.onMeshRemovedObservable.notifyObservers(toRemove);
  21059. return index;
  21060. };
  21061. Scene.prototype.addTransformNode = function (newTransformNode) {
  21062. this.transformNodes.push(newTransformNode);
  21063. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  21064. };
  21065. Scene.prototype.removeTransformNode = function (toRemove) {
  21066. var index = this.transformNodes.indexOf(toRemove);
  21067. if (index !== -1) {
  21068. // Remove from the scene if found
  21069. this.transformNodes.splice(index, 1);
  21070. }
  21071. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  21072. return index;
  21073. };
  21074. Scene.prototype.removeSkeleton = function (toRemove) {
  21075. var index = this.skeletons.indexOf(toRemove);
  21076. if (index !== -1) {
  21077. // Remove from the scene if found
  21078. this.skeletons.splice(index, 1);
  21079. }
  21080. return index;
  21081. };
  21082. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  21083. var index = this.morphTargetManagers.indexOf(toRemove);
  21084. if (index !== -1) {
  21085. // Remove from the scene if found
  21086. this.morphTargetManagers.splice(index, 1);
  21087. }
  21088. return index;
  21089. };
  21090. Scene.prototype.removeLight = function (toRemove) {
  21091. var index = this.lights.indexOf(toRemove);
  21092. if (index !== -1) {
  21093. // Remove from meshes
  21094. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21095. var mesh = _a[_i];
  21096. mesh._removeLightSource(toRemove);
  21097. }
  21098. // Remove from the scene if mesh found
  21099. this.lights.splice(index, 1);
  21100. this.sortLightsByPriority();
  21101. }
  21102. this.onLightRemovedObservable.notifyObservers(toRemove);
  21103. return index;
  21104. };
  21105. Scene.prototype.removeCamera = function (toRemove) {
  21106. var index = this.cameras.indexOf(toRemove);
  21107. if (index !== -1) {
  21108. // Remove from the scene if mesh found
  21109. this.cameras.splice(index, 1);
  21110. }
  21111. // Remove from activeCameras
  21112. var index2 = this.activeCameras.indexOf(toRemove);
  21113. if (index2 !== -1) {
  21114. // Remove from the scene if mesh found
  21115. this.activeCameras.splice(index2, 1);
  21116. }
  21117. // Reset the activeCamera
  21118. if (this.activeCamera === toRemove) {
  21119. if (this.cameras.length > 0) {
  21120. this.activeCamera = this.cameras[0];
  21121. }
  21122. else {
  21123. this.activeCamera = null;
  21124. }
  21125. }
  21126. this.onCameraRemovedObservable.notifyObservers(toRemove);
  21127. return index;
  21128. };
  21129. Scene.prototype.removeParticleSystem = function (toRemove) {
  21130. var index = this.particleSystems.indexOf(toRemove);
  21131. if (index !== -1) {
  21132. this.particleSystems.splice(index, 1);
  21133. }
  21134. return index;
  21135. };
  21136. ;
  21137. Scene.prototype.removeAnimation = function (toRemove) {
  21138. var index = this.animations.indexOf(toRemove);
  21139. if (index !== -1) {
  21140. this.animations.splice(index, 1);
  21141. }
  21142. return index;
  21143. };
  21144. ;
  21145. Scene.prototype.removeMultiMaterial = function (toRemove) {
  21146. var index = this.multiMaterials.indexOf(toRemove);
  21147. if (index !== -1) {
  21148. this.multiMaterials.splice(index, 1);
  21149. }
  21150. return index;
  21151. };
  21152. ;
  21153. Scene.prototype.removeMaterial = function (toRemove) {
  21154. var index = this.materials.indexOf(toRemove);
  21155. if (index !== -1) {
  21156. this.materials.splice(index, 1);
  21157. }
  21158. return index;
  21159. };
  21160. ;
  21161. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  21162. var index = this.lensFlareSystems.indexOf(toRemove);
  21163. if (index !== -1) {
  21164. this.lensFlareSystems.splice(index, 1);
  21165. }
  21166. return index;
  21167. };
  21168. ;
  21169. Scene.prototype.removeActionManager = function (toRemove) {
  21170. var index = this._actionManagers.indexOf(toRemove);
  21171. if (index !== -1) {
  21172. this._actionManagers.splice(index, 1);
  21173. }
  21174. return index;
  21175. };
  21176. ;
  21177. Scene.prototype.addLight = function (newLight) {
  21178. this.lights.push(newLight);
  21179. this.sortLightsByPriority();
  21180. // Add light to all meshes (To support if the light is removed and then readded)
  21181. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  21182. var mesh = _a[_i];
  21183. if (mesh._lightSources.indexOf(newLight) === -1) {
  21184. mesh._lightSources.push(newLight);
  21185. mesh._resyncLightSources();
  21186. }
  21187. }
  21188. this.onNewLightAddedObservable.notifyObservers(newLight);
  21189. };
  21190. Scene.prototype.sortLightsByPriority = function () {
  21191. if (this.requireLightSorting) {
  21192. this.lights.sort(BABYLON.Light.compareLightsPriority);
  21193. }
  21194. };
  21195. Scene.prototype.addCamera = function (newCamera) {
  21196. this.cameras.push(newCamera);
  21197. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  21198. };
  21199. Scene.prototype.addSkeleton = function (newSkeleton) {
  21200. this.skeletons.push(newSkeleton);
  21201. };
  21202. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  21203. this.particleSystems.push(newParticleSystem);
  21204. };
  21205. Scene.prototype.addAnimation = function (newAnimation) {
  21206. this.animations.push(newAnimation);
  21207. };
  21208. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  21209. this.multiMaterials.push(newMultiMaterial);
  21210. };
  21211. Scene.prototype.addMaterial = function (newMaterial) {
  21212. this.materials.push(newMaterial);
  21213. };
  21214. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  21215. this.morphTargetManagers.push(newMorphTargetManager);
  21216. };
  21217. Scene.prototype.addGeometry = function (newGeometrie) {
  21218. this._geometries.push(newGeometrie);
  21219. };
  21220. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  21221. this.lensFlareSystems.push(newLensFlareSystem);
  21222. };
  21223. Scene.prototype.addActionManager = function (newActionManager) {
  21224. this._actionManagers.push(newActionManager);
  21225. };
  21226. /**
  21227. * Switch active camera
  21228. * @param {Camera} newCamera - new active camera
  21229. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  21230. */
  21231. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  21232. if (attachControl === void 0) { attachControl = true; }
  21233. var canvas = this._engine.getRenderingCanvas();
  21234. if (!canvas) {
  21235. return;
  21236. }
  21237. if (this.activeCamera) {
  21238. this.activeCamera.detachControl(canvas);
  21239. }
  21240. this.activeCamera = newCamera;
  21241. if (attachControl) {
  21242. newCamera.attachControl(canvas);
  21243. }
  21244. };
  21245. /**
  21246. * sets the active camera of the scene using its ID
  21247. * @param {string} id - the camera's ID
  21248. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21249. * @see activeCamera
  21250. */
  21251. Scene.prototype.setActiveCameraByID = function (id) {
  21252. var camera = this.getCameraByID(id);
  21253. if (camera) {
  21254. this.activeCamera = camera;
  21255. return camera;
  21256. }
  21257. return null;
  21258. };
  21259. /**
  21260. * sets the active camera of the scene using its name
  21261. * @param {string} name - the camera's name
  21262. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  21263. * @see activeCamera
  21264. */
  21265. Scene.prototype.setActiveCameraByName = function (name) {
  21266. var camera = this.getCameraByName(name);
  21267. if (camera) {
  21268. this.activeCamera = camera;
  21269. return camera;
  21270. }
  21271. return null;
  21272. };
  21273. /**
  21274. * get an animation group using its name
  21275. * @param {string} the material's name
  21276. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  21277. */
  21278. Scene.prototype.getAnimationGroupByName = function (name) {
  21279. for (var index = 0; index < this.animationGroups.length; index++) {
  21280. if (this.animationGroups[index].name === name) {
  21281. return this.animationGroups[index];
  21282. }
  21283. }
  21284. return null;
  21285. };
  21286. /**
  21287. * get a material using its id
  21288. * @param {string} the material's ID
  21289. * @return {BABYLON.Material|null} the material or null if none found.
  21290. */
  21291. Scene.prototype.getMaterialByID = function (id) {
  21292. for (var index = 0; index < this.materials.length; index++) {
  21293. if (this.materials[index].id === id) {
  21294. return this.materials[index];
  21295. }
  21296. }
  21297. return null;
  21298. };
  21299. /**
  21300. * get a material using its name
  21301. * @param {string} the material's name
  21302. * @return {BABYLON.Material|null} the material or null if none found.
  21303. */
  21304. Scene.prototype.getMaterialByName = function (name) {
  21305. for (var index = 0; index < this.materials.length; index++) {
  21306. if (this.materials[index].name === name) {
  21307. return this.materials[index];
  21308. }
  21309. }
  21310. return null;
  21311. };
  21312. Scene.prototype.getLensFlareSystemByName = function (name) {
  21313. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21314. if (this.lensFlareSystems[index].name === name) {
  21315. return this.lensFlareSystems[index];
  21316. }
  21317. }
  21318. return null;
  21319. };
  21320. Scene.prototype.getLensFlareSystemByID = function (id) {
  21321. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  21322. if (this.lensFlareSystems[index].id === id) {
  21323. return this.lensFlareSystems[index];
  21324. }
  21325. }
  21326. return null;
  21327. };
  21328. Scene.prototype.getCameraByID = function (id) {
  21329. for (var index = 0; index < this.cameras.length; index++) {
  21330. if (this.cameras[index].id === id) {
  21331. return this.cameras[index];
  21332. }
  21333. }
  21334. return null;
  21335. };
  21336. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  21337. for (var index = 0; index < this.cameras.length; index++) {
  21338. if (this.cameras[index].uniqueId === uniqueId) {
  21339. return this.cameras[index];
  21340. }
  21341. }
  21342. return null;
  21343. };
  21344. /**
  21345. * get a camera using its name
  21346. * @param {string} the camera's name
  21347. * @return {BABYLON.Camera|null} the camera or null if none found.
  21348. */
  21349. Scene.prototype.getCameraByName = function (name) {
  21350. for (var index = 0; index < this.cameras.length; index++) {
  21351. if (this.cameras[index].name === name) {
  21352. return this.cameras[index];
  21353. }
  21354. }
  21355. return null;
  21356. };
  21357. /**
  21358. * get a bone using its id
  21359. * @param {string} the bone's id
  21360. * @return {BABYLON.Bone|null} the bone or null if not found
  21361. */
  21362. Scene.prototype.getBoneByID = function (id) {
  21363. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21364. var skeleton = this.skeletons[skeletonIndex];
  21365. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21366. if (skeleton.bones[boneIndex].id === id) {
  21367. return skeleton.bones[boneIndex];
  21368. }
  21369. }
  21370. }
  21371. return null;
  21372. };
  21373. /**
  21374. * get a bone using its id
  21375. * @param {string} the bone's name
  21376. * @return {BABYLON.Bone|null} the bone or null if not found
  21377. */
  21378. Scene.prototype.getBoneByName = function (name) {
  21379. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  21380. var skeleton = this.skeletons[skeletonIndex];
  21381. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  21382. if (skeleton.bones[boneIndex].name === name) {
  21383. return skeleton.bones[boneIndex];
  21384. }
  21385. }
  21386. }
  21387. return null;
  21388. };
  21389. /**
  21390. * get a light node using its name
  21391. * @param {string} the light's name
  21392. * @return {BABYLON.Light|null} the light or null if none found.
  21393. */
  21394. Scene.prototype.getLightByName = function (name) {
  21395. for (var index = 0; index < this.lights.length; index++) {
  21396. if (this.lights[index].name === name) {
  21397. return this.lights[index];
  21398. }
  21399. }
  21400. return null;
  21401. };
  21402. /**
  21403. * get a light node using its ID
  21404. * @param {string} the light's id
  21405. * @return {BABYLON.Light|null} the light or null if none found.
  21406. */
  21407. Scene.prototype.getLightByID = function (id) {
  21408. for (var index = 0; index < this.lights.length; index++) {
  21409. if (this.lights[index].id === id) {
  21410. return this.lights[index];
  21411. }
  21412. }
  21413. return null;
  21414. };
  21415. /**
  21416. * get a light node using its scene-generated unique ID
  21417. * @param {number} the light's unique id
  21418. * @return {BABYLON.Light|null} the light or null if none found.
  21419. */
  21420. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  21421. for (var index = 0; index < this.lights.length; index++) {
  21422. if (this.lights[index].uniqueId === uniqueId) {
  21423. return this.lights[index];
  21424. }
  21425. }
  21426. return null;
  21427. };
  21428. /**
  21429. * get a particle system by id
  21430. * @param id {number} the particle system id
  21431. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  21432. */
  21433. Scene.prototype.getParticleSystemByID = function (id) {
  21434. for (var index = 0; index < this.particleSystems.length; index++) {
  21435. if (this.particleSystems[index].id === id) {
  21436. return this.particleSystems[index];
  21437. }
  21438. }
  21439. return null;
  21440. };
  21441. /**
  21442. * get a geometry using its ID
  21443. * @param {string} the geometry's id
  21444. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  21445. */
  21446. Scene.prototype.getGeometryByID = function (id) {
  21447. for (var index = 0; index < this._geometries.length; index++) {
  21448. if (this._geometries[index].id === id) {
  21449. return this._geometries[index];
  21450. }
  21451. }
  21452. return null;
  21453. };
  21454. /**
  21455. * add a new geometry to this scene.
  21456. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  21457. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  21458. * @return {boolean} was the geometry added or not
  21459. */
  21460. Scene.prototype.pushGeometry = function (geometry, force) {
  21461. if (!force && this.getGeometryByID(geometry.id)) {
  21462. return false;
  21463. }
  21464. this._geometries.push(geometry);
  21465. //notify the collision coordinator
  21466. if (this.collisionCoordinator) {
  21467. this.collisionCoordinator.onGeometryAdded(geometry);
  21468. }
  21469. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  21470. return true;
  21471. };
  21472. /**
  21473. * Removes an existing geometry
  21474. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  21475. * @return {boolean} was the geometry removed or not
  21476. */
  21477. Scene.prototype.removeGeometry = function (geometry) {
  21478. var index = this._geometries.indexOf(geometry);
  21479. if (index > -1) {
  21480. this._geometries.splice(index, 1);
  21481. //notify the collision coordinator
  21482. if (this.collisionCoordinator) {
  21483. this.collisionCoordinator.onGeometryDeleted(geometry);
  21484. }
  21485. this.onGeometryRemovedObservable.notifyObservers(geometry);
  21486. return true;
  21487. }
  21488. return false;
  21489. };
  21490. Scene.prototype.getGeometries = function () {
  21491. return this._geometries;
  21492. };
  21493. /**
  21494. * Get the first added mesh found of a given ID
  21495. * @param {string} id - the id to search for
  21496. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21497. */
  21498. Scene.prototype.getMeshByID = function (id) {
  21499. for (var index = 0; index < this.meshes.length; index++) {
  21500. if (this.meshes[index].id === id) {
  21501. return this.meshes[index];
  21502. }
  21503. }
  21504. return null;
  21505. };
  21506. Scene.prototype.getMeshesByID = function (id) {
  21507. return this.meshes.filter(function (m) {
  21508. return m.id === id;
  21509. });
  21510. };
  21511. /**
  21512. * Get the first added transform node found of a given ID
  21513. * @param {string} id - the id to search for
  21514. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  21515. */
  21516. Scene.prototype.getTransformNodeByID = function (id) {
  21517. for (var index = 0; index < this.transformNodes.length; index++) {
  21518. if (this.transformNodes[index].id === id) {
  21519. return this.transformNodes[index];
  21520. }
  21521. }
  21522. return null;
  21523. };
  21524. Scene.prototype.getTransformNodesByID = function (id) {
  21525. return this.transformNodes.filter(function (m) {
  21526. return m.id === id;
  21527. });
  21528. };
  21529. /**
  21530. * Get a mesh with its auto-generated unique id
  21531. * @param {number} uniqueId - the unique id to search for
  21532. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21533. */
  21534. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  21535. for (var index = 0; index < this.meshes.length; index++) {
  21536. if (this.meshes[index].uniqueId === uniqueId) {
  21537. return this.meshes[index];
  21538. }
  21539. }
  21540. return null;
  21541. };
  21542. /**
  21543. * Get a the last added mesh found of a given ID
  21544. * @param {string} id - the id to search for
  21545. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  21546. */
  21547. Scene.prototype.getLastMeshByID = function (id) {
  21548. for (var index = this.meshes.length - 1; index >= 0; index--) {
  21549. if (this.meshes[index].id === id) {
  21550. return this.meshes[index];
  21551. }
  21552. }
  21553. return null;
  21554. };
  21555. /**
  21556. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  21557. * @param {string} id - the id to search for
  21558. * @return {BABYLON.Node|null} the node found or null if not found at all.
  21559. */
  21560. Scene.prototype.getLastEntryByID = function (id) {
  21561. var index;
  21562. for (index = this.meshes.length - 1; index >= 0; index--) {
  21563. if (this.meshes[index].id === id) {
  21564. return this.meshes[index];
  21565. }
  21566. }
  21567. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  21568. if (this.transformNodes[index].id === id) {
  21569. return this.transformNodes[index];
  21570. }
  21571. }
  21572. for (index = this.cameras.length - 1; index >= 0; index--) {
  21573. if (this.cameras[index].id === id) {
  21574. return this.cameras[index];
  21575. }
  21576. }
  21577. for (index = this.lights.length - 1; index >= 0; index--) {
  21578. if (this.lights[index].id === id) {
  21579. return this.lights[index];
  21580. }
  21581. }
  21582. return null;
  21583. };
  21584. Scene.prototype.getNodeByID = function (id) {
  21585. var mesh = this.getMeshByID(id);
  21586. if (mesh) {
  21587. return mesh;
  21588. }
  21589. var light = this.getLightByID(id);
  21590. if (light) {
  21591. return light;
  21592. }
  21593. var camera = this.getCameraByID(id);
  21594. if (camera) {
  21595. return camera;
  21596. }
  21597. var bone = this.getBoneByID(id);
  21598. return bone;
  21599. };
  21600. Scene.prototype.getNodeByName = function (name) {
  21601. var mesh = this.getMeshByName(name);
  21602. if (mesh) {
  21603. return mesh;
  21604. }
  21605. var light = this.getLightByName(name);
  21606. if (light) {
  21607. return light;
  21608. }
  21609. var camera = this.getCameraByName(name);
  21610. if (camera) {
  21611. return camera;
  21612. }
  21613. var bone = this.getBoneByName(name);
  21614. return bone;
  21615. };
  21616. Scene.prototype.getMeshByName = function (name) {
  21617. for (var index = 0; index < this.meshes.length; index++) {
  21618. if (this.meshes[index].name === name) {
  21619. return this.meshes[index];
  21620. }
  21621. }
  21622. return null;
  21623. };
  21624. Scene.prototype.getTransformNodeByName = function (name) {
  21625. for (var index = 0; index < this.transformNodes.length; index++) {
  21626. if (this.transformNodes[index].name === name) {
  21627. return this.transformNodes[index];
  21628. }
  21629. }
  21630. return null;
  21631. };
  21632. Scene.prototype.getSoundByName = function (name) {
  21633. var index;
  21634. if (BABYLON.AudioEngine) {
  21635. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  21636. if (this.mainSoundTrack.soundCollection[index].name === name) {
  21637. return this.mainSoundTrack.soundCollection[index];
  21638. }
  21639. }
  21640. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  21641. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  21642. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  21643. return this.soundTracks[sdIndex].soundCollection[index];
  21644. }
  21645. }
  21646. }
  21647. }
  21648. return null;
  21649. };
  21650. Scene.prototype.getLastSkeletonByID = function (id) {
  21651. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  21652. if (this.skeletons[index].id === id) {
  21653. return this.skeletons[index];
  21654. }
  21655. }
  21656. return null;
  21657. };
  21658. Scene.prototype.getSkeletonById = function (id) {
  21659. for (var index = 0; index < this.skeletons.length; index++) {
  21660. if (this.skeletons[index].id === id) {
  21661. return this.skeletons[index];
  21662. }
  21663. }
  21664. return null;
  21665. };
  21666. Scene.prototype.getSkeletonByName = function (name) {
  21667. for (var index = 0; index < this.skeletons.length; index++) {
  21668. if (this.skeletons[index].name === name) {
  21669. return this.skeletons[index];
  21670. }
  21671. }
  21672. return null;
  21673. };
  21674. Scene.prototype.getMorphTargetManagerById = function (id) {
  21675. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  21676. if (this.morphTargetManagers[index].uniqueId === id) {
  21677. return this.morphTargetManagers[index];
  21678. }
  21679. }
  21680. return null;
  21681. };
  21682. Scene.prototype.isActiveMesh = function (mesh) {
  21683. return (this._activeMeshes.indexOf(mesh) !== -1);
  21684. };
  21685. /**
  21686. * Return a the first highlight layer of the scene with a given name.
  21687. * @param name The name of the highlight layer to look for.
  21688. * @return The highlight layer if found otherwise null.
  21689. */
  21690. Scene.prototype.getHighlightLayerByName = function (name) {
  21691. for (var index = 0; index < this.highlightLayers.length; index++) {
  21692. if (this.highlightLayers[index].name === name) {
  21693. return this.highlightLayers[index];
  21694. }
  21695. }
  21696. return null;
  21697. };
  21698. Object.defineProperty(Scene.prototype, "uid", {
  21699. /**
  21700. * Return a unique id as a string which can serve as an identifier for the scene
  21701. */
  21702. get: function () {
  21703. if (!this._uid) {
  21704. this._uid = BABYLON.Tools.RandomId();
  21705. }
  21706. return this._uid;
  21707. },
  21708. enumerable: true,
  21709. configurable: true
  21710. });
  21711. /**
  21712. * Add an externaly attached data from its key.
  21713. * This method call will fail and return false, if such key already exists.
  21714. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  21715. * @param key the unique key that identifies the data
  21716. * @param data the data object to associate to the key for this Engine instance
  21717. * @return true if no such key were already present and the data was added successfully, false otherwise
  21718. */
  21719. Scene.prototype.addExternalData = function (key, data) {
  21720. if (!this._externalData) {
  21721. this._externalData = new BABYLON.StringDictionary();
  21722. }
  21723. return this._externalData.add(key, data);
  21724. };
  21725. /**
  21726. * Get an externaly attached data from its key
  21727. * @param key the unique key that identifies the data
  21728. * @return the associated data, if present (can be null), or undefined if not present
  21729. */
  21730. Scene.prototype.getExternalData = function (key) {
  21731. if (!this._externalData) {
  21732. return null;
  21733. }
  21734. return this._externalData.get(key);
  21735. };
  21736. /**
  21737. * Get an externaly attached data from its key, create it using a factory if it's not already present
  21738. * @param key the unique key that identifies the data
  21739. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  21740. * @return the associated data, can be null if the factory returned null.
  21741. */
  21742. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  21743. if (!this._externalData) {
  21744. this._externalData = new BABYLON.StringDictionary();
  21745. }
  21746. return this._externalData.getOrAddWithFactory(key, factory);
  21747. };
  21748. /**
  21749. * Remove an externaly attached data from the Engine instance
  21750. * @param key the unique key that identifies the data
  21751. * @return true if the data was successfully removed, false if it doesn't exist
  21752. */
  21753. Scene.prototype.removeExternalData = function (key) {
  21754. return this._externalData.remove(key);
  21755. };
  21756. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  21757. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  21758. if (mesh.showSubMeshesBoundingBox) {
  21759. var boundingInfo = subMesh.getBoundingInfo();
  21760. if (boundingInfo !== null && boundingInfo !== undefined) {
  21761. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21762. }
  21763. }
  21764. var material = subMesh.getMaterial();
  21765. if (material !== null && material !== undefined) {
  21766. // Render targets
  21767. if (material.getRenderTargetTextures !== undefined) {
  21768. if (this._processedMaterials.indexOf(material) === -1) {
  21769. this._processedMaterials.push(material);
  21770. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  21771. }
  21772. }
  21773. // Dispatch
  21774. this._activeIndices.addCount(subMesh.indexCount, false);
  21775. this._renderingManager.dispatch(subMesh, mesh, material);
  21776. }
  21777. }
  21778. };
  21779. Scene.prototype._isInIntermediateRendering = function () {
  21780. return this._intermediateRendering;
  21781. };
  21782. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  21783. this._activeMeshCandidateProvider = provider;
  21784. };
  21785. Scene.prototype.getActiveMeshCandidateProvider = function () {
  21786. return this._activeMeshCandidateProvider;
  21787. };
  21788. /**
  21789. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  21790. */
  21791. Scene.prototype.freezeActiveMeshes = function () {
  21792. this._evaluateActiveMeshes();
  21793. this._activeMeshesFrozen = true;
  21794. return this;
  21795. };
  21796. /**
  21797. * Use this function to restart evaluating active meshes on every frame
  21798. */
  21799. Scene.prototype.unfreezeActiveMeshes = function () {
  21800. this._activeMeshesFrozen = false;
  21801. return this;
  21802. };
  21803. Scene.prototype._evaluateActiveMeshes = function () {
  21804. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  21805. return;
  21806. }
  21807. if (!this.activeCamera) {
  21808. return;
  21809. }
  21810. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  21811. this.activeCamera._activeMeshes.reset();
  21812. this._activeMeshes.reset();
  21813. this._renderingManager.reset();
  21814. this._processedMaterials.reset();
  21815. this._activeParticleSystems.reset();
  21816. this._activeSkeletons.reset();
  21817. this._softwareSkinnedMeshes.reset();
  21818. if (this._boundingBoxRenderer) {
  21819. this._boundingBoxRenderer.reset();
  21820. }
  21821. // Meshes
  21822. var meshes;
  21823. var len;
  21824. var checkIsEnabled = true;
  21825. // Determine mesh candidates
  21826. if (this._activeMeshCandidateProvider !== undefined) {
  21827. // Use _activeMeshCandidateProvider
  21828. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  21829. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  21830. if (meshes !== undefined) {
  21831. len = meshes.length;
  21832. }
  21833. else {
  21834. len = 0;
  21835. }
  21836. }
  21837. else if (this._selectionOctree !== undefined) {
  21838. // Octree
  21839. var selection = this._selectionOctree.select(this._frustumPlanes);
  21840. meshes = selection.data;
  21841. len = selection.length;
  21842. }
  21843. else {
  21844. // Full scene traversal
  21845. len = this.meshes.length;
  21846. meshes = this.meshes;
  21847. }
  21848. // Check each mesh
  21849. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  21850. mesh = meshes[meshIndex];
  21851. if (mesh.isBlocked) {
  21852. continue;
  21853. }
  21854. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  21855. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  21856. continue;
  21857. }
  21858. mesh.computeWorldMatrix();
  21859. // Intersections
  21860. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  21861. this._meshesForIntersections.pushNoDuplicate(mesh);
  21862. }
  21863. // Switch to current LOD
  21864. meshLOD = mesh.getLOD(this.activeCamera);
  21865. if (meshLOD === undefined || meshLOD === null) {
  21866. continue;
  21867. }
  21868. mesh._preActivate();
  21869. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  21870. this._activeMeshes.push(mesh);
  21871. this.activeCamera._activeMeshes.push(mesh);
  21872. mesh._activate(this._renderId);
  21873. if (meshLOD !== mesh) {
  21874. meshLOD._activate(this._renderId);
  21875. }
  21876. this._activeMesh(mesh, meshLOD);
  21877. }
  21878. }
  21879. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  21880. // Particle systems
  21881. if (this.particlesEnabled) {
  21882. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  21883. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  21884. var particleSystem = this.particleSystems[particleIndex];
  21885. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  21886. continue;
  21887. }
  21888. var emitter = particleSystem.emitter;
  21889. if (!emitter.position || emitter.isEnabled()) {
  21890. this._activeParticleSystems.push(particleSystem);
  21891. particleSystem.animate();
  21892. this._renderingManager.dispatchParticles(particleSystem);
  21893. }
  21894. }
  21895. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  21896. }
  21897. };
  21898. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  21899. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  21900. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  21901. mesh.skeleton.prepare();
  21902. }
  21903. if (!mesh.computeBonesUsingShaders) {
  21904. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  21905. }
  21906. }
  21907. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  21908. var boundingInfo = sourceMesh.getBoundingInfo();
  21909. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  21910. }
  21911. if (mesh !== undefined && mesh !== null
  21912. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  21913. // Submeshes Octrees
  21914. var len;
  21915. var subMeshes;
  21916. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  21917. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  21918. len = intersections.length;
  21919. subMeshes = intersections.data;
  21920. }
  21921. else {
  21922. subMeshes = mesh.subMeshes;
  21923. len = subMeshes.length;
  21924. }
  21925. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  21926. subMesh = subMeshes[subIndex];
  21927. this._evaluateSubMesh(subMesh, mesh);
  21928. }
  21929. }
  21930. };
  21931. Scene.prototype.updateTransformMatrix = function (force) {
  21932. if (!this.activeCamera) {
  21933. return;
  21934. }
  21935. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  21936. };
  21937. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  21938. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  21939. };
  21940. Scene.prototype._renderForCamera = function (camera) {
  21941. if (camera && camera._skipRendering) {
  21942. return;
  21943. }
  21944. var engine = this._engine;
  21945. this.activeCamera = camera;
  21946. if (!this.activeCamera)
  21947. throw new Error("Active camera not set");
  21948. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21949. // Viewport
  21950. engine.setViewport(this.activeCamera.viewport);
  21951. // Camera
  21952. this.resetCachedMaterial();
  21953. this._renderId++;
  21954. this.activeCamera.update();
  21955. this.updateTransformMatrix();
  21956. if (camera._alternateCamera) {
  21957. this.updateAlternateTransformMatrix(camera._alternateCamera);
  21958. this._alternateRendering = true;
  21959. }
  21960. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  21961. // Meshes
  21962. this._evaluateActiveMeshes();
  21963. // Software skinning
  21964. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  21965. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  21966. mesh.applySkeleton(mesh.skeleton);
  21967. }
  21968. // Render targets
  21969. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21970. var needsRestoreFrameBuffer = false;
  21971. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  21972. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  21973. }
  21974. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  21975. this._intermediateRendering = true;
  21976. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21977. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  21978. var renderTarget = this._renderTargets.data[renderIndex];
  21979. if (renderTarget._shouldRender()) {
  21980. this._renderId++;
  21981. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  21982. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  21983. }
  21984. }
  21985. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  21986. this._intermediateRendering = false;
  21987. this._renderId++;
  21988. needsRestoreFrameBuffer = true; // Restore back buffer
  21989. }
  21990. // Render HighlightLayer Texture
  21991. var stencilState = this._engine.getStencilBuffer();
  21992. var renderhighlights = false;
  21993. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  21994. this._intermediateRendering = true;
  21995. for (var i = 0; i < this.highlightLayers.length; i++) {
  21996. var highlightLayer = this.highlightLayers[i];
  21997. if (highlightLayer.shouldRender() &&
  21998. (!highlightLayer.camera ||
  21999. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  22000. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  22001. renderhighlights = true;
  22002. var renderTarget = highlightLayer._mainTexture;
  22003. if (renderTarget._shouldRender()) {
  22004. this._renderId++;
  22005. renderTarget.render(false, false);
  22006. needsRestoreFrameBuffer = true;
  22007. }
  22008. }
  22009. }
  22010. this._intermediateRendering = false;
  22011. this._renderId++;
  22012. }
  22013. if (needsRestoreFrameBuffer) {
  22014. engine.restoreDefaultFramebuffer(); // Restore back buffer
  22015. }
  22016. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22017. // Prepare Frame
  22018. this.postProcessManager._prepareFrame();
  22019. // Backgrounds
  22020. var layerIndex;
  22021. var layer;
  22022. if (this.layers.length) {
  22023. engine.setDepthBuffer(false);
  22024. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22025. layer = this.layers[layerIndex];
  22026. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22027. layer.render();
  22028. }
  22029. }
  22030. engine.setDepthBuffer(true);
  22031. }
  22032. // Activate HighlightLayer stencil
  22033. if (renderhighlights) {
  22034. this._engine.setStencilBuffer(true);
  22035. }
  22036. // Render
  22037. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  22038. this._renderingManager.render(null, null, true, true);
  22039. this.onAfterDrawPhaseObservable.notifyObservers(this);
  22040. // Restore HighlightLayer stencil
  22041. if (renderhighlights) {
  22042. this._engine.setStencilBuffer(stencilState);
  22043. }
  22044. // Bounding boxes
  22045. if (this._boundingBoxRenderer) {
  22046. this._boundingBoxRenderer.render();
  22047. }
  22048. // Lens flares
  22049. if (this.lensFlaresEnabled) {
  22050. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22051. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  22052. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  22053. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  22054. lensFlareSystem.render();
  22055. }
  22056. }
  22057. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  22058. }
  22059. // Foregrounds
  22060. if (this.layers.length) {
  22061. engine.setDepthBuffer(false);
  22062. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  22063. layer = this.layers[layerIndex];
  22064. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  22065. layer.render();
  22066. }
  22067. }
  22068. engine.setDepthBuffer(true);
  22069. }
  22070. // Highlight Layer
  22071. if (renderhighlights) {
  22072. engine.setDepthBuffer(false);
  22073. for (var i = 0; i < this.highlightLayers.length; i++) {
  22074. if (this.highlightLayers[i].shouldRender()) {
  22075. this.highlightLayers[i].render();
  22076. }
  22077. }
  22078. engine.setDepthBuffer(true);
  22079. }
  22080. // Finalize frame
  22081. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  22082. // Reset some special arrays
  22083. this._renderTargets.reset();
  22084. this._alternateRendering = false;
  22085. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  22086. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  22087. };
  22088. Scene.prototype._processSubCameras = function (camera) {
  22089. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  22090. this._renderForCamera(camera);
  22091. return;
  22092. }
  22093. // Update camera
  22094. if (this.activeCamera) {
  22095. this.activeCamera.update();
  22096. }
  22097. // rig cameras
  22098. for (var index = 0; index < camera._rigCameras.length; index++) {
  22099. this._renderForCamera(camera._rigCameras[index]);
  22100. }
  22101. this.activeCamera = camera;
  22102. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  22103. };
  22104. Scene.prototype._checkIntersections = function () {
  22105. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  22106. var sourceMesh = this._meshesForIntersections.data[index];
  22107. if (!sourceMesh.actionManager) {
  22108. continue;
  22109. }
  22110. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  22111. var action = sourceMesh.actionManager.actions[actionIndex];
  22112. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22113. var parameters = action.getTriggerParameter();
  22114. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  22115. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  22116. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  22117. if (areIntersecting && currentIntersectionInProgress === -1) {
  22118. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  22119. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22120. sourceMesh._intersectionsInProgress.push(otherMesh);
  22121. }
  22122. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22123. sourceMesh._intersectionsInProgress.push(otherMesh);
  22124. }
  22125. }
  22126. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  22127. //They intersected, and now they don't.
  22128. //is this trigger an exit trigger? execute an event.
  22129. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22130. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  22131. }
  22132. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  22133. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  22134. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  22135. }
  22136. }
  22137. }
  22138. }
  22139. }
  22140. };
  22141. Scene.prototype.render = function () {
  22142. if (this.isDisposed) {
  22143. return;
  22144. }
  22145. this._activeParticles.fetchNewFrame();
  22146. this._totalVertices.fetchNewFrame();
  22147. this._activeIndices.fetchNewFrame();
  22148. this._activeBones.fetchNewFrame();
  22149. this._meshesForIntersections.reset();
  22150. this.resetCachedMaterial();
  22151. this.onBeforeAnimationsObservable.notifyObservers(this);
  22152. // Actions
  22153. if (this.actionManager) {
  22154. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  22155. }
  22156. //Simplification Queue
  22157. if (this.simplificationQueue && !this.simplificationQueue.running) {
  22158. this.simplificationQueue.executeNext();
  22159. }
  22160. if (this._engine.isDeterministicLockStep()) {
  22161. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  22162. var defaultFPS = (60.0 / 1000.0);
  22163. var defaultFrameTime = 1000 / 60; // frame time in MS
  22164. if (this._physicsEngine) {
  22165. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  22166. }
  22167. var stepsTaken = 0;
  22168. var maxSubSteps = this._engine.getLockstepMaxSteps();
  22169. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  22170. internalSteps = Math.min(internalSteps, maxSubSteps);
  22171. do {
  22172. this.onBeforeStepObservable.notifyObservers(this);
  22173. // Animations
  22174. this._animationRatio = defaultFrameTime * defaultFPS;
  22175. this._animate();
  22176. this.onAfterAnimationsObservable.notifyObservers(this);
  22177. // Physics
  22178. if (this._physicsEngine) {
  22179. this.onBeforePhysicsObservable.notifyObservers(this);
  22180. this._physicsEngine._step(defaultFrameTime / 1000);
  22181. this.onAfterPhysicsObservable.notifyObservers(this);
  22182. }
  22183. this.onAfterStepObservable.notifyObservers(this);
  22184. this._currentStepId++;
  22185. stepsTaken++;
  22186. deltaTime -= defaultFrameTime;
  22187. } while (deltaTime > 0 && stepsTaken < internalSteps);
  22188. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  22189. }
  22190. else {
  22191. // Animations
  22192. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  22193. this._animationRatio = deltaTime * (60.0 / 1000.0);
  22194. this._animate();
  22195. this.onAfterAnimationsObservable.notifyObservers(this);
  22196. // Physics
  22197. if (this._physicsEngine) {
  22198. this.onBeforePhysicsObservable.notifyObservers(this);
  22199. this._physicsEngine._step(deltaTime / 1000.0);
  22200. this.onAfterPhysicsObservable.notifyObservers(this);
  22201. }
  22202. }
  22203. // update gamepad manager
  22204. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  22205. this._gamepadManager._checkGamepadsStatus();
  22206. }
  22207. // Before render
  22208. this.onBeforeRenderObservable.notifyObservers(this);
  22209. // Customs render targets
  22210. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  22211. var engine = this.getEngine();
  22212. var currentActiveCamera = this.activeCamera;
  22213. if (this.renderTargetsEnabled) {
  22214. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22215. this._intermediateRendering = true;
  22216. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  22217. var renderTarget = this.customRenderTargets[customIndex];
  22218. if (renderTarget._shouldRender()) {
  22219. this._renderId++;
  22220. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  22221. if (!this.activeCamera)
  22222. throw new Error("Active camera not set");
  22223. // Viewport
  22224. engine.setViewport(this.activeCamera.viewport);
  22225. // Camera
  22226. this.updateTransformMatrix();
  22227. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  22228. }
  22229. }
  22230. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  22231. this._intermediateRendering = false;
  22232. this._renderId++;
  22233. }
  22234. // Restore back buffer
  22235. if (this.customRenderTargets.length > 0) {
  22236. engine.restoreDefaultFramebuffer();
  22237. }
  22238. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  22239. this.activeCamera = currentActiveCamera;
  22240. // Procedural textures
  22241. if (this.proceduralTexturesEnabled) {
  22242. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22243. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  22244. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  22245. if (proceduralTexture._shouldRender()) {
  22246. proceduralTexture.render();
  22247. }
  22248. }
  22249. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  22250. }
  22251. // Clear
  22252. if (this.autoClearDepthAndStencil || this.autoClear) {
  22253. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  22254. }
  22255. // Shadows
  22256. if (this.shadowsEnabled) {
  22257. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  22258. var light = this.lights[lightIndex];
  22259. var shadowGenerator = light.getShadowGenerator();
  22260. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  22261. var shadowMap = (shadowGenerator.getShadowMap());
  22262. if (this.textures.indexOf(shadowMap) !== -1) {
  22263. this._renderTargets.push(shadowMap);
  22264. }
  22265. }
  22266. }
  22267. }
  22268. // Depth renderer
  22269. if (this._depthRenderer) {
  22270. this._renderTargets.push(this._depthRenderer.getDepthMap());
  22271. }
  22272. // Geometry renderer
  22273. if (this._geometryBufferRenderer) {
  22274. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  22275. }
  22276. // RenderPipeline
  22277. if (this._postProcessRenderPipelineManager) {
  22278. this._postProcessRenderPipelineManager.update();
  22279. }
  22280. // Multi-cameras?
  22281. if (this.activeCameras.length > 0) {
  22282. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  22283. if (cameraIndex > 0) {
  22284. this._engine.clear(null, false, true, true);
  22285. }
  22286. this._processSubCameras(this.activeCameras[cameraIndex]);
  22287. }
  22288. }
  22289. else {
  22290. if (!this.activeCamera) {
  22291. throw new Error("No camera defined");
  22292. }
  22293. this._processSubCameras(this.activeCamera);
  22294. }
  22295. // Intersection checks
  22296. this._checkIntersections();
  22297. // Update the audio listener attached to the camera
  22298. if (BABYLON.AudioEngine) {
  22299. this._updateAudioParameters();
  22300. }
  22301. // After render
  22302. if (this.afterRender) {
  22303. this.afterRender();
  22304. }
  22305. this.onAfterRenderObservable.notifyObservers(this);
  22306. // Cleaning
  22307. for (var index = 0; index < this._toBeDisposed.length; index++) {
  22308. var data = this._toBeDisposed.data[index];
  22309. if (data) {
  22310. data.dispose();
  22311. }
  22312. this._toBeDisposed[index] = null;
  22313. }
  22314. this._toBeDisposed.reset();
  22315. if (this.dumpNextRenderTargets) {
  22316. this.dumpNextRenderTargets = false;
  22317. }
  22318. this._activeBones.addCount(0, true);
  22319. this._activeIndices.addCount(0, true);
  22320. this._activeParticles.addCount(0, true);
  22321. };
  22322. Scene.prototype._updateAudioParameters = function () {
  22323. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  22324. return;
  22325. }
  22326. var listeningCamera;
  22327. var audioEngine = BABYLON.Engine.audioEngine;
  22328. if (this.activeCameras.length > 0) {
  22329. listeningCamera = this.activeCameras[0];
  22330. }
  22331. else {
  22332. listeningCamera = this.activeCamera;
  22333. }
  22334. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  22335. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  22336. // for VR cameras
  22337. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  22338. listeningCamera = listeningCamera.rigCameras[0];
  22339. }
  22340. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  22341. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  22342. cameraDirection.normalize();
  22343. // To avoid some errors on GearVR
  22344. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  22345. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  22346. }
  22347. var i;
  22348. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22349. var sound = this.mainSoundTrack.soundCollection[i];
  22350. if (sound.useCustomAttenuation) {
  22351. sound.updateDistanceFromListener();
  22352. }
  22353. }
  22354. for (i = 0; i < this.soundTracks.length; i++) {
  22355. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22356. sound = this.soundTracks[i].soundCollection[j];
  22357. if (sound.useCustomAttenuation) {
  22358. sound.updateDistanceFromListener();
  22359. }
  22360. }
  22361. }
  22362. }
  22363. };
  22364. Object.defineProperty(Scene.prototype, "audioEnabled", {
  22365. // Audio
  22366. get: function () {
  22367. return this._audioEnabled;
  22368. },
  22369. set: function (value) {
  22370. this._audioEnabled = value;
  22371. if (BABYLON.AudioEngine) {
  22372. if (this._audioEnabled) {
  22373. this._enableAudio();
  22374. }
  22375. else {
  22376. this._disableAudio();
  22377. }
  22378. }
  22379. },
  22380. enumerable: true,
  22381. configurable: true
  22382. });
  22383. Scene.prototype._disableAudio = function () {
  22384. var i;
  22385. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22386. this.mainSoundTrack.soundCollection[i].pause();
  22387. }
  22388. for (i = 0; i < this.soundTracks.length; i++) {
  22389. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22390. this.soundTracks[i].soundCollection[j].pause();
  22391. }
  22392. }
  22393. };
  22394. Scene.prototype._enableAudio = function () {
  22395. var i;
  22396. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  22397. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  22398. this.mainSoundTrack.soundCollection[i].play();
  22399. }
  22400. }
  22401. for (i = 0; i < this.soundTracks.length; i++) {
  22402. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  22403. if (this.soundTracks[i].soundCollection[j].isPaused) {
  22404. this.soundTracks[i].soundCollection[j].play();
  22405. }
  22406. }
  22407. }
  22408. };
  22409. Object.defineProperty(Scene.prototype, "headphone", {
  22410. get: function () {
  22411. return this._headphone;
  22412. },
  22413. set: function (value) {
  22414. this._headphone = value;
  22415. if (BABYLON.AudioEngine) {
  22416. if (this._headphone) {
  22417. this._switchAudioModeForHeadphones();
  22418. }
  22419. else {
  22420. this._switchAudioModeForNormalSpeakers();
  22421. }
  22422. }
  22423. },
  22424. enumerable: true,
  22425. configurable: true
  22426. });
  22427. Scene.prototype._switchAudioModeForHeadphones = function () {
  22428. this.mainSoundTrack.switchPanningModelToHRTF();
  22429. for (var i = 0; i < this.soundTracks.length; i++) {
  22430. this.soundTracks[i].switchPanningModelToHRTF();
  22431. }
  22432. };
  22433. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  22434. this.mainSoundTrack.switchPanningModelToEqualPower();
  22435. for (var i = 0; i < this.soundTracks.length; i++) {
  22436. this.soundTracks[i].switchPanningModelToEqualPower();
  22437. }
  22438. };
  22439. Scene.prototype.enableDepthRenderer = function () {
  22440. if (this._depthRenderer) {
  22441. return this._depthRenderer;
  22442. }
  22443. this._depthRenderer = new BABYLON.DepthRenderer(this);
  22444. return this._depthRenderer;
  22445. };
  22446. Scene.prototype.disableDepthRenderer = function () {
  22447. if (!this._depthRenderer) {
  22448. return;
  22449. }
  22450. this._depthRenderer.dispose();
  22451. this._depthRenderer = null;
  22452. };
  22453. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  22454. if (ratio === void 0) { ratio = 1; }
  22455. if (this._geometryBufferRenderer) {
  22456. return this._geometryBufferRenderer;
  22457. }
  22458. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  22459. if (!this._geometryBufferRenderer.isSupported) {
  22460. this._geometryBufferRenderer = null;
  22461. }
  22462. return this._geometryBufferRenderer;
  22463. };
  22464. Scene.prototype.disableGeometryBufferRenderer = function () {
  22465. if (!this._geometryBufferRenderer) {
  22466. return;
  22467. }
  22468. this._geometryBufferRenderer.dispose();
  22469. this._geometryBufferRenderer = null;
  22470. };
  22471. Scene.prototype.freezeMaterials = function () {
  22472. for (var i = 0; i < this.materials.length; i++) {
  22473. this.materials[i].freeze();
  22474. }
  22475. };
  22476. Scene.prototype.unfreezeMaterials = function () {
  22477. for (var i = 0; i < this.materials.length; i++) {
  22478. this.materials[i].unfreeze();
  22479. }
  22480. };
  22481. Scene.prototype.dispose = function () {
  22482. this.beforeRender = null;
  22483. this.afterRender = null;
  22484. this.skeletons = [];
  22485. this.morphTargetManagers = [];
  22486. this.importedMeshesFiles = new Array();
  22487. this.stopAllAnimations();
  22488. this.resetCachedMaterial();
  22489. if (this._depthRenderer) {
  22490. this._depthRenderer.dispose();
  22491. }
  22492. if (this._gamepadManager) {
  22493. this._gamepadManager.dispose();
  22494. this._gamepadManager = null;
  22495. }
  22496. // Smart arrays
  22497. if (this.activeCamera) {
  22498. this.activeCamera._activeMeshes.dispose();
  22499. this.activeCamera = null;
  22500. }
  22501. this._activeMeshes.dispose();
  22502. this._renderingManager.dispose();
  22503. this._processedMaterials.dispose();
  22504. this._activeParticleSystems.dispose();
  22505. this._activeSkeletons.dispose();
  22506. this._softwareSkinnedMeshes.dispose();
  22507. this._renderTargets.dispose();
  22508. if (this._boundingBoxRenderer) {
  22509. this._boundingBoxRenderer.dispose();
  22510. }
  22511. this._meshesForIntersections.dispose();
  22512. this._toBeDisposed.dispose();
  22513. // Abort active requests
  22514. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  22515. var request = _a[_i];
  22516. request.abort();
  22517. }
  22518. // Debug layer
  22519. if (this._debugLayer) {
  22520. this._debugLayer.hide();
  22521. }
  22522. // Events
  22523. this.onDisposeObservable.notifyObservers(this);
  22524. this.onDisposeObservable.clear();
  22525. this.onBeforeRenderObservable.clear();
  22526. this.onAfterRenderObservable.clear();
  22527. this.OnBeforeRenderTargetsRenderObservable.clear();
  22528. this.OnAfterRenderTargetsRenderObservable.clear();
  22529. this.onAfterStepObservable.clear();
  22530. this.onBeforeStepObservable.clear();
  22531. this.onBeforeActiveMeshesEvaluationObservable.clear();
  22532. this.onAfterActiveMeshesEvaluationObservable.clear();
  22533. this.onBeforeParticlesRenderingObservable.clear();
  22534. this.onAfterParticlesRenderingObservable.clear();
  22535. this.onBeforeSpritesRenderingObservable.clear();
  22536. this.onAfterSpritesRenderingObservable.clear();
  22537. this.onBeforeDrawPhaseObservable.clear();
  22538. this.onAfterDrawPhaseObservable.clear();
  22539. this.onBeforePhysicsObservable.clear();
  22540. this.onAfterPhysicsObservable.clear();
  22541. this.onBeforeAnimationsObservable.clear();
  22542. this.onAfterAnimationsObservable.clear();
  22543. this.onDataLoadedObservable.clear();
  22544. this.detachControl();
  22545. // Release sounds & sounds tracks
  22546. if (BABYLON.AudioEngine) {
  22547. this.disposeSounds();
  22548. }
  22549. // VR Helper
  22550. if (this.VRHelper) {
  22551. this.VRHelper.dispose();
  22552. }
  22553. // Detach cameras
  22554. var canvas = this._engine.getRenderingCanvas();
  22555. if (canvas) {
  22556. var index;
  22557. for (index = 0; index < this.cameras.length; index++) {
  22558. this.cameras[index].detachControl(canvas);
  22559. }
  22560. }
  22561. // Release animation groups
  22562. while (this.animationGroups.length) {
  22563. this.animationGroups[0].dispose();
  22564. }
  22565. // Release lights
  22566. while (this.lights.length) {
  22567. this.lights[0].dispose();
  22568. }
  22569. // Release meshes
  22570. while (this.meshes.length) {
  22571. this.meshes[0].dispose(true);
  22572. }
  22573. while (this.transformNodes.length) {
  22574. this.removeTransformNode(this.transformNodes[0]);
  22575. }
  22576. // Release cameras
  22577. while (this.cameras.length) {
  22578. this.cameras[0].dispose();
  22579. }
  22580. // Release materials
  22581. if (this.defaultMaterial) {
  22582. this.defaultMaterial.dispose();
  22583. }
  22584. while (this.multiMaterials.length) {
  22585. this.multiMaterials[0].dispose();
  22586. }
  22587. while (this.materials.length) {
  22588. this.materials[0].dispose();
  22589. }
  22590. // Release particles
  22591. while (this.particleSystems.length) {
  22592. this.particleSystems[0].dispose();
  22593. }
  22594. // Release sprites
  22595. while (this.spriteManagers.length) {
  22596. this.spriteManagers[0].dispose();
  22597. }
  22598. // Release postProcesses
  22599. while (this.postProcesses.length) {
  22600. this.postProcesses[0].dispose();
  22601. }
  22602. // Release layers
  22603. while (this.layers.length) {
  22604. this.layers[0].dispose();
  22605. }
  22606. while (this.highlightLayers.length) {
  22607. this.highlightLayers[0].dispose();
  22608. }
  22609. // Release textures
  22610. while (this.textures.length) {
  22611. this.textures[0].dispose();
  22612. }
  22613. // Release UBO
  22614. this._sceneUbo.dispose();
  22615. if (this._alternateSceneUbo) {
  22616. this._alternateSceneUbo.dispose();
  22617. }
  22618. // Post-processes
  22619. this.postProcessManager.dispose();
  22620. if (this._postProcessRenderPipelineManager) {
  22621. this._postProcessRenderPipelineManager.dispose();
  22622. }
  22623. // Physics
  22624. if (this._physicsEngine) {
  22625. this.disablePhysicsEngine();
  22626. }
  22627. // Remove from engine
  22628. index = this._engine.scenes.indexOf(this);
  22629. if (index > -1) {
  22630. this._engine.scenes.splice(index, 1);
  22631. }
  22632. this._engine.wipeCaches(true);
  22633. this._isDisposed = true;
  22634. };
  22635. Object.defineProperty(Scene.prototype, "isDisposed", {
  22636. get: function () {
  22637. return this._isDisposed;
  22638. },
  22639. enumerable: true,
  22640. configurable: true
  22641. });
  22642. // Release sounds & sounds tracks
  22643. Scene.prototype.disposeSounds = function () {
  22644. if (!this._mainSoundTrack) {
  22645. return;
  22646. }
  22647. this.mainSoundTrack.dispose();
  22648. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  22649. this.soundTracks[scIndex].dispose();
  22650. }
  22651. };
  22652. // Octrees
  22653. Scene.prototype.getWorldExtends = function () {
  22654. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22655. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  22656. for (var index = 0; index < this.meshes.length; index++) {
  22657. var mesh = this.meshes[index];
  22658. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  22659. continue;
  22660. }
  22661. mesh.computeWorldMatrix(true);
  22662. var boundingInfo = mesh.getBoundingInfo();
  22663. var minBox = boundingInfo.boundingBox.minimumWorld;
  22664. var maxBox = boundingInfo.boundingBox.maximumWorld;
  22665. BABYLON.Tools.CheckExtends(minBox, min, max);
  22666. BABYLON.Tools.CheckExtends(maxBox, min, max);
  22667. }
  22668. return {
  22669. min: min,
  22670. max: max
  22671. };
  22672. };
  22673. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  22674. if (maxCapacity === void 0) { maxCapacity = 64; }
  22675. if (maxDepth === void 0) { maxDepth = 2; }
  22676. if (!this._selectionOctree) {
  22677. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  22678. }
  22679. var worldExtends = this.getWorldExtends();
  22680. // Update octree
  22681. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  22682. return this._selectionOctree;
  22683. };
  22684. // Picking
  22685. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  22686. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22687. var result = BABYLON.Ray.Zero();
  22688. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  22689. return result;
  22690. };
  22691. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  22692. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  22693. var engine = this._engine;
  22694. if (!camera) {
  22695. if (!this.activeCamera)
  22696. throw new Error("Active camera not set");
  22697. camera = this.activeCamera;
  22698. }
  22699. var cameraViewport = camera.viewport;
  22700. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22701. // Moving coordinates to local viewport world
  22702. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22703. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22704. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  22705. return this;
  22706. };
  22707. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  22708. var result = BABYLON.Ray.Zero();
  22709. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  22710. return result;
  22711. };
  22712. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  22713. if (!BABYLON.PickingInfo) {
  22714. return this;
  22715. }
  22716. var engine = this._engine;
  22717. if (!camera) {
  22718. if (!this.activeCamera)
  22719. throw new Error("Active camera not set");
  22720. camera = this.activeCamera;
  22721. }
  22722. var cameraViewport = camera.viewport;
  22723. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  22724. var identity = BABYLON.Matrix.Identity();
  22725. // Moving coordinates to local viewport world
  22726. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  22727. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  22728. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  22729. return this;
  22730. };
  22731. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  22732. if (!BABYLON.PickingInfo) {
  22733. return null;
  22734. }
  22735. var pickingInfo = null;
  22736. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22737. var mesh = this.meshes[meshIndex];
  22738. if (predicate) {
  22739. if (!predicate(mesh)) {
  22740. continue;
  22741. }
  22742. }
  22743. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22744. continue;
  22745. }
  22746. var world = mesh.getWorldMatrix();
  22747. var ray = rayFunction(world);
  22748. var result = mesh.intersects(ray, fastCheck);
  22749. if (!result || !result.hit)
  22750. continue;
  22751. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22752. continue;
  22753. pickingInfo = result;
  22754. if (fastCheck) {
  22755. break;
  22756. }
  22757. }
  22758. return pickingInfo || new BABYLON.PickingInfo();
  22759. };
  22760. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  22761. if (!BABYLON.PickingInfo) {
  22762. return null;
  22763. }
  22764. var pickingInfos = new Array();
  22765. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  22766. var mesh = this.meshes[meshIndex];
  22767. if (predicate) {
  22768. if (!predicate(mesh)) {
  22769. continue;
  22770. }
  22771. }
  22772. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  22773. continue;
  22774. }
  22775. var world = mesh.getWorldMatrix();
  22776. var ray = rayFunction(world);
  22777. var result = mesh.intersects(ray, false);
  22778. if (!result || !result.hit)
  22779. continue;
  22780. pickingInfos.push(result);
  22781. }
  22782. return pickingInfos;
  22783. };
  22784. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  22785. if (!BABYLON.PickingInfo) {
  22786. return null;
  22787. }
  22788. var pickingInfo = null;
  22789. if (!camera) {
  22790. if (!this.activeCamera) {
  22791. return null;
  22792. }
  22793. camera = this.activeCamera;
  22794. }
  22795. if (this.spriteManagers.length > 0) {
  22796. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  22797. var spriteManager = this.spriteManagers[spriteIndex];
  22798. if (!spriteManager.isPickable) {
  22799. continue;
  22800. }
  22801. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  22802. if (!result || !result.hit)
  22803. continue;
  22804. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  22805. continue;
  22806. pickingInfo = result;
  22807. if (fastCheck) {
  22808. break;
  22809. }
  22810. }
  22811. }
  22812. return pickingInfo || new BABYLON.PickingInfo();
  22813. };
  22814. /** Launch a ray to try to pick a mesh in the scene
  22815. * @param x position on screen
  22816. * @param y position on screen
  22817. * @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
  22818. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22819. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22820. */
  22821. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  22822. var _this = this;
  22823. if (!BABYLON.PickingInfo) {
  22824. return null;
  22825. }
  22826. return this._internalPick(function (world) {
  22827. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  22828. return _this._tempPickingRay;
  22829. }, predicate, fastCheck);
  22830. };
  22831. /** Launch a ray to try to pick a sprite in the scene
  22832. * @param x position on screen
  22833. * @param y position on screen
  22834. * @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
  22835. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22836. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22837. */
  22838. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  22839. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  22840. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  22841. };
  22842. /** Use the given ray to pick a mesh in the scene
  22843. * @param ray The ray to use to pick meshes
  22844. * @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
  22845. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  22846. */
  22847. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  22848. var _this = this;
  22849. return this._internalPick(function (world) {
  22850. if (!_this._pickWithRayInverseMatrix) {
  22851. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22852. }
  22853. world.invertToRef(_this._pickWithRayInverseMatrix);
  22854. if (!_this._cachedRayForTransform) {
  22855. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22856. }
  22857. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22858. return _this._cachedRayForTransform;
  22859. }, predicate, fastCheck);
  22860. };
  22861. /**
  22862. * Launch a ray to try to pick a mesh in the scene
  22863. * @param x X position on screen
  22864. * @param y Y position on screen
  22865. * @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
  22866. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  22867. */
  22868. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  22869. var _this = this;
  22870. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  22871. };
  22872. /**
  22873. * Launch a ray to try to pick a mesh in the scene
  22874. * @param ray Ray to use
  22875. * @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
  22876. */
  22877. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  22878. var _this = this;
  22879. return this._internalMultiPick(function (world) {
  22880. if (!_this._pickWithRayInverseMatrix) {
  22881. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  22882. }
  22883. world.invertToRef(_this._pickWithRayInverseMatrix);
  22884. if (!_this._cachedRayForTransform) {
  22885. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  22886. }
  22887. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  22888. return _this._cachedRayForTransform;
  22889. }, predicate);
  22890. };
  22891. Scene.prototype.setPointerOverMesh = function (mesh) {
  22892. if (this._pointerOverMesh === mesh) {
  22893. return;
  22894. }
  22895. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22896. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22897. }
  22898. this._pointerOverMesh = mesh;
  22899. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  22900. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  22901. }
  22902. };
  22903. Scene.prototype.getPointerOverMesh = function () {
  22904. return this._pointerOverMesh;
  22905. };
  22906. Scene.prototype.setPointerOverSprite = function (sprite) {
  22907. if (this._pointerOverSprite === sprite) {
  22908. return;
  22909. }
  22910. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22911. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22912. }
  22913. this._pointerOverSprite = sprite;
  22914. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  22915. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  22916. }
  22917. };
  22918. Scene.prototype.getPointerOverSprite = function () {
  22919. return this._pointerOverSprite;
  22920. };
  22921. // Physics
  22922. Scene.prototype.getPhysicsEngine = function () {
  22923. return this._physicsEngine;
  22924. };
  22925. /**
  22926. * Enables physics to the current scene
  22927. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  22928. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  22929. * @return {boolean} was the physics engine initialized
  22930. */
  22931. Scene.prototype.enablePhysics = function (gravity, plugin) {
  22932. if (gravity === void 0) { gravity = null; }
  22933. if (this._physicsEngine) {
  22934. return true;
  22935. }
  22936. try {
  22937. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  22938. return true;
  22939. }
  22940. catch (e) {
  22941. BABYLON.Tools.Error(e.message);
  22942. return false;
  22943. }
  22944. };
  22945. Scene.prototype.disablePhysicsEngine = function () {
  22946. if (!this._physicsEngine) {
  22947. return;
  22948. }
  22949. this._physicsEngine.dispose();
  22950. this._physicsEngine = null;
  22951. };
  22952. Scene.prototype.isPhysicsEnabled = function () {
  22953. return this._physicsEngine !== undefined;
  22954. };
  22955. Scene.prototype.deleteCompoundImpostor = function (compound) {
  22956. var mesh = compound.parts[0].mesh;
  22957. if (mesh.physicsImpostor) {
  22958. mesh.physicsImpostor.dispose();
  22959. mesh.physicsImpostor = null;
  22960. }
  22961. };
  22962. // Misc.
  22963. Scene.prototype._rebuildGeometries = function () {
  22964. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  22965. var geometry = _a[_i];
  22966. geometry._rebuild();
  22967. }
  22968. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  22969. var mesh = _c[_b];
  22970. mesh._rebuild();
  22971. }
  22972. if (this.postProcessManager) {
  22973. this.postProcessManager._rebuild();
  22974. }
  22975. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  22976. var layer = _e[_d];
  22977. layer._rebuild();
  22978. }
  22979. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  22980. var highlightLayer = _g[_f];
  22981. highlightLayer._rebuild();
  22982. }
  22983. if (this._boundingBoxRenderer) {
  22984. this._boundingBoxRenderer._rebuild();
  22985. }
  22986. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  22987. var system = _j[_h];
  22988. system.rebuild();
  22989. }
  22990. if (this._postProcessRenderPipelineManager) {
  22991. this._postProcessRenderPipelineManager._rebuild();
  22992. }
  22993. };
  22994. Scene.prototype._rebuildTextures = function () {
  22995. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  22996. var texture = _a[_i];
  22997. texture._rebuild();
  22998. }
  22999. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23000. };
  23001. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  23002. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  23003. if (replace === void 0) { replace = false; }
  23004. if (attachCameraControls === void 0) { attachCameraControls = false; }
  23005. // Dispose existing camera or light in replace mode.
  23006. if (replace) {
  23007. if (this.activeCamera) {
  23008. this.activeCamera.dispose();
  23009. this.activeCamera = null;
  23010. }
  23011. if (this.lights) {
  23012. for (var i = 0; i < this.lights.length; i++) {
  23013. this.lights[i].dispose();
  23014. }
  23015. }
  23016. }
  23017. // Light
  23018. if (this.lights.length === 0) {
  23019. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  23020. }
  23021. // Camera
  23022. if (!this.activeCamera) {
  23023. var worldExtends = this.getWorldExtends();
  23024. var worldSize = worldExtends.max.subtract(worldExtends.min);
  23025. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  23026. var camera;
  23027. var radius = worldSize.length() * 1.5;
  23028. if (createArcRotateCamera) {
  23029. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  23030. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  23031. arcRotateCamera.wheelPrecision = 100 / radius;
  23032. camera = arcRotateCamera;
  23033. }
  23034. else {
  23035. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  23036. freeCamera.setTarget(worldCenter);
  23037. camera = freeCamera;
  23038. }
  23039. camera.minZ = radius * 0.01;
  23040. camera.maxZ = radius * 1000;
  23041. camera.speed = radius * 0.2;
  23042. this.activeCamera = camera;
  23043. var canvas = this.getEngine().getRenderingCanvas();
  23044. if (attachCameraControls && canvas) {
  23045. camera.attachControl(canvas);
  23046. }
  23047. }
  23048. };
  23049. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  23050. if (pbr === void 0) { pbr = false; }
  23051. if (scale === void 0) { scale = 1000; }
  23052. if (blur === void 0) { blur = 0; }
  23053. if (environmentTexture) {
  23054. this.environmentTexture = environmentTexture;
  23055. }
  23056. if (!this.environmentTexture) {
  23057. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  23058. return null;
  23059. }
  23060. // Skybox
  23061. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  23062. if (pbr) {
  23063. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  23064. hdrSkyboxMaterial.backFaceCulling = false;
  23065. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23066. if (hdrSkyboxMaterial.reflectionTexture) {
  23067. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23068. }
  23069. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  23070. hdrSkyboxMaterial.disableLighting = true;
  23071. hdrSkyboxMaterial.twoSidedLighting = true;
  23072. hdrSkybox.infiniteDistance = true;
  23073. hdrSkybox.material = hdrSkyboxMaterial;
  23074. }
  23075. else {
  23076. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  23077. skyboxMaterial.backFaceCulling = false;
  23078. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  23079. if (skyboxMaterial.reflectionTexture) {
  23080. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  23081. }
  23082. skyboxMaterial.disableLighting = true;
  23083. hdrSkybox.infiniteDistance = true;
  23084. hdrSkybox.material = skyboxMaterial;
  23085. }
  23086. return hdrSkybox;
  23087. };
  23088. Scene.prototype.createDefaultEnvironment = function (options) {
  23089. if (BABYLON.EnvironmentHelper) {
  23090. return new BABYLON.EnvironmentHelper(options, this);
  23091. }
  23092. return null;
  23093. };
  23094. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  23095. if (webVROptions === void 0) { webVROptions = {}; }
  23096. return new BABYLON.VRExperienceHelper(this, webVROptions);
  23097. };
  23098. // Tags
  23099. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  23100. if (tagsQuery === undefined) {
  23101. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  23102. return list;
  23103. }
  23104. var listByTags = [];
  23105. forEach = forEach || (function (item) { return; });
  23106. for (var i in list) {
  23107. var item = list[i];
  23108. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  23109. listByTags.push(item);
  23110. forEach(item);
  23111. }
  23112. }
  23113. return listByTags;
  23114. };
  23115. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  23116. return this._getByTags(this.meshes, tagsQuery, forEach);
  23117. };
  23118. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  23119. return this._getByTags(this.cameras, tagsQuery, forEach);
  23120. };
  23121. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  23122. return this._getByTags(this.lights, tagsQuery, forEach);
  23123. };
  23124. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  23125. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  23126. };
  23127. /**
  23128. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23129. * This allowed control for front to back rendering or reversly depending of the special needs.
  23130. *
  23131. * @param renderingGroupId The rendering group id corresponding to its index
  23132. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23133. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23134. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23135. */
  23136. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23137. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23138. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23139. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23140. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23141. };
  23142. /**
  23143. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23144. *
  23145. * @param renderingGroupId The rendering group id corresponding to its index
  23146. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23147. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23148. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23149. */
  23150. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23151. if (depth === void 0) { depth = true; }
  23152. if (stencil === void 0) { stencil = true; }
  23153. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  23154. };
  23155. /**
  23156. * Will flag all materials as dirty to trigger new shader compilation
  23157. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  23158. */
  23159. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  23160. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  23161. var material = _a[_i];
  23162. if (predicate && !predicate(material)) {
  23163. continue;
  23164. }
  23165. material.markAsDirty(flag);
  23166. }
  23167. };
  23168. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  23169. var _this = this;
  23170. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  23171. this._activeRequests.push(request);
  23172. request.onCompleteObservable.add(function (request) {
  23173. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  23174. });
  23175. return request;
  23176. };
  23177. // Statics
  23178. Scene._FOGMODE_NONE = 0;
  23179. Scene._FOGMODE_EXP = 1;
  23180. Scene._FOGMODE_EXP2 = 2;
  23181. Scene._FOGMODE_LINEAR = 3;
  23182. Scene._uniqueIdCounter = 0;
  23183. Scene.MinDeltaTime = 1.0;
  23184. Scene.MaxDeltaTime = 1000.0;
  23185. /** The distance in pixel that you have to move to prevent some events */
  23186. Scene.DragMovementThreshold = 10; // in pixels
  23187. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  23188. Scene.LongPressDelay = 500; // in milliseconds
  23189. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  23190. Scene.DoubleClickDelay = 300; // in milliseconds
  23191. /** If you need to check double click without raising a single click at first click, enable this flag */
  23192. Scene.ExclusiveDoubleClickMode = false;
  23193. return Scene;
  23194. }());
  23195. BABYLON.Scene = Scene;
  23196. })(BABYLON || (BABYLON = {}));
  23197. //# sourceMappingURL=babylon.scene.js.map
  23198. var BABYLON;
  23199. (function (BABYLON) {
  23200. var AssetContainer = /** @class */ (function () {
  23201. function AssetContainer(scene) {
  23202. // Objects
  23203. this.cameras = new Array();
  23204. this.lights = new Array();
  23205. this.meshes = new Array();
  23206. this.skeletons = new Array();
  23207. this.particleSystems = new Array();
  23208. this.animations = new Array();
  23209. this.multiMaterials = new Array();
  23210. this.materials = new Array();
  23211. this.morphTargetManagers = new Array();
  23212. this.geometries = new Array();
  23213. this.transformNodes = new Array();
  23214. this.lensFlareSystems = new Array();
  23215. this.shadowGenerators = new Array();
  23216. this.actionManagers = new Array();
  23217. this.sounds = new Array();
  23218. this.scene = scene;
  23219. }
  23220. AssetContainer.prototype.addAllToScene = function () {
  23221. var _this = this;
  23222. this.cameras.forEach(function (o) {
  23223. _this.scene.addCamera(o);
  23224. });
  23225. this.lights.forEach(function (o) {
  23226. _this.scene.addLight(o);
  23227. });
  23228. this.meshes.forEach(function (o) {
  23229. _this.scene.addMesh(o);
  23230. });
  23231. this.skeletons.forEach(function (o) {
  23232. _this.scene.addSkeleton(o);
  23233. });
  23234. this.particleSystems.forEach(function (o) {
  23235. _this.scene.addParticleSystem(o);
  23236. });
  23237. this.animations.forEach(function (o) {
  23238. _this.scene.addAnimation(o);
  23239. });
  23240. this.multiMaterials.forEach(function (o) {
  23241. _this.scene.addMultiMaterial(o);
  23242. });
  23243. this.materials.forEach(function (o) {
  23244. _this.scene.addMaterial(o);
  23245. });
  23246. this.morphTargetManagers.forEach(function (o) {
  23247. _this.scene.addMorphTargetManager(o);
  23248. });
  23249. this.geometries.forEach(function (o) {
  23250. _this.scene.addGeometry(o);
  23251. });
  23252. this.transformNodes.forEach(function (o) {
  23253. _this.scene.addTransformNode(o);
  23254. });
  23255. this.lensFlareSystems.forEach(function (o) {
  23256. _this.scene.addLensFlareSystem(o);
  23257. });
  23258. this.actionManagers.forEach(function (o) {
  23259. _this.scene.addActionManager(o);
  23260. });
  23261. this.sounds.forEach(function (o) {
  23262. o.play();
  23263. o.autoplay = true;
  23264. _this.scene.mainSoundTrack.AddSound(o);
  23265. });
  23266. };
  23267. AssetContainer.prototype.removeAllFromScene = function () {
  23268. var _this = this;
  23269. this.cameras.forEach(function (o) {
  23270. _this.scene.removeCamera(o);
  23271. });
  23272. this.lights.forEach(function (o) {
  23273. _this.scene.removeLight(o);
  23274. });
  23275. this.meshes.forEach(function (o) {
  23276. _this.scene.removeMesh(o);
  23277. });
  23278. this.skeletons.forEach(function (o) {
  23279. _this.scene.removeSkeleton(o);
  23280. });
  23281. this.particleSystems.forEach(function (o) {
  23282. _this.scene.removeParticleSystem(o);
  23283. });
  23284. this.animations.forEach(function (o) {
  23285. _this.scene.removeAnimation(o);
  23286. });
  23287. this.multiMaterials.forEach(function (o) {
  23288. _this.scene.removeMultiMaterial(o);
  23289. });
  23290. this.materials.forEach(function (o) {
  23291. _this.scene.removeMaterial(o);
  23292. });
  23293. this.morphTargetManagers.forEach(function (o) {
  23294. _this.scene.removeMorphTargetManager(o);
  23295. });
  23296. this.geometries.forEach(function (o) {
  23297. _this.scene.removeGeometry(o);
  23298. });
  23299. this.transformNodes.forEach(function (o) {
  23300. _this.scene.removeTransformNode(o);
  23301. });
  23302. this.lensFlareSystems.forEach(function (o) {
  23303. _this.scene.removeLensFlareSystem(o);
  23304. });
  23305. this.actionManagers.forEach(function (o) {
  23306. _this.scene.removeActionManager(o);
  23307. });
  23308. this.sounds.forEach(function (o) {
  23309. o.stop();
  23310. o.autoplay = false;
  23311. _this.scene.mainSoundTrack.RemoveSound(o);
  23312. });
  23313. };
  23314. return AssetContainer;
  23315. }());
  23316. BABYLON.AssetContainer = AssetContainer;
  23317. })(BABYLON || (BABYLON = {}));
  23318. //# sourceMappingURL=babylon.assetContainer.js.map
  23319. var BABYLON;
  23320. (function (BABYLON) {
  23321. var Buffer = /** @class */ (function () {
  23322. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  23323. if (instanced === void 0) { instanced = false; }
  23324. if (engine instanceof BABYLON.Mesh) {
  23325. this._engine = engine.getScene().getEngine();
  23326. }
  23327. else {
  23328. this._engine = engine;
  23329. }
  23330. this._updatable = updatable;
  23331. this._data = data;
  23332. this._strideSize = stride;
  23333. if (!postponeInternalCreation) {
  23334. this.create();
  23335. }
  23336. this._instanced = instanced;
  23337. this._instanceDivisor = instanced ? 1 : 0;
  23338. }
  23339. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  23340. // a lot of these parameters are ignored as they are overriden by the buffer
  23341. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  23342. };
  23343. // Properties
  23344. Buffer.prototype.isUpdatable = function () {
  23345. return this._updatable;
  23346. };
  23347. Buffer.prototype.getData = function () {
  23348. return this._data;
  23349. };
  23350. Buffer.prototype.getBuffer = function () {
  23351. return this._buffer;
  23352. };
  23353. Buffer.prototype.getStrideSize = function () {
  23354. return this._strideSize;
  23355. };
  23356. Buffer.prototype.getIsInstanced = function () {
  23357. return this._instanced;
  23358. };
  23359. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  23360. get: function () {
  23361. return this._instanceDivisor;
  23362. },
  23363. set: function (value) {
  23364. this._instanceDivisor = value;
  23365. if (value == 0) {
  23366. this._instanced = false;
  23367. }
  23368. else {
  23369. this._instanced = true;
  23370. }
  23371. },
  23372. enumerable: true,
  23373. configurable: true
  23374. });
  23375. // Methods
  23376. Buffer.prototype.create = function (data) {
  23377. if (data === void 0) { data = null; }
  23378. if (!data && this._buffer) {
  23379. return; // nothing to do
  23380. }
  23381. data = data || this._data;
  23382. if (!data) {
  23383. return;
  23384. }
  23385. if (!this._buffer) {
  23386. if (this._updatable) {
  23387. this._buffer = this._engine.createDynamicVertexBuffer(data);
  23388. this._data = data;
  23389. }
  23390. else {
  23391. this._buffer = this._engine.createVertexBuffer(data);
  23392. }
  23393. }
  23394. else if (this._updatable) {
  23395. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  23396. this._data = data;
  23397. }
  23398. };
  23399. Buffer.prototype._rebuild = function () {
  23400. this._buffer = null;
  23401. this.create(this._data);
  23402. };
  23403. Buffer.prototype.update = function (data) {
  23404. this.create(data);
  23405. };
  23406. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  23407. if (!this._buffer) {
  23408. return;
  23409. }
  23410. if (this._updatable) {
  23411. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  23412. this._data = null;
  23413. }
  23414. };
  23415. Buffer.prototype.dispose = function () {
  23416. if (!this._buffer) {
  23417. return;
  23418. }
  23419. if (this._engine._releaseBuffer(this._buffer)) {
  23420. this._buffer = null;
  23421. }
  23422. };
  23423. return Buffer;
  23424. }());
  23425. BABYLON.Buffer = Buffer;
  23426. })(BABYLON || (BABYLON = {}));
  23427. //# sourceMappingURL=babylon.buffer.js.map
  23428. var BABYLON;
  23429. (function (BABYLON) {
  23430. var VertexBuffer = /** @class */ (function () {
  23431. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  23432. if (!stride) {
  23433. // Deduce stride from kind
  23434. switch (kind) {
  23435. case VertexBuffer.PositionKind:
  23436. stride = 3;
  23437. break;
  23438. case VertexBuffer.NormalKind:
  23439. stride = 3;
  23440. break;
  23441. case VertexBuffer.UVKind:
  23442. case VertexBuffer.UV2Kind:
  23443. case VertexBuffer.UV3Kind:
  23444. case VertexBuffer.UV4Kind:
  23445. case VertexBuffer.UV5Kind:
  23446. case VertexBuffer.UV6Kind:
  23447. stride = 2;
  23448. break;
  23449. case VertexBuffer.TangentKind:
  23450. case VertexBuffer.ColorKind:
  23451. stride = 4;
  23452. break;
  23453. case VertexBuffer.MatricesIndicesKind:
  23454. case VertexBuffer.MatricesIndicesExtraKind:
  23455. stride = 4;
  23456. break;
  23457. case VertexBuffer.MatricesWeightsKind:
  23458. case VertexBuffer.MatricesWeightsExtraKind:
  23459. default:
  23460. stride = 4;
  23461. break;
  23462. }
  23463. }
  23464. if (data instanceof BABYLON.Buffer) {
  23465. if (!stride) {
  23466. stride = data.getStrideSize();
  23467. }
  23468. this._buffer = data;
  23469. this._ownsBuffer = false;
  23470. }
  23471. else {
  23472. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  23473. this._ownsBuffer = true;
  23474. }
  23475. this._stride = stride;
  23476. this._offset = offset ? offset : 0;
  23477. this._size = size ? size : stride;
  23478. this._kind = kind;
  23479. }
  23480. VertexBuffer.prototype._rebuild = function () {
  23481. if (!this._buffer) {
  23482. return;
  23483. }
  23484. this._buffer._rebuild();
  23485. };
  23486. /**
  23487. * Returns the kind of the VertexBuffer (string).
  23488. */
  23489. VertexBuffer.prototype.getKind = function () {
  23490. return this._kind;
  23491. };
  23492. // Properties
  23493. /**
  23494. * Boolean : is the VertexBuffer updatable ?
  23495. */
  23496. VertexBuffer.prototype.isUpdatable = function () {
  23497. return this._buffer.isUpdatable();
  23498. };
  23499. /**
  23500. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  23501. */
  23502. VertexBuffer.prototype.getData = function () {
  23503. return this._buffer.getData();
  23504. };
  23505. /**
  23506. * Returns the WebGLBuffer associated to the VertexBuffer.
  23507. */
  23508. VertexBuffer.prototype.getBuffer = function () {
  23509. return this._buffer.getBuffer();
  23510. };
  23511. /**
  23512. * Returns the stride of the VertexBuffer (integer).
  23513. */
  23514. VertexBuffer.prototype.getStrideSize = function () {
  23515. return this._stride;
  23516. };
  23517. /**
  23518. * Returns the offset (integer).
  23519. */
  23520. VertexBuffer.prototype.getOffset = function () {
  23521. return this._offset;
  23522. };
  23523. /**
  23524. * Returns the VertexBuffer total size (integer).
  23525. */
  23526. VertexBuffer.prototype.getSize = function () {
  23527. return this._size;
  23528. };
  23529. /**
  23530. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  23531. */
  23532. VertexBuffer.prototype.getIsInstanced = function () {
  23533. return this._buffer.getIsInstanced();
  23534. };
  23535. /**
  23536. * Returns the instancing divisor, zero for non-instanced (integer).
  23537. */
  23538. VertexBuffer.prototype.getInstanceDivisor = function () {
  23539. return this._buffer.instanceDivisor;
  23540. };
  23541. // Methods
  23542. /**
  23543. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  23544. * Returns the created WebGLBuffer.
  23545. */
  23546. VertexBuffer.prototype.create = function (data) {
  23547. return this._buffer.create(data);
  23548. };
  23549. /**
  23550. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23551. * Returns the updated WebGLBuffer.
  23552. */
  23553. VertexBuffer.prototype.update = function (data) {
  23554. return this._buffer.update(data);
  23555. };
  23556. /**
  23557. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  23558. * Returns the directly updated WebGLBuffer.
  23559. */
  23560. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  23561. return this._buffer.updateDirectly(data, offset);
  23562. };
  23563. /**
  23564. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  23565. */
  23566. VertexBuffer.prototype.dispose = function () {
  23567. if (this._ownsBuffer) {
  23568. this._buffer.dispose();
  23569. }
  23570. };
  23571. Object.defineProperty(VertexBuffer, "PositionKind", {
  23572. get: function () {
  23573. return VertexBuffer._PositionKind;
  23574. },
  23575. enumerable: true,
  23576. configurable: true
  23577. });
  23578. Object.defineProperty(VertexBuffer, "NormalKind", {
  23579. get: function () {
  23580. return VertexBuffer._NormalKind;
  23581. },
  23582. enumerable: true,
  23583. configurable: true
  23584. });
  23585. Object.defineProperty(VertexBuffer, "TangentKind", {
  23586. get: function () {
  23587. return VertexBuffer._TangentKind;
  23588. },
  23589. enumerable: true,
  23590. configurable: true
  23591. });
  23592. Object.defineProperty(VertexBuffer, "UVKind", {
  23593. get: function () {
  23594. return VertexBuffer._UVKind;
  23595. },
  23596. enumerable: true,
  23597. configurable: true
  23598. });
  23599. Object.defineProperty(VertexBuffer, "UV2Kind", {
  23600. get: function () {
  23601. return VertexBuffer._UV2Kind;
  23602. },
  23603. enumerable: true,
  23604. configurable: true
  23605. });
  23606. Object.defineProperty(VertexBuffer, "UV3Kind", {
  23607. get: function () {
  23608. return VertexBuffer._UV3Kind;
  23609. },
  23610. enumerable: true,
  23611. configurable: true
  23612. });
  23613. Object.defineProperty(VertexBuffer, "UV4Kind", {
  23614. get: function () {
  23615. return VertexBuffer._UV4Kind;
  23616. },
  23617. enumerable: true,
  23618. configurable: true
  23619. });
  23620. Object.defineProperty(VertexBuffer, "UV5Kind", {
  23621. get: function () {
  23622. return VertexBuffer._UV5Kind;
  23623. },
  23624. enumerable: true,
  23625. configurable: true
  23626. });
  23627. Object.defineProperty(VertexBuffer, "UV6Kind", {
  23628. get: function () {
  23629. return VertexBuffer._UV6Kind;
  23630. },
  23631. enumerable: true,
  23632. configurable: true
  23633. });
  23634. Object.defineProperty(VertexBuffer, "ColorKind", {
  23635. get: function () {
  23636. return VertexBuffer._ColorKind;
  23637. },
  23638. enumerable: true,
  23639. configurable: true
  23640. });
  23641. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  23642. get: function () {
  23643. return VertexBuffer._MatricesIndicesKind;
  23644. },
  23645. enumerable: true,
  23646. configurable: true
  23647. });
  23648. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  23649. get: function () {
  23650. return VertexBuffer._MatricesWeightsKind;
  23651. },
  23652. enumerable: true,
  23653. configurable: true
  23654. });
  23655. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  23656. get: function () {
  23657. return VertexBuffer._MatricesIndicesExtraKind;
  23658. },
  23659. enumerable: true,
  23660. configurable: true
  23661. });
  23662. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  23663. get: function () {
  23664. return VertexBuffer._MatricesWeightsExtraKind;
  23665. },
  23666. enumerable: true,
  23667. configurable: true
  23668. });
  23669. // Enums
  23670. VertexBuffer._PositionKind = "position";
  23671. VertexBuffer._NormalKind = "normal";
  23672. VertexBuffer._TangentKind = "tangent";
  23673. VertexBuffer._UVKind = "uv";
  23674. VertexBuffer._UV2Kind = "uv2";
  23675. VertexBuffer._UV3Kind = "uv3";
  23676. VertexBuffer._UV4Kind = "uv4";
  23677. VertexBuffer._UV5Kind = "uv5";
  23678. VertexBuffer._UV6Kind = "uv6";
  23679. VertexBuffer._ColorKind = "color";
  23680. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  23681. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  23682. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  23683. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  23684. return VertexBuffer;
  23685. }());
  23686. BABYLON.VertexBuffer = VertexBuffer;
  23687. })(BABYLON || (BABYLON = {}));
  23688. //# sourceMappingURL=babylon.vertexBuffer.js.map
  23689. var BABYLON;
  23690. (function (BABYLON) {
  23691. var InternalTexture = /** @class */ (function () {
  23692. function InternalTexture(engine, dataSource) {
  23693. this.onLoadedObservable = new BABYLON.Observable();
  23694. // Private
  23695. this._initialSlot = -1;
  23696. this._designatedSlot = -1;
  23697. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  23698. this._references = 1;
  23699. this._engine = engine;
  23700. this._dataSource = dataSource;
  23701. this._webGLTexture = engine._createTexture();
  23702. }
  23703. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  23704. get: function () {
  23705. return this._dataSource;
  23706. },
  23707. enumerable: true,
  23708. configurable: true
  23709. });
  23710. InternalTexture.prototype.incrementReferences = function () {
  23711. this._references++;
  23712. };
  23713. InternalTexture.prototype.updateSize = function (width, height, depth) {
  23714. if (depth === void 0) { depth = 1; }
  23715. this.width = width;
  23716. this.height = height;
  23717. this.depth = depth;
  23718. this.baseWidth = width;
  23719. this.baseHeight = height;
  23720. this.baseDepth = depth;
  23721. this._size = width * height * depth;
  23722. };
  23723. InternalTexture.prototype._rebuild = function () {
  23724. var _this = this;
  23725. var proxy;
  23726. this.isReady = false;
  23727. this._cachedCoordinatesMode = null;
  23728. this._cachedWrapU = null;
  23729. this._cachedWrapV = null;
  23730. this._cachedAnisotropicFilteringLevel = null;
  23731. switch (this._dataSource) {
  23732. case InternalTexture.DATASOURCE_TEMP:
  23733. return;
  23734. case InternalTexture.DATASOURCE_URL:
  23735. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  23736. _this.isReady = true;
  23737. }, null, this._buffer, undefined, this.format);
  23738. proxy._swapAndDie(this);
  23739. return;
  23740. case InternalTexture.DATASOURCE_RAW:
  23741. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23742. proxy._swapAndDie(this);
  23743. this.isReady = true;
  23744. return;
  23745. case InternalTexture.DATASOURCE_RAW3D:
  23746. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23747. proxy._swapAndDie(this);
  23748. this.isReady = true;
  23749. return;
  23750. case InternalTexture.DATASOURCE_DYNAMIC:
  23751. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  23752. proxy._swapAndDie(this);
  23753. // The engine will make sure to update content so no need to flag it as isReady = true
  23754. return;
  23755. case InternalTexture.DATASOURCE_RENDERTARGET:
  23756. var options = new BABYLON.RenderTargetCreationOptions();
  23757. options.generateDepthBuffer = this._generateDepthBuffer;
  23758. options.generateMipMaps = this.generateMipMaps;
  23759. options.generateStencilBuffer = this._generateStencilBuffer;
  23760. options.samplingMode = this.samplingMode;
  23761. options.type = this.type;
  23762. if (this.isCube) {
  23763. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  23764. }
  23765. else {
  23766. var size = {
  23767. width: this.width,
  23768. height: this.height
  23769. };
  23770. proxy = this._engine.createRenderTargetTexture(size, options);
  23771. }
  23772. proxy._swapAndDie(this);
  23773. this.isReady = true;
  23774. return;
  23775. case InternalTexture.DATASOURCE_CUBE:
  23776. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  23777. _this.isReady = true;
  23778. }, null, this.format, this._extension);
  23779. proxy._swapAndDie(this);
  23780. return;
  23781. case InternalTexture.DATASOURCE_CUBERAW:
  23782. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  23783. proxy._swapAndDie(this);
  23784. this.isReady = true;
  23785. return;
  23786. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  23787. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  23788. if (proxy) {
  23789. proxy._swapAndDie(_this);
  23790. }
  23791. _this.isReady = true;
  23792. }, null, this.format, this._extension);
  23793. return;
  23794. }
  23795. };
  23796. InternalTexture.prototype._swapAndDie = function (target) {
  23797. target._webGLTexture = this._webGLTexture;
  23798. if (this._framebuffer) {
  23799. target._framebuffer = this._framebuffer;
  23800. }
  23801. if (this._depthStencilBuffer) {
  23802. target._depthStencilBuffer = this._depthStencilBuffer;
  23803. }
  23804. if (this._lodTextureHigh) {
  23805. if (target._lodTextureHigh) {
  23806. target._lodTextureHigh.dispose();
  23807. }
  23808. target._lodTextureHigh = this._lodTextureHigh;
  23809. }
  23810. if (this._lodTextureMid) {
  23811. if (target._lodTextureMid) {
  23812. target._lodTextureMid.dispose();
  23813. }
  23814. target._lodTextureMid = this._lodTextureMid;
  23815. }
  23816. if (this._lodTextureLow) {
  23817. if (target._lodTextureLow) {
  23818. target._lodTextureLow.dispose();
  23819. }
  23820. target._lodTextureLow = this._lodTextureLow;
  23821. }
  23822. var cache = this._engine.getLoadedTexturesCache();
  23823. var index = cache.indexOf(this);
  23824. if (index !== -1) {
  23825. cache.splice(index, 1);
  23826. }
  23827. };
  23828. InternalTexture.prototype.dispose = function () {
  23829. if (!this._webGLTexture) {
  23830. return;
  23831. }
  23832. this._references--;
  23833. if (this._references === 0) {
  23834. this._engine._releaseTexture(this);
  23835. this._webGLTexture = null;
  23836. }
  23837. };
  23838. InternalTexture.DATASOURCE_UNKNOWN = 0;
  23839. InternalTexture.DATASOURCE_URL = 1;
  23840. InternalTexture.DATASOURCE_TEMP = 2;
  23841. InternalTexture.DATASOURCE_RAW = 3;
  23842. InternalTexture.DATASOURCE_DYNAMIC = 4;
  23843. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  23844. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  23845. InternalTexture.DATASOURCE_CUBE = 7;
  23846. InternalTexture.DATASOURCE_CUBERAW = 8;
  23847. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  23848. InternalTexture.DATASOURCE_RAW3D = 10;
  23849. return InternalTexture;
  23850. }());
  23851. BABYLON.InternalTexture = InternalTexture;
  23852. })(BABYLON || (BABYLON = {}));
  23853. //# sourceMappingURL=babylon.internalTexture.js.map
  23854. var BABYLON;
  23855. (function (BABYLON) {
  23856. var BaseTexture = /** @class */ (function () {
  23857. function BaseTexture(scene) {
  23858. this._hasAlpha = false;
  23859. this.getAlphaFromRGB = false;
  23860. this.level = 1;
  23861. this.coordinatesIndex = 0;
  23862. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23863. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23864. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23865. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  23866. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  23867. this.isCube = false;
  23868. this.is3D = false;
  23869. this.gammaSpace = true;
  23870. this.invertZ = false;
  23871. this.lodLevelInAlpha = false;
  23872. this.lodGenerationOffset = 0.0;
  23873. this.lodGenerationScale = 0.8;
  23874. this.isRenderTarget = false;
  23875. this.animations = new Array();
  23876. /**
  23877. * An event triggered when the texture is disposed.
  23878. * @type {BABYLON.Observable}
  23879. */
  23880. this.onDisposeObservable = new BABYLON.Observable();
  23881. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23882. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  23883. if (this._scene) {
  23884. this._scene.textures.push(this);
  23885. }
  23886. this._uid = null;
  23887. }
  23888. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  23889. get: function () {
  23890. return this._hasAlpha;
  23891. },
  23892. set: function (value) {
  23893. if (this._hasAlpha === value) {
  23894. return;
  23895. }
  23896. this._hasAlpha = value;
  23897. if (this._scene) {
  23898. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23899. }
  23900. },
  23901. enumerable: true,
  23902. configurable: true
  23903. });
  23904. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  23905. get: function () {
  23906. return this._coordinatesMode;
  23907. },
  23908. set: function (value) {
  23909. if (this._coordinatesMode === value) {
  23910. return;
  23911. }
  23912. this._coordinatesMode = value;
  23913. if (this._scene) {
  23914. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23915. }
  23916. },
  23917. enumerable: true,
  23918. configurable: true
  23919. });
  23920. Object.defineProperty(BaseTexture.prototype, "uid", {
  23921. get: function () {
  23922. if (!this._uid) {
  23923. this._uid = BABYLON.Tools.RandomId();
  23924. }
  23925. return this._uid;
  23926. },
  23927. enumerable: true,
  23928. configurable: true
  23929. });
  23930. BaseTexture.prototype.toString = function () {
  23931. return this.name;
  23932. };
  23933. BaseTexture.prototype.getClassName = function () {
  23934. return "BaseTexture";
  23935. };
  23936. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23937. set: function (callback) {
  23938. if (this._onDisposeObserver) {
  23939. this.onDisposeObservable.remove(this._onDisposeObserver);
  23940. }
  23941. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23942. },
  23943. enumerable: true,
  23944. configurable: true
  23945. });
  23946. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  23947. get: function () {
  23948. return true;
  23949. },
  23950. enumerable: true,
  23951. configurable: true
  23952. });
  23953. BaseTexture.prototype.getScene = function () {
  23954. return this._scene;
  23955. };
  23956. BaseTexture.prototype.getTextureMatrix = function () {
  23957. return BABYLON.Matrix.IdentityReadOnly;
  23958. };
  23959. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23960. return BABYLON.Matrix.IdentityReadOnly;
  23961. };
  23962. BaseTexture.prototype.getInternalTexture = function () {
  23963. return this._texture;
  23964. };
  23965. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  23966. return !this.isBlocking || this.isReady();
  23967. };
  23968. BaseTexture.prototype.isReady = function () {
  23969. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23970. this.delayLoad();
  23971. return false;
  23972. }
  23973. if (this._texture) {
  23974. return this._texture.isReady;
  23975. }
  23976. return false;
  23977. };
  23978. BaseTexture.prototype.getSize = function () {
  23979. if (this._texture && this._texture.width) {
  23980. return new BABYLON.Size(this._texture.width, this._texture.height);
  23981. }
  23982. if (this._texture && this._texture._size) {
  23983. return new BABYLON.Size(this._texture._size, this._texture._size);
  23984. }
  23985. return BABYLON.Size.Zero();
  23986. };
  23987. BaseTexture.prototype.getBaseSize = function () {
  23988. if (!this.isReady() || !this._texture)
  23989. return BABYLON.Size.Zero();
  23990. if (this._texture._size) {
  23991. return new BABYLON.Size(this._texture._size, this._texture._size);
  23992. }
  23993. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  23994. };
  23995. BaseTexture.prototype.scale = function (ratio) {
  23996. };
  23997. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23998. get: function () {
  23999. return false;
  24000. },
  24001. enumerable: true,
  24002. configurable: true
  24003. });
  24004. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24005. if (!this._scene) {
  24006. return null;
  24007. }
  24008. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24009. for (var index = 0; index < texturesCache.length; index++) {
  24010. var texturesCacheEntry = texturesCache[index];
  24011. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  24012. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24013. texturesCacheEntry.incrementReferences();
  24014. return texturesCacheEntry;
  24015. }
  24016. }
  24017. }
  24018. return null;
  24019. };
  24020. BaseTexture.prototype._rebuild = function () {
  24021. };
  24022. BaseTexture.prototype.delayLoad = function () {
  24023. };
  24024. BaseTexture.prototype.clone = function () {
  24025. return null;
  24026. };
  24027. Object.defineProperty(BaseTexture.prototype, "textureType", {
  24028. get: function () {
  24029. if (!this._texture) {
  24030. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24031. }
  24032. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  24033. },
  24034. enumerable: true,
  24035. configurable: true
  24036. });
  24037. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  24038. get: function () {
  24039. if (!this._texture) {
  24040. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24041. }
  24042. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  24043. },
  24044. enumerable: true,
  24045. configurable: true
  24046. });
  24047. BaseTexture.prototype.readPixels = function (faceIndex) {
  24048. if (faceIndex === void 0) { faceIndex = 0; }
  24049. if (!this._texture) {
  24050. return null;
  24051. }
  24052. var size = this.getSize();
  24053. var scene = this.getScene();
  24054. if (!scene) {
  24055. return null;
  24056. }
  24057. var engine = scene.getEngine();
  24058. if (this._texture.isCube) {
  24059. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  24060. }
  24061. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  24062. };
  24063. BaseTexture.prototype.releaseInternalTexture = function () {
  24064. if (this._texture) {
  24065. this._texture.dispose();
  24066. this._texture = null;
  24067. }
  24068. };
  24069. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  24070. get: function () {
  24071. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  24072. return null;
  24073. }
  24074. if (!this._texture._sphericalPolynomial) {
  24075. this._texture._sphericalPolynomial =
  24076. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  24077. }
  24078. return this._texture._sphericalPolynomial;
  24079. },
  24080. set: function (value) {
  24081. if (this._texture) {
  24082. this._texture._sphericalPolynomial = value;
  24083. }
  24084. },
  24085. enumerable: true,
  24086. configurable: true
  24087. });
  24088. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  24089. get: function () {
  24090. if (this._texture) {
  24091. return this._texture._lodTextureHigh;
  24092. }
  24093. return null;
  24094. },
  24095. enumerable: true,
  24096. configurable: true
  24097. });
  24098. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  24099. get: function () {
  24100. if (this._texture) {
  24101. return this._texture._lodTextureMid;
  24102. }
  24103. return null;
  24104. },
  24105. enumerable: true,
  24106. configurable: true
  24107. });
  24108. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  24109. get: function () {
  24110. if (this._texture) {
  24111. return this._texture._lodTextureLow;
  24112. }
  24113. return null;
  24114. },
  24115. enumerable: true,
  24116. configurable: true
  24117. });
  24118. BaseTexture.prototype.dispose = function () {
  24119. if (!this._scene) {
  24120. return;
  24121. }
  24122. // Animations
  24123. this._scene.stopAnimation(this);
  24124. // Remove from scene
  24125. this._scene._removePendingData(this);
  24126. var index = this._scene.textures.indexOf(this);
  24127. if (index >= 0) {
  24128. this._scene.textures.splice(index, 1);
  24129. }
  24130. if (this._texture === undefined) {
  24131. return;
  24132. }
  24133. // Release
  24134. this.releaseInternalTexture();
  24135. // Callback
  24136. this.onDisposeObservable.notifyObservers(this);
  24137. this.onDisposeObservable.clear();
  24138. };
  24139. BaseTexture.prototype.serialize = function () {
  24140. if (!this.name) {
  24141. return null;
  24142. }
  24143. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24144. // Animations
  24145. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24146. return serializationObject;
  24147. };
  24148. BaseTexture.WhenAllReady = function (textures, callback) {
  24149. var numRemaining = textures.length;
  24150. if (numRemaining === 0) {
  24151. callback();
  24152. return;
  24153. }
  24154. var _loop_1 = function () {
  24155. texture = textures[i];
  24156. if (texture.isReady()) {
  24157. if (--numRemaining === 0) {
  24158. callback();
  24159. }
  24160. }
  24161. else {
  24162. onLoadObservable = texture.onLoadObservable;
  24163. var onLoadCallback_1 = function () {
  24164. onLoadObservable.removeCallback(onLoadCallback_1);
  24165. if (--numRemaining === 0) {
  24166. callback();
  24167. }
  24168. };
  24169. onLoadObservable.add(onLoadCallback_1);
  24170. }
  24171. };
  24172. var texture, onLoadObservable;
  24173. for (var i = 0; i < textures.length; i++) {
  24174. _loop_1();
  24175. }
  24176. };
  24177. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  24178. __decorate([
  24179. BABYLON.serialize()
  24180. ], BaseTexture.prototype, "name", void 0);
  24181. __decorate([
  24182. BABYLON.serialize("hasAlpha")
  24183. ], BaseTexture.prototype, "_hasAlpha", void 0);
  24184. __decorate([
  24185. BABYLON.serialize()
  24186. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24187. __decorate([
  24188. BABYLON.serialize()
  24189. ], BaseTexture.prototype, "level", void 0);
  24190. __decorate([
  24191. BABYLON.serialize()
  24192. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24193. __decorate([
  24194. BABYLON.serialize("coordinatesMode")
  24195. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  24196. __decorate([
  24197. BABYLON.serialize()
  24198. ], BaseTexture.prototype, "wrapU", void 0);
  24199. __decorate([
  24200. BABYLON.serialize()
  24201. ], BaseTexture.prototype, "wrapV", void 0);
  24202. __decorate([
  24203. BABYLON.serialize()
  24204. ], BaseTexture.prototype, "wrapR", void 0);
  24205. __decorate([
  24206. BABYLON.serialize()
  24207. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24208. __decorate([
  24209. BABYLON.serialize()
  24210. ], BaseTexture.prototype, "isCube", void 0);
  24211. __decorate([
  24212. BABYLON.serialize()
  24213. ], BaseTexture.prototype, "is3D", void 0);
  24214. __decorate([
  24215. BABYLON.serialize()
  24216. ], BaseTexture.prototype, "gammaSpace", void 0);
  24217. __decorate([
  24218. BABYLON.serialize()
  24219. ], BaseTexture.prototype, "invertZ", void 0);
  24220. __decorate([
  24221. BABYLON.serialize()
  24222. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  24223. __decorate([
  24224. BABYLON.serialize()
  24225. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  24226. __decorate([
  24227. BABYLON.serialize()
  24228. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  24229. __decorate([
  24230. BABYLON.serialize()
  24231. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24232. return BaseTexture;
  24233. }());
  24234. BABYLON.BaseTexture = BaseTexture;
  24235. })(BABYLON || (BABYLON = {}));
  24236. //# sourceMappingURL=babylon.baseTexture.js.map
  24237. var BABYLON;
  24238. (function (BABYLON) {
  24239. var Texture = /** @class */ (function (_super) {
  24240. __extends(Texture, _super);
  24241. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  24242. if (noMipmap === void 0) { noMipmap = false; }
  24243. if (invertY === void 0) { invertY = true; }
  24244. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24245. if (onLoad === void 0) { onLoad = null; }
  24246. if (onError === void 0) { onError = null; }
  24247. if (buffer === void 0) { buffer = null; }
  24248. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24249. var _this = _super.call(this, scene) || this;
  24250. _this.uOffset = 0;
  24251. _this.vOffset = 0;
  24252. _this.uScale = 1.0;
  24253. _this.vScale = 1.0;
  24254. _this.uAng = 0;
  24255. _this.vAng = 0;
  24256. _this.wAng = 0;
  24257. _this._isBlocking = true;
  24258. _this.name = url || "";
  24259. _this.url = url;
  24260. _this._noMipmap = noMipmap;
  24261. _this._invertY = invertY;
  24262. _this._samplingMode = samplingMode;
  24263. _this._buffer = buffer;
  24264. _this._deleteBuffer = deleteBuffer;
  24265. if (format) {
  24266. _this._format = format;
  24267. }
  24268. scene = _this.getScene();
  24269. if (!scene) {
  24270. return _this;
  24271. }
  24272. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  24273. var load = function () {
  24274. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  24275. _this.onLoadObservable.notifyObservers(_this);
  24276. }
  24277. if (onLoad) {
  24278. onLoad();
  24279. }
  24280. if (!_this.isBlocking && scene) {
  24281. scene.resetCachedMaterial();
  24282. }
  24283. };
  24284. if (!_this.url) {
  24285. _this._delayedOnLoad = load;
  24286. _this._delayedOnError = onError;
  24287. return _this;
  24288. }
  24289. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  24290. if (!_this._texture) {
  24291. if (!scene.useDelayedTextureLoading) {
  24292. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  24293. if (deleteBuffer) {
  24294. delete _this._buffer;
  24295. }
  24296. }
  24297. else {
  24298. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24299. _this._delayedOnLoad = load;
  24300. _this._delayedOnError = onError;
  24301. }
  24302. }
  24303. else {
  24304. if (_this._texture.isReady) {
  24305. BABYLON.Tools.SetImmediate(function () { return load(); });
  24306. }
  24307. else {
  24308. _this._texture.onLoadedObservable.add(load);
  24309. }
  24310. }
  24311. return _this;
  24312. }
  24313. Object.defineProperty(Texture.prototype, "noMipmap", {
  24314. get: function () {
  24315. return this._noMipmap;
  24316. },
  24317. enumerable: true,
  24318. configurable: true
  24319. });
  24320. Object.defineProperty(Texture.prototype, "isBlocking", {
  24321. get: function () {
  24322. return this._isBlocking;
  24323. },
  24324. set: function (value) {
  24325. this._isBlocking = value;
  24326. },
  24327. enumerable: true,
  24328. configurable: true
  24329. });
  24330. Object.defineProperty(Texture.prototype, "samplingMode", {
  24331. get: function () {
  24332. return this._samplingMode;
  24333. },
  24334. enumerable: true,
  24335. configurable: true
  24336. });
  24337. Texture.prototype.updateURL = function (url) {
  24338. this.url = url;
  24339. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24340. this.delayLoad();
  24341. };
  24342. Texture.prototype.delayLoad = function () {
  24343. var _this = this;
  24344. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24345. return;
  24346. }
  24347. var scene = this.getScene();
  24348. if (!scene) {
  24349. return;
  24350. }
  24351. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24352. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24353. if (!this._texture) {
  24354. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  24355. if (this._deleteBuffer) {
  24356. delete this._buffer;
  24357. }
  24358. }
  24359. else {
  24360. if (this._texture.isReady) {
  24361. BABYLON.Tools.SetImmediate(function () {
  24362. if (!_this._delayedOnLoad) {
  24363. return;
  24364. }
  24365. _this._delayedOnLoad();
  24366. });
  24367. }
  24368. else {
  24369. if (this._delayedOnLoad) {
  24370. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  24371. }
  24372. }
  24373. }
  24374. };
  24375. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24376. if (!this._texture) {
  24377. return;
  24378. }
  24379. var scene = this.getScene();
  24380. if (!scene) {
  24381. return;
  24382. }
  24383. this._samplingMode = samplingMode;
  24384. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24385. };
  24386. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24387. x *= this.uScale;
  24388. y *= this.vScale;
  24389. x -= 0.5 * this.uScale;
  24390. y -= 0.5 * this.vScale;
  24391. z -= 0.5;
  24392. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24393. t.x += 0.5 * this.uScale + this.uOffset;
  24394. t.y += 0.5 * this.vScale + this.vOffset;
  24395. t.z += 0.5;
  24396. };
  24397. Texture.prototype.getTextureMatrix = function () {
  24398. var _this = this;
  24399. if (this.uOffset === this._cachedUOffset &&
  24400. this.vOffset === this._cachedVOffset &&
  24401. this.uScale === this._cachedUScale &&
  24402. this.vScale === this._cachedVScale &&
  24403. this.uAng === this._cachedUAng &&
  24404. this.vAng === this._cachedVAng &&
  24405. this.wAng === this._cachedWAng) {
  24406. return this._cachedTextureMatrix;
  24407. }
  24408. this._cachedUOffset = this.uOffset;
  24409. this._cachedVOffset = this.vOffset;
  24410. this._cachedUScale = this.uScale;
  24411. this._cachedVScale = this.vScale;
  24412. this._cachedUAng = this.uAng;
  24413. this._cachedVAng = this.vAng;
  24414. this._cachedWAng = this.wAng;
  24415. if (!this._cachedTextureMatrix) {
  24416. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24417. this._rowGenerationMatrix = new BABYLON.Matrix();
  24418. this._t0 = BABYLON.Vector3.Zero();
  24419. this._t1 = BABYLON.Vector3.Zero();
  24420. this._t2 = BABYLON.Vector3.Zero();
  24421. }
  24422. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24423. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24424. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24425. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24426. this._t1.subtractInPlace(this._t0);
  24427. this._t2.subtractInPlace(this._t0);
  24428. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24429. this._cachedTextureMatrix.m[0] = this._t1.x;
  24430. this._cachedTextureMatrix.m[1] = this._t1.y;
  24431. this._cachedTextureMatrix.m[2] = this._t1.z;
  24432. this._cachedTextureMatrix.m[4] = this._t2.x;
  24433. this._cachedTextureMatrix.m[5] = this._t2.y;
  24434. this._cachedTextureMatrix.m[6] = this._t2.z;
  24435. this._cachedTextureMatrix.m[8] = this._t0.x;
  24436. this._cachedTextureMatrix.m[9] = this._t0.y;
  24437. this._cachedTextureMatrix.m[10] = this._t0.z;
  24438. var scene = this.getScene();
  24439. if (!scene) {
  24440. return this._cachedTextureMatrix;
  24441. }
  24442. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24443. return mat.hasTexture(_this);
  24444. });
  24445. return this._cachedTextureMatrix;
  24446. };
  24447. Texture.prototype.getReflectionTextureMatrix = function () {
  24448. var _this = this;
  24449. var scene = this.getScene();
  24450. if (!scene) {
  24451. return this._cachedTextureMatrix;
  24452. }
  24453. if (this.uOffset === this._cachedUOffset &&
  24454. this.vOffset === this._cachedVOffset &&
  24455. this.uScale === this._cachedUScale &&
  24456. this.vScale === this._cachedVScale &&
  24457. this.coordinatesMode === this._cachedCoordinatesMode) {
  24458. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  24459. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  24460. return this._cachedTextureMatrix;
  24461. }
  24462. }
  24463. else {
  24464. return this._cachedTextureMatrix;
  24465. }
  24466. }
  24467. if (!this._cachedTextureMatrix) {
  24468. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24469. }
  24470. if (!this._projectionModeMatrix) {
  24471. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24472. }
  24473. this._cachedUOffset = this.uOffset;
  24474. this._cachedVOffset = this.vOffset;
  24475. this._cachedUScale = this.uScale;
  24476. this._cachedVScale = this.vScale;
  24477. this._cachedCoordinatesMode = this.coordinatesMode;
  24478. switch (this.coordinatesMode) {
  24479. case Texture.PLANAR_MODE:
  24480. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24481. this._cachedTextureMatrix[0] = this.uScale;
  24482. this._cachedTextureMatrix[5] = this.vScale;
  24483. this._cachedTextureMatrix[12] = this.uOffset;
  24484. this._cachedTextureMatrix[13] = this.vOffset;
  24485. break;
  24486. case Texture.PROJECTION_MODE:
  24487. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24488. this._projectionModeMatrix.m[0] = 0.5;
  24489. this._projectionModeMatrix.m[5] = -0.5;
  24490. this._projectionModeMatrix.m[10] = 0.0;
  24491. this._projectionModeMatrix.m[12] = 0.5;
  24492. this._projectionModeMatrix.m[13] = 0.5;
  24493. this._projectionModeMatrix.m[14] = 1.0;
  24494. this._projectionModeMatrix.m[15] = 1.0;
  24495. var projectionMatrix = scene.getProjectionMatrix();
  24496. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  24497. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24498. break;
  24499. default:
  24500. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24501. break;
  24502. }
  24503. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  24504. return (mat.getActiveTextures().indexOf(_this) !== -1);
  24505. });
  24506. return this._cachedTextureMatrix;
  24507. };
  24508. Texture.prototype.clone = function () {
  24509. var _this = this;
  24510. return BABYLON.SerializationHelper.Clone(function () {
  24511. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24512. }, this);
  24513. };
  24514. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24515. get: function () {
  24516. if (!this._onLoadObservable) {
  24517. this._onLoadObservable = new BABYLON.Observable();
  24518. }
  24519. return this._onLoadObservable;
  24520. },
  24521. enumerable: true,
  24522. configurable: true
  24523. });
  24524. Texture.prototype.serialize = function () {
  24525. var serializationObject = _super.prototype.serialize.call(this);
  24526. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  24527. serializationObject.base64String = this._buffer;
  24528. serializationObject.name = serializationObject.name.replace("data:", "");
  24529. }
  24530. return serializationObject;
  24531. };
  24532. Texture.prototype.getClassName = function () {
  24533. return "Texture";
  24534. };
  24535. Texture.prototype.dispose = function () {
  24536. _super.prototype.dispose.call(this);
  24537. if (this.onLoadObservable) {
  24538. this.onLoadObservable.clear();
  24539. this._onLoadObservable = null;
  24540. }
  24541. this._delayedOnLoad = null;
  24542. this._delayedOnError = null;
  24543. };
  24544. // Statics
  24545. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24546. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24547. if (onLoad === void 0) { onLoad = null; }
  24548. if (onError === void 0) { onError = null; }
  24549. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24550. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  24551. };
  24552. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24553. if (parsedTexture.customType) {
  24554. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24555. // Update Sampling Mode
  24556. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  24557. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  24558. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  24559. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  24560. }
  24561. }
  24562. return parsedCustomTexture;
  24563. }
  24564. if (parsedTexture.isCube) {
  24565. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24566. }
  24567. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24568. return null;
  24569. }
  24570. var texture = BABYLON.SerializationHelper.Parse(function () {
  24571. var generateMipMaps = true;
  24572. if (parsedTexture.noMipmap) {
  24573. generateMipMaps = false;
  24574. }
  24575. if (parsedTexture.mirrorPlane) {
  24576. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24577. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24578. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24579. return mirrorTexture;
  24580. }
  24581. else if (parsedTexture.isRenderTarget) {
  24582. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  24583. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24584. return renderTargetTexture;
  24585. }
  24586. else {
  24587. var texture;
  24588. if (parsedTexture.base64String) {
  24589. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  24590. }
  24591. else {
  24592. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  24593. }
  24594. return texture;
  24595. }
  24596. }, parsedTexture, scene);
  24597. // Update Sampling Mode
  24598. if (parsedTexture.samplingMode) {
  24599. var sampling = parsedTexture.samplingMode;
  24600. if (texture._samplingMode !== sampling) {
  24601. texture.updateSamplingMode(sampling);
  24602. }
  24603. }
  24604. // Animations
  24605. if (parsedTexture.animations) {
  24606. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24607. var parsedAnimation = parsedTexture.animations[animationIndex];
  24608. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24609. }
  24610. }
  24611. return texture;
  24612. };
  24613. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  24614. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24615. if (noMipmap === void 0) { noMipmap = false; }
  24616. if (invertY === void 0) { invertY = true; }
  24617. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24618. if (onLoad === void 0) { onLoad = null; }
  24619. if (onError === void 0) { onError = null; }
  24620. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  24621. if (name.substr(0, 5) !== "data:") {
  24622. name = "data:" + name;
  24623. }
  24624. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  24625. };
  24626. // Constants
  24627. Texture.NEAREST_SAMPLINGMODE = 1;
  24628. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  24629. Texture.BILINEAR_SAMPLINGMODE = 2;
  24630. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  24631. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24632. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  24633. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  24634. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  24635. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  24636. Texture.NEAREST_LINEAR = 7;
  24637. Texture.NEAREST_NEAREST = 8;
  24638. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  24639. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  24640. Texture.LINEAR_LINEAR = 11;
  24641. Texture.LINEAR_NEAREST = 12;
  24642. Texture.EXPLICIT_MODE = 0;
  24643. Texture.SPHERICAL_MODE = 1;
  24644. Texture.PLANAR_MODE = 2;
  24645. Texture.CUBIC_MODE = 3;
  24646. Texture.PROJECTION_MODE = 4;
  24647. Texture.SKYBOX_MODE = 5;
  24648. Texture.INVCUBIC_MODE = 6;
  24649. Texture.EQUIRECTANGULAR_MODE = 7;
  24650. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24651. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  24652. Texture.CLAMP_ADDRESSMODE = 0;
  24653. Texture.WRAP_ADDRESSMODE = 1;
  24654. Texture.MIRROR_ADDRESSMODE = 2;
  24655. __decorate([
  24656. BABYLON.serialize()
  24657. ], Texture.prototype, "url", void 0);
  24658. __decorate([
  24659. BABYLON.serialize()
  24660. ], Texture.prototype, "uOffset", void 0);
  24661. __decorate([
  24662. BABYLON.serialize()
  24663. ], Texture.prototype, "vOffset", void 0);
  24664. __decorate([
  24665. BABYLON.serialize()
  24666. ], Texture.prototype, "uScale", void 0);
  24667. __decorate([
  24668. BABYLON.serialize()
  24669. ], Texture.prototype, "vScale", void 0);
  24670. __decorate([
  24671. BABYLON.serialize()
  24672. ], Texture.prototype, "uAng", void 0);
  24673. __decorate([
  24674. BABYLON.serialize()
  24675. ], Texture.prototype, "vAng", void 0);
  24676. __decorate([
  24677. BABYLON.serialize()
  24678. ], Texture.prototype, "wAng", void 0);
  24679. __decorate([
  24680. BABYLON.serialize()
  24681. ], Texture.prototype, "isBlocking", null);
  24682. return Texture;
  24683. }(BABYLON.BaseTexture));
  24684. BABYLON.Texture = Texture;
  24685. })(BABYLON || (BABYLON = {}));
  24686. //# sourceMappingURL=babylon.texture.js.map
  24687. var BABYLON;
  24688. (function (BABYLON) {
  24689. var _InstancesBatch = /** @class */ (function () {
  24690. function _InstancesBatch() {
  24691. this.mustReturn = false;
  24692. this.visibleInstances = new Array();
  24693. this.renderSelf = new Array();
  24694. }
  24695. return _InstancesBatch;
  24696. }());
  24697. BABYLON._InstancesBatch = _InstancesBatch;
  24698. var Mesh = /** @class */ (function (_super) {
  24699. __extends(Mesh, _super);
  24700. /**
  24701. * @constructor
  24702. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  24703. * @param {Scene} scene The scene to add this mesh to.
  24704. * @param {Node} parent The parent of this mesh, if it has one
  24705. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  24706. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  24707. * When false, achieved by calling a clone(), also passing False.
  24708. * This will make creation of children, recursive.
  24709. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  24710. */
  24711. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  24712. if (scene === void 0) { scene = null; }
  24713. if (parent === void 0) { parent = null; }
  24714. if (source === void 0) { source = null; }
  24715. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24716. var _this = _super.call(this, name, scene) || this;
  24717. // Events
  24718. /**
  24719. * An event triggered before rendering the mesh
  24720. * @type {BABYLON.Observable}
  24721. */
  24722. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24723. /**
  24724. * An event triggered after rendering the mesh
  24725. * @type {BABYLON.Observable}
  24726. */
  24727. _this.onAfterRenderObservable = new BABYLON.Observable();
  24728. /**
  24729. * An event triggered before drawing the mesh
  24730. * @type {BABYLON.Observable}
  24731. */
  24732. _this.onBeforeDrawObservable = new BABYLON.Observable();
  24733. // Members
  24734. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24735. _this.instances = new Array();
  24736. _this._LODLevels = new Array();
  24737. _this._visibleInstances = {};
  24738. _this._renderIdForInstances = new Array();
  24739. _this._batchCache = new _InstancesBatch();
  24740. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  24741. // Use by builder only to know what orientation were the mesh build in.
  24742. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  24743. _this.overrideMaterialSideOrientation = null;
  24744. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  24745. // Will be used to save a source mesh reference, If any
  24746. _this._source = null;
  24747. scene = _this.getScene();
  24748. if (source) {
  24749. // Source mesh
  24750. _this._source = source;
  24751. // Geometry
  24752. if (source._geometry) {
  24753. source._geometry.applyToMesh(_this);
  24754. }
  24755. // Deep copy
  24756. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  24757. // Metadata
  24758. if (source.metadata && source.metadata.clone) {
  24759. _this.metadata = source.metadata.clone();
  24760. }
  24761. else {
  24762. _this.metadata = source.metadata;
  24763. }
  24764. // Tags
  24765. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  24766. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  24767. }
  24768. // Parent
  24769. _this.parent = source.parent;
  24770. // Pivot
  24771. _this.setPivotMatrix(source.getPivotMatrix());
  24772. _this.id = name + "." + source.id;
  24773. // Material
  24774. _this.material = source.material;
  24775. var index;
  24776. if (!doNotCloneChildren) {
  24777. // Children
  24778. var directDescendants = source.getDescendants(true);
  24779. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  24780. var child = directDescendants[index_1];
  24781. if (child.clone) {
  24782. child.clone(name + "." + child.name, _this);
  24783. }
  24784. }
  24785. }
  24786. // Physics clone
  24787. var physicsEngine = _this.getScene().getPhysicsEngine();
  24788. if (clonePhysicsImpostor && physicsEngine) {
  24789. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  24790. if (impostor) {
  24791. _this.physicsImpostor = impostor.clone(_this);
  24792. }
  24793. }
  24794. // Particles
  24795. for (index = 0; index < scene.particleSystems.length; index++) {
  24796. var system = scene.particleSystems[index];
  24797. if (system.emitter === source) {
  24798. system.clone(system.name, _this);
  24799. }
  24800. }
  24801. _this.computeWorldMatrix(true);
  24802. }
  24803. // Parent
  24804. if (parent !== null) {
  24805. _this.parent = parent;
  24806. }
  24807. return _this;
  24808. }
  24809. Object.defineProperty(Mesh, "FRONTSIDE", {
  24810. /**
  24811. * Mesh side orientation : usually the external or front surface
  24812. */
  24813. get: function () {
  24814. return Mesh._FRONTSIDE;
  24815. },
  24816. enumerable: true,
  24817. configurable: true
  24818. });
  24819. Object.defineProperty(Mesh, "BACKSIDE", {
  24820. /**
  24821. * Mesh side orientation : usually the internal or back surface
  24822. */
  24823. get: function () {
  24824. return Mesh._BACKSIDE;
  24825. },
  24826. enumerable: true,
  24827. configurable: true
  24828. });
  24829. Object.defineProperty(Mesh, "DOUBLESIDE", {
  24830. /**
  24831. * Mesh side orientation : both internal and external or front and back surfaces
  24832. */
  24833. get: function () {
  24834. return Mesh._DOUBLESIDE;
  24835. },
  24836. enumerable: true,
  24837. configurable: true
  24838. });
  24839. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  24840. /**
  24841. * Mesh side orientation : by default, `FRONTSIDE`
  24842. */
  24843. get: function () {
  24844. return Mesh._DEFAULTSIDE;
  24845. },
  24846. enumerable: true,
  24847. configurable: true
  24848. });
  24849. Object.defineProperty(Mesh, "NO_CAP", {
  24850. /**
  24851. * Mesh cap setting : no cap
  24852. */
  24853. get: function () {
  24854. return Mesh._NO_CAP;
  24855. },
  24856. enumerable: true,
  24857. configurable: true
  24858. });
  24859. Object.defineProperty(Mesh, "CAP_START", {
  24860. /**
  24861. * Mesh cap setting : one cap at the beginning of the mesh
  24862. */
  24863. get: function () {
  24864. return Mesh._CAP_START;
  24865. },
  24866. enumerable: true,
  24867. configurable: true
  24868. });
  24869. Object.defineProperty(Mesh, "CAP_END", {
  24870. /**
  24871. * Mesh cap setting : one cap at the end of the mesh
  24872. */
  24873. get: function () {
  24874. return Mesh._CAP_END;
  24875. },
  24876. enumerable: true,
  24877. configurable: true
  24878. });
  24879. Object.defineProperty(Mesh, "CAP_ALL", {
  24880. /**
  24881. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  24882. */
  24883. get: function () {
  24884. return Mesh._CAP_ALL;
  24885. },
  24886. enumerable: true,
  24887. configurable: true
  24888. });
  24889. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  24890. set: function (callback) {
  24891. if (this._onBeforeDrawObserver) {
  24892. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  24893. }
  24894. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  24895. },
  24896. enumerable: true,
  24897. configurable: true
  24898. });
  24899. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  24900. get: function () {
  24901. return this._morphTargetManager;
  24902. },
  24903. set: function (value) {
  24904. if (this._morphTargetManager === value) {
  24905. return;
  24906. }
  24907. this._morphTargetManager = value;
  24908. this._syncGeometryWithMorphTargetManager();
  24909. },
  24910. enumerable: true,
  24911. configurable: true
  24912. });
  24913. Object.defineProperty(Mesh.prototype, "source", {
  24914. get: function () {
  24915. return this._source;
  24916. },
  24917. enumerable: true,
  24918. configurable: true
  24919. });
  24920. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  24921. get: function () {
  24922. return this._unIndexed;
  24923. },
  24924. set: function (value) {
  24925. if (this._unIndexed !== value) {
  24926. this._unIndexed = value;
  24927. this._markSubMeshesAsAttributesDirty();
  24928. }
  24929. },
  24930. enumerable: true,
  24931. configurable: true
  24932. });
  24933. // Methods
  24934. /**
  24935. * Returns the string "Mesh".
  24936. */
  24937. Mesh.prototype.getClassName = function () {
  24938. return "Mesh";
  24939. };
  24940. /**
  24941. * Returns a string.
  24942. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24943. */
  24944. Mesh.prototype.toString = function (fullDetails) {
  24945. var ret = _super.prototype.toString.call(this, fullDetails);
  24946. ret += ", n vertices: " + this.getTotalVertices();
  24947. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  24948. if (this.animations) {
  24949. for (var i = 0; i < this.animations.length; i++) {
  24950. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  24951. }
  24952. }
  24953. if (fullDetails) {
  24954. if (this._geometry) {
  24955. var ib = this.getIndices();
  24956. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24957. if (vb && ib) {
  24958. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  24959. }
  24960. }
  24961. else {
  24962. ret += ", flat shading: UNKNOWN";
  24963. }
  24964. }
  24965. return ret;
  24966. };
  24967. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  24968. /**
  24969. * True if the mesh has some Levels Of Details (LOD).
  24970. * Returns a boolean.
  24971. */
  24972. get: function () {
  24973. return this._LODLevels.length > 0;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. Mesh.prototype._sortLODLevels = function () {
  24979. this._LODLevels.sort(function (a, b) {
  24980. if (a.distance < b.distance) {
  24981. return 1;
  24982. }
  24983. if (a.distance > b.distance) {
  24984. return -1;
  24985. }
  24986. return 0;
  24987. });
  24988. };
  24989. /**
  24990. * Add a mesh as LOD level triggered at the given distance.
  24991. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  24992. * @param {number} distance The distance from the center of the object to show this level
  24993. * @param {Mesh} mesh The mesh to be added as LOD level
  24994. * @return {Mesh} This mesh (for chaining)
  24995. */
  24996. Mesh.prototype.addLODLevel = function (distance, mesh) {
  24997. if (mesh && mesh._masterMesh) {
  24998. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  24999. return this;
  25000. }
  25001. var level = new BABYLON.MeshLODLevel(distance, mesh);
  25002. this._LODLevels.push(level);
  25003. if (mesh) {
  25004. mesh._masterMesh = this;
  25005. }
  25006. this._sortLODLevels();
  25007. return this;
  25008. };
  25009. /**
  25010. * Returns the LOD level mesh at the passed distance or null if not found.
  25011. * It is related to the method `addLODLevel(distance, mesh)`.
  25012. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25013. * Returns an object Mesh or `null`.
  25014. */
  25015. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  25016. for (var index = 0; index < this._LODLevels.length; index++) {
  25017. var level = this._LODLevels[index];
  25018. if (level.distance === distance) {
  25019. return level.mesh;
  25020. }
  25021. }
  25022. return null;
  25023. };
  25024. /**
  25025. * Remove a mesh from the LOD array
  25026. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25027. * @param {Mesh} mesh The mesh to be removed.
  25028. * @return {Mesh} This mesh (for chaining)
  25029. */
  25030. Mesh.prototype.removeLODLevel = function (mesh) {
  25031. for (var index = 0; index < this._LODLevels.length; index++) {
  25032. if (this._LODLevels[index].mesh === mesh) {
  25033. this._LODLevels.splice(index, 1);
  25034. if (mesh) {
  25035. mesh._masterMesh = null;
  25036. }
  25037. }
  25038. }
  25039. this._sortLODLevels();
  25040. return this;
  25041. };
  25042. /**
  25043. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  25044. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  25045. */
  25046. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  25047. if (!this._LODLevels || this._LODLevels.length === 0) {
  25048. return this;
  25049. }
  25050. var bSphere;
  25051. if (boundingSphere) {
  25052. bSphere = boundingSphere;
  25053. }
  25054. else {
  25055. var boundingInfo = this.getBoundingInfo();
  25056. bSphere = boundingInfo.boundingSphere;
  25057. }
  25058. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  25059. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  25060. if (this.onLODLevelSelection) {
  25061. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  25062. }
  25063. return this;
  25064. }
  25065. for (var index = 0; index < this._LODLevels.length; index++) {
  25066. var level = this._LODLevels[index];
  25067. if (level.distance < distanceToCamera) {
  25068. if (level.mesh) {
  25069. level.mesh._preActivate();
  25070. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  25071. }
  25072. if (this.onLODLevelSelection) {
  25073. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  25074. }
  25075. return level.mesh;
  25076. }
  25077. }
  25078. if (this.onLODLevelSelection) {
  25079. this.onLODLevelSelection(distanceToCamera, this, this);
  25080. }
  25081. return this;
  25082. };
  25083. Object.defineProperty(Mesh.prototype, "geometry", {
  25084. /**
  25085. * Returns the mesh internal Geometry object.
  25086. */
  25087. get: function () {
  25088. return this._geometry;
  25089. },
  25090. enumerable: true,
  25091. configurable: true
  25092. });
  25093. /**
  25094. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  25095. */
  25096. Mesh.prototype.getTotalVertices = function () {
  25097. if (this._geometry === null || this._geometry === undefined) {
  25098. return 0;
  25099. }
  25100. return this._geometry.getTotalVertices();
  25101. };
  25102. /**
  25103. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  25104. * 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.
  25105. * You can force the copy with forceCopy === true
  25106. * Returns null if the mesh has no geometry or no vertex buffer.
  25107. * Possible `kind` values :
  25108. * - BABYLON.VertexBuffer.PositionKind
  25109. * - BABYLON.VertexBuffer.UVKind
  25110. * - BABYLON.VertexBuffer.UV2Kind
  25111. * - BABYLON.VertexBuffer.UV3Kind
  25112. * - BABYLON.VertexBuffer.UV4Kind
  25113. * - BABYLON.VertexBuffer.UV5Kind
  25114. * - BABYLON.VertexBuffer.UV6Kind
  25115. * - BABYLON.VertexBuffer.ColorKind
  25116. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25117. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25118. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25119. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25120. */
  25121. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  25122. if (!this._geometry) {
  25123. return null;
  25124. }
  25125. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  25126. };
  25127. /**
  25128. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  25129. * Returns `null` if the mesh has no geometry.
  25130. * Possible `kind` values :
  25131. * - BABYLON.VertexBuffer.PositionKind
  25132. * - BABYLON.VertexBuffer.UVKind
  25133. * - BABYLON.VertexBuffer.UV2Kind
  25134. * - BABYLON.VertexBuffer.UV3Kind
  25135. * - BABYLON.VertexBuffer.UV4Kind
  25136. * - BABYLON.VertexBuffer.UV5Kind
  25137. * - BABYLON.VertexBuffer.UV6Kind
  25138. * - BABYLON.VertexBuffer.ColorKind
  25139. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25140. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25141. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25142. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25143. */
  25144. Mesh.prototype.getVertexBuffer = function (kind) {
  25145. if (!this._geometry) {
  25146. return null;
  25147. }
  25148. return this._geometry.getVertexBuffer(kind);
  25149. };
  25150. /**
  25151. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  25152. * Possible `kind` values :
  25153. * - BABYLON.VertexBuffer.PositionKind
  25154. * - BABYLON.VertexBuffer.UVKind
  25155. * - BABYLON.VertexBuffer.UV2Kind
  25156. * - BABYLON.VertexBuffer.UV3Kind
  25157. * - BABYLON.VertexBuffer.UV4Kind
  25158. * - BABYLON.VertexBuffer.UV5Kind
  25159. * - BABYLON.VertexBuffer.UV6Kind
  25160. * - BABYLON.VertexBuffer.ColorKind
  25161. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25162. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25163. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25164. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25165. */
  25166. Mesh.prototype.isVerticesDataPresent = function (kind) {
  25167. if (!this._geometry) {
  25168. if (this._delayInfo) {
  25169. return this._delayInfo.indexOf(kind) !== -1;
  25170. }
  25171. return false;
  25172. }
  25173. return this._geometry.isVerticesDataPresent(kind);
  25174. };
  25175. /**
  25176. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  25177. * Possible `kind` values :
  25178. * - BABYLON.VertexBuffer.PositionKind
  25179. * - BABYLON.VertexBuffer.UVKind
  25180. * - BABYLON.VertexBuffer.UV2Kind
  25181. * - BABYLON.VertexBuffer.UV3Kind
  25182. * - BABYLON.VertexBuffer.UV4Kind
  25183. * - BABYLON.VertexBuffer.UV5Kind
  25184. * - BABYLON.VertexBuffer.UV6Kind
  25185. * - BABYLON.VertexBuffer.ColorKind
  25186. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25187. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25188. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25189. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25190. */
  25191. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  25192. if (!this._geometry) {
  25193. if (this._delayInfo) {
  25194. return this._delayInfo.indexOf(kind) !== -1;
  25195. }
  25196. return false;
  25197. }
  25198. return this._geometry.isVertexBufferUpdatable(kind);
  25199. };
  25200. /**
  25201. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  25202. * Possible `kind` values :
  25203. * - BABYLON.VertexBuffer.PositionKind
  25204. * - BABYLON.VertexBuffer.UVKind
  25205. * - BABYLON.VertexBuffer.UV2Kind
  25206. * - BABYLON.VertexBuffer.UV3Kind
  25207. * - BABYLON.VertexBuffer.UV4Kind
  25208. * - BABYLON.VertexBuffer.UV5Kind
  25209. * - BABYLON.VertexBuffer.UV6Kind
  25210. * - BABYLON.VertexBuffer.ColorKind
  25211. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25212. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25213. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25214. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25215. */
  25216. Mesh.prototype.getVerticesDataKinds = function () {
  25217. if (!this._geometry) {
  25218. var result = new Array();
  25219. if (this._delayInfo) {
  25220. this._delayInfo.forEach(function (kind, index, array) {
  25221. result.push(kind);
  25222. });
  25223. }
  25224. return result;
  25225. }
  25226. return this._geometry.getVerticesDataKinds();
  25227. };
  25228. /**
  25229. * Returns a positive integer : the total number of indices in this mesh geometry.
  25230. * Returns zero if the mesh has no geometry.
  25231. */
  25232. Mesh.prototype.getTotalIndices = function () {
  25233. if (!this._geometry) {
  25234. return 0;
  25235. }
  25236. return this._geometry.getTotalIndices();
  25237. };
  25238. /**
  25239. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  25240. * 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.
  25241. * Returns an empty array if the mesh has no geometry.
  25242. */
  25243. Mesh.prototype.getIndices = function (copyWhenShared) {
  25244. if (!this._geometry) {
  25245. return [];
  25246. }
  25247. return this._geometry.getIndices(copyWhenShared);
  25248. };
  25249. Object.defineProperty(Mesh.prototype, "isBlocked", {
  25250. get: function () {
  25251. return this._masterMesh !== null && this._masterMesh !== undefined;
  25252. },
  25253. enumerable: true,
  25254. configurable: true
  25255. });
  25256. /**
  25257. * Determine if the current mesh is ready to be rendered
  25258. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  25259. * @returns true if all associated assets are ready (material, textures, shaders)
  25260. */
  25261. Mesh.prototype.isReady = function (forceInstanceSupport) {
  25262. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  25263. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25264. return false;
  25265. }
  25266. if (!_super.prototype.isReady.call(this)) {
  25267. return false;
  25268. }
  25269. if (!this.subMeshes || this.subMeshes.length === 0) {
  25270. return true;
  25271. }
  25272. var engine = this.getEngine();
  25273. var scene = this.getScene();
  25274. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  25275. this.computeWorldMatrix();
  25276. var mat = this.material || scene.defaultMaterial;
  25277. if (mat) {
  25278. if (mat.storeEffectOnSubMeshes) {
  25279. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25280. var subMesh = _a[_i];
  25281. var effectiveMaterial = subMesh.getMaterial();
  25282. if (effectiveMaterial) {
  25283. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25284. return false;
  25285. }
  25286. }
  25287. }
  25288. }
  25289. else {
  25290. if (!mat.isReady(this, hardwareInstancedRendering)) {
  25291. return false;
  25292. }
  25293. }
  25294. }
  25295. // Shadows
  25296. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  25297. var light = _c[_b];
  25298. var generator = light.getShadowGenerator();
  25299. if (generator) {
  25300. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  25301. var subMesh = _e[_d];
  25302. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  25303. return false;
  25304. }
  25305. }
  25306. }
  25307. }
  25308. // LOD
  25309. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  25310. var lod = _g[_f];
  25311. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  25312. return false;
  25313. }
  25314. }
  25315. return true;
  25316. };
  25317. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  25318. /**
  25319. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  25320. * This property is pertinent only for updatable parametric shapes.
  25321. */
  25322. get: function () {
  25323. return this._areNormalsFrozen;
  25324. },
  25325. enumerable: true,
  25326. configurable: true
  25327. });
  25328. /**
  25329. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25330. * It has no effect at all on other shapes.
  25331. * It prevents the mesh normals from being recomputed on next `positions` array update.
  25332. * Returns the Mesh.
  25333. */
  25334. Mesh.prototype.freezeNormals = function () {
  25335. this._areNormalsFrozen = true;
  25336. return this;
  25337. };
  25338. /**
  25339. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  25340. * It has no effect at all on other shapes.
  25341. * It reactivates the mesh normals computation if it was previously frozen.
  25342. * Returns the Mesh.
  25343. */
  25344. Mesh.prototype.unfreezeNormals = function () {
  25345. this._areNormalsFrozen = false;
  25346. return this;
  25347. };
  25348. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  25349. /**
  25350. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  25351. */
  25352. set: function (count) {
  25353. this._overridenInstanceCount = count;
  25354. },
  25355. enumerable: true,
  25356. configurable: true
  25357. });
  25358. // Methods
  25359. Mesh.prototype._preActivate = function () {
  25360. var sceneRenderId = this.getScene().getRenderId();
  25361. if (this._preActivateId === sceneRenderId) {
  25362. return this;
  25363. }
  25364. this._preActivateId = sceneRenderId;
  25365. this._visibleInstances = null;
  25366. return this;
  25367. };
  25368. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  25369. if (this._visibleInstances) {
  25370. this._visibleInstances.intermediateDefaultRenderId = renderId;
  25371. }
  25372. return this;
  25373. };
  25374. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  25375. if (!this._visibleInstances) {
  25376. this._visibleInstances = {};
  25377. this._visibleInstances.defaultRenderId = renderId;
  25378. this._visibleInstances.selfDefaultRenderId = this._renderId;
  25379. }
  25380. if (!this._visibleInstances[renderId]) {
  25381. this._visibleInstances[renderId] = new Array();
  25382. }
  25383. this._visibleInstances[renderId].push(instance);
  25384. return this;
  25385. };
  25386. /**
  25387. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  25388. * This means the mesh underlying bounding box and sphere are recomputed.
  25389. * Returns the Mesh.
  25390. */
  25391. Mesh.prototype.refreshBoundingInfo = function () {
  25392. return this._refreshBoundingInfo(false);
  25393. };
  25394. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  25395. if (this._boundingInfo && this._boundingInfo.isLocked) {
  25396. return this;
  25397. }
  25398. var data = this._getPositionData(applySkeleton);
  25399. if (data) {
  25400. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  25401. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25402. }
  25403. if (this.subMeshes) {
  25404. for (var index = 0; index < this.subMeshes.length; index++) {
  25405. this.subMeshes[index].refreshBoundingInfo();
  25406. }
  25407. }
  25408. this._updateBoundingInfo();
  25409. return this;
  25410. };
  25411. Mesh.prototype._getPositionData = function (applySkeleton) {
  25412. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25413. if (data && applySkeleton && this.skeleton) {
  25414. data = data.slice();
  25415. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  25416. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  25417. if (matricesWeightsData && matricesIndicesData) {
  25418. var needExtras = this.numBoneInfluencers > 4;
  25419. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  25420. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  25421. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  25422. var tempVector = BABYLON.Tmp.Vector3[0];
  25423. var finalMatrix = BABYLON.Tmp.Matrix[0];
  25424. var tempMatrix = BABYLON.Tmp.Matrix[1];
  25425. var matWeightIdx = 0;
  25426. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  25427. finalMatrix.reset();
  25428. var inf;
  25429. var weight;
  25430. for (inf = 0; inf < 4; inf++) {
  25431. weight = matricesWeightsData[matWeightIdx + inf];
  25432. if (weight <= 0)
  25433. break;
  25434. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25435. finalMatrix.addToSelf(tempMatrix);
  25436. }
  25437. if (needExtras) {
  25438. for (inf = 0; inf < 4; inf++) {
  25439. weight = matricesWeightsExtraData[matWeightIdx + inf];
  25440. if (weight <= 0)
  25441. break;
  25442. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  25443. finalMatrix.addToSelf(tempMatrix);
  25444. }
  25445. }
  25446. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  25447. tempVector.toArray(data, index);
  25448. }
  25449. }
  25450. }
  25451. return data;
  25452. };
  25453. Mesh.prototype._createGlobalSubMesh = function (force) {
  25454. var totalVertices = this.getTotalVertices();
  25455. if (!totalVertices || !this.getIndices()) {
  25456. return null;
  25457. }
  25458. // Check if we need to recreate the submeshes
  25459. if (this.subMeshes && this.subMeshes.length > 0) {
  25460. var ib = this.getIndices();
  25461. if (!ib) {
  25462. return null;
  25463. }
  25464. var totalIndices = ib.length;
  25465. var needToRecreate = false;
  25466. if (force) {
  25467. needToRecreate = true;
  25468. }
  25469. else {
  25470. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  25471. var submesh = _a[_i];
  25472. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  25473. needToRecreate = true;
  25474. break;
  25475. }
  25476. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  25477. needToRecreate = true;
  25478. break;
  25479. }
  25480. }
  25481. }
  25482. if (!needToRecreate) {
  25483. return this.subMeshes[0];
  25484. }
  25485. }
  25486. this.releaseSubMeshes();
  25487. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  25488. };
  25489. Mesh.prototype.subdivide = function (count) {
  25490. if (count < 1) {
  25491. return;
  25492. }
  25493. var totalIndices = this.getTotalIndices();
  25494. var subdivisionSize = (totalIndices / count) | 0;
  25495. var offset = 0;
  25496. // Ensure that subdivisionSize is a multiple of 3
  25497. while (subdivisionSize % 3 !== 0) {
  25498. subdivisionSize++;
  25499. }
  25500. this.releaseSubMeshes();
  25501. for (var index = 0; index < count; index++) {
  25502. if (offset >= totalIndices) {
  25503. break;
  25504. }
  25505. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  25506. offset += subdivisionSize;
  25507. }
  25508. this.synchronizeInstances();
  25509. };
  25510. /**
  25511. * Sets the vertex data of the mesh geometry for the requested `kind`.
  25512. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  25513. * The `data` are either a numeric array either a Float32Array.
  25514. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  25515. * 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).
  25516. * Note that a new underlying VertexBuffer object is created each call.
  25517. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  25518. *
  25519. * Possible `kind` values :
  25520. * - BABYLON.VertexBuffer.PositionKind
  25521. * - BABYLON.VertexBuffer.UVKind
  25522. * - BABYLON.VertexBuffer.UV2Kind
  25523. * - BABYLON.VertexBuffer.UV3Kind
  25524. * - BABYLON.VertexBuffer.UV4Kind
  25525. * - BABYLON.VertexBuffer.UV5Kind
  25526. * - BABYLON.VertexBuffer.UV6Kind
  25527. * - BABYLON.VertexBuffer.ColorKind
  25528. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25529. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25530. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25531. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25532. *
  25533. * Returns the Mesh.
  25534. */
  25535. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25536. if (updatable === void 0) { updatable = false; }
  25537. if (!this._geometry) {
  25538. var vertexData = new BABYLON.VertexData();
  25539. vertexData.set(data, kind);
  25540. var scene = this.getScene();
  25541. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25542. }
  25543. else {
  25544. this._geometry.setVerticesData(kind, data, updatable, stride);
  25545. }
  25546. return this;
  25547. };
  25548. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  25549. if (updatable === void 0) { updatable = true; }
  25550. var vb = this.getVertexBuffer(kind);
  25551. if (!vb || vb.isUpdatable() === updatable) {
  25552. return;
  25553. }
  25554. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  25555. };
  25556. /**
  25557. * Sets the mesh VertexBuffer.
  25558. * Returns the Mesh.
  25559. */
  25560. Mesh.prototype.setVerticesBuffer = function (buffer) {
  25561. if (!this._geometry) {
  25562. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  25563. }
  25564. this._geometry.setVerticesBuffer(buffer);
  25565. return this;
  25566. };
  25567. /**
  25568. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  25569. * If the mesh has no geometry, it is simply returned as it is.
  25570. * The `data` are either a numeric array either a Float32Array.
  25571. * No new underlying VertexBuffer object is created.
  25572. * 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.
  25573. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  25574. *
  25575. * Possible `kind` values :
  25576. * - BABYLON.VertexBuffer.PositionKind
  25577. * - BABYLON.VertexBuffer.UVKind
  25578. * - BABYLON.VertexBuffer.UV2Kind
  25579. * - BABYLON.VertexBuffer.UV3Kind
  25580. * - BABYLON.VertexBuffer.UV4Kind
  25581. * - BABYLON.VertexBuffer.UV5Kind
  25582. * - BABYLON.VertexBuffer.UV6Kind
  25583. * - BABYLON.VertexBuffer.ColorKind
  25584. * - BABYLON.VertexBuffer.MatricesIndicesKind
  25585. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  25586. * - BABYLON.VertexBuffer.MatricesWeightsKind
  25587. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  25588. *
  25589. * Returns the Mesh.
  25590. */
  25591. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  25592. if (!this._geometry) {
  25593. return this;
  25594. }
  25595. if (!makeItUnique) {
  25596. this._geometry.updateVerticesData(kind, data, updateExtends);
  25597. }
  25598. else {
  25599. this.makeGeometryUnique();
  25600. this.updateVerticesData(kind, data, updateExtends, false);
  25601. }
  25602. return this;
  25603. };
  25604. /**
  25605. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  25606. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  25607. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  25608. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  25609. * Returns the Mesh.
  25610. */
  25611. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  25612. if (computeNormals === void 0) { computeNormals = true; }
  25613. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25614. if (!positions) {
  25615. return this;
  25616. }
  25617. positionFunction(positions);
  25618. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  25619. if (computeNormals) {
  25620. var indices = this.getIndices();
  25621. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25622. if (!normals) {
  25623. return this;
  25624. }
  25625. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  25626. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  25627. }
  25628. return this;
  25629. };
  25630. /**
  25631. * Creates a un-shared specific occurence of the geometry for the mesh.
  25632. * Returns the Mesh.
  25633. */
  25634. Mesh.prototype.makeGeometryUnique = function () {
  25635. if (!this._geometry) {
  25636. return this;
  25637. }
  25638. var oldGeometry = this._geometry;
  25639. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  25640. oldGeometry.releaseForMesh(this, true);
  25641. geometry.applyToMesh(this);
  25642. return this;
  25643. };
  25644. /**
  25645. * Sets the mesh indices.
  25646. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  25647. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  25648. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  25649. * This method creates a new index buffer each call.
  25650. * Returns the Mesh.
  25651. */
  25652. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  25653. if (totalVertices === void 0) { totalVertices = null; }
  25654. if (updatable === void 0) { updatable = false; }
  25655. if (!this._geometry) {
  25656. var vertexData = new BABYLON.VertexData();
  25657. vertexData.indices = indices;
  25658. var scene = this.getScene();
  25659. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  25660. }
  25661. else {
  25662. this._geometry.setIndices(indices, totalVertices, updatable);
  25663. }
  25664. return this;
  25665. };
  25666. /**
  25667. * Update the current index buffer
  25668. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  25669. * Returns the Mesh.
  25670. */
  25671. Mesh.prototype.updateIndices = function (indices, offset) {
  25672. if (!this._geometry) {
  25673. return this;
  25674. }
  25675. this._geometry.updateIndices(indices, offset);
  25676. return this;
  25677. };
  25678. /**
  25679. * Invert the geometry to move from a right handed system to a left handed one.
  25680. * Returns the Mesh.
  25681. */
  25682. Mesh.prototype.toLeftHanded = function () {
  25683. if (!this._geometry) {
  25684. return this;
  25685. }
  25686. this._geometry.toLeftHanded();
  25687. return this;
  25688. };
  25689. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  25690. if (!this._geometry) {
  25691. return this;
  25692. }
  25693. var engine = this.getScene().getEngine();
  25694. // Wireframe
  25695. var indexToBind;
  25696. if (this._unIndexed) {
  25697. indexToBind = null;
  25698. }
  25699. else {
  25700. switch (fillMode) {
  25701. case BABYLON.Material.PointFillMode:
  25702. indexToBind = null;
  25703. break;
  25704. case BABYLON.Material.WireFrameFillMode:
  25705. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  25706. break;
  25707. default:
  25708. case BABYLON.Material.TriangleFillMode:
  25709. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  25710. break;
  25711. }
  25712. }
  25713. // VBOs
  25714. this._geometry._bind(effect, indexToBind);
  25715. return this;
  25716. };
  25717. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  25718. if (alternate === void 0) { alternate = false; }
  25719. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25720. return this;
  25721. }
  25722. this.onBeforeDrawObservable.notifyObservers(this);
  25723. var scene = this.getScene();
  25724. var engine = scene.getEngine();
  25725. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  25726. // or triangles as points
  25727. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  25728. }
  25729. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  25730. // Triangles as wireframe
  25731. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  25732. }
  25733. else {
  25734. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  25735. }
  25736. if (scene._isAlternateRenderingEnabled && !alternate) {
  25737. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  25738. if (!effect || !scene.activeCamera) {
  25739. return this;
  25740. }
  25741. scene._switchToAlternateCameraConfiguration(true);
  25742. this._effectiveMaterial.bindView(effect);
  25743. this._effectiveMaterial.bindViewProjection(effect);
  25744. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  25745. this._draw(subMesh, fillMode, instancesCount, true);
  25746. engine.setViewport(scene.activeCamera.viewport);
  25747. scene._switchToAlternateCameraConfiguration(false);
  25748. this._effectiveMaterial.bindView(effect);
  25749. this._effectiveMaterial.bindViewProjection(effect);
  25750. }
  25751. return this;
  25752. };
  25753. /**
  25754. * Registers for this mesh a javascript function called just before the rendering process.
  25755. * This function is passed the current mesh.
  25756. * Return the Mesh.
  25757. */
  25758. Mesh.prototype.registerBeforeRender = function (func) {
  25759. this.onBeforeRenderObservable.add(func);
  25760. return this;
  25761. };
  25762. /**
  25763. * Disposes a previously registered javascript function called before the rendering.
  25764. * This function is passed the current mesh.
  25765. * Returns the Mesh.
  25766. */
  25767. Mesh.prototype.unregisterBeforeRender = function (func) {
  25768. this.onBeforeRenderObservable.removeCallback(func);
  25769. return this;
  25770. };
  25771. /**
  25772. * Registers for this mesh a javascript function called just after the rendering is complete.
  25773. * This function is passed the current mesh.
  25774. * Returns the Mesh.
  25775. */
  25776. Mesh.prototype.registerAfterRender = function (func) {
  25777. this.onAfterRenderObservable.add(func);
  25778. return this;
  25779. };
  25780. /**
  25781. * Disposes a previously registered javascript function called after the rendering.
  25782. * This function is passed the current mesh.
  25783. * Return the Mesh.
  25784. */
  25785. Mesh.prototype.unregisterAfterRender = function (func) {
  25786. this.onAfterRenderObservable.removeCallback(func);
  25787. return this;
  25788. };
  25789. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  25790. var scene = this.getScene();
  25791. this._batchCache.mustReturn = false;
  25792. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  25793. this._batchCache.visibleInstances[subMeshId] = null;
  25794. if (this._visibleInstances) {
  25795. var currentRenderId = scene.getRenderId();
  25796. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  25797. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  25798. var selfRenderId = this._renderId;
  25799. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  25800. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  25801. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  25802. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  25803. }
  25804. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  25805. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  25806. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  25807. this._batchCache.mustReturn = true;
  25808. return this._batchCache;
  25809. }
  25810. if (currentRenderId !== selfRenderId) {
  25811. this._batchCache.renderSelf[subMeshId] = false;
  25812. }
  25813. }
  25814. this._renderIdForInstances[subMeshId] = currentRenderId;
  25815. }
  25816. return this._batchCache;
  25817. };
  25818. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  25819. var visibleInstances = batch.visibleInstances[subMesh._id];
  25820. if (!visibleInstances) {
  25821. return this;
  25822. }
  25823. var matricesCount = visibleInstances.length + 1;
  25824. var bufferSize = matricesCount * 16 * 4;
  25825. var currentInstancesBufferSize = this._instancesBufferSize;
  25826. var instancesBuffer = this._instancesBuffer;
  25827. while (this._instancesBufferSize < bufferSize) {
  25828. this._instancesBufferSize *= 2;
  25829. }
  25830. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  25831. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  25832. }
  25833. var offset = 0;
  25834. var instancesCount = 0;
  25835. var world = this.getWorldMatrix();
  25836. if (batch.renderSelf[subMesh._id]) {
  25837. world.copyToArray(this._instancesData, offset);
  25838. offset += 16;
  25839. instancesCount++;
  25840. }
  25841. if (visibleInstances) {
  25842. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  25843. var instance = visibleInstances[instanceIndex];
  25844. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  25845. offset += 16;
  25846. instancesCount++;
  25847. }
  25848. }
  25849. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  25850. if (instancesBuffer) {
  25851. instancesBuffer.dispose();
  25852. }
  25853. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  25854. this._instancesBuffer = instancesBuffer;
  25855. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  25856. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  25857. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  25858. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  25859. }
  25860. else {
  25861. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  25862. }
  25863. this._bind(subMesh, effect, fillMode);
  25864. this._draw(subMesh, fillMode, instancesCount);
  25865. engine.unbindInstanceAttributes();
  25866. return this;
  25867. };
  25868. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  25869. var scene = this.getScene();
  25870. var engine = scene.getEngine();
  25871. if (hardwareInstancedRendering) {
  25872. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  25873. }
  25874. else {
  25875. if (batch.renderSelf[subMesh._id]) {
  25876. // Draw
  25877. if (onBeforeDraw) {
  25878. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  25879. }
  25880. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  25881. }
  25882. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  25883. if (visibleInstancesForSubMesh) {
  25884. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  25885. var instance = visibleInstancesForSubMesh[instanceIndex];
  25886. // World
  25887. var world = instance.getWorldMatrix();
  25888. if (onBeforeDraw) {
  25889. onBeforeDraw(true, world, effectiveMaterial);
  25890. }
  25891. // Draw
  25892. this._draw(subMesh, fillMode);
  25893. }
  25894. }
  25895. }
  25896. return this;
  25897. };
  25898. /**
  25899. * Triggers the draw call for the mesh.
  25900. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  25901. * Returns the Mesh.
  25902. */
  25903. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  25904. this.checkOcclusionQuery();
  25905. if (this._isOccluded) {
  25906. return this;
  25907. }
  25908. var scene = this.getScene();
  25909. // Managing instances
  25910. var batch = this._getInstancesRenderList(subMesh._id);
  25911. if (batch.mustReturn) {
  25912. return this;
  25913. }
  25914. // Checking geometry state
  25915. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25916. return this;
  25917. }
  25918. this.onBeforeRenderObservable.notifyObservers(this);
  25919. var engine = scene.getEngine();
  25920. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25921. // Material
  25922. var material = subMesh.getMaterial();
  25923. if (!material) {
  25924. return this;
  25925. }
  25926. this._effectiveMaterial = material;
  25927. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25928. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  25929. return this;
  25930. }
  25931. }
  25932. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  25933. return this;
  25934. }
  25935. // Alpha mode
  25936. if (enableAlphaMode) {
  25937. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  25938. }
  25939. // Outline - step 1
  25940. var savedDepthWrite = engine.getDepthWrite();
  25941. if (this.renderOutline) {
  25942. engine.setDepthWrite(false);
  25943. scene.getOutlineRenderer().render(subMesh, batch);
  25944. engine.setDepthWrite(savedDepthWrite);
  25945. }
  25946. var effect;
  25947. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25948. effect = subMesh.effect;
  25949. }
  25950. else {
  25951. effect = this._effectiveMaterial.getEffect();
  25952. }
  25953. if (!effect) {
  25954. return this;
  25955. }
  25956. var sideOrientation = this.overrideMaterialSideOrientation;
  25957. if (sideOrientation == null) {
  25958. sideOrientation = this._effectiveMaterial.sideOrientation;
  25959. if (this._getWorldMatrixDeterminant() < 0) {
  25960. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  25961. }
  25962. }
  25963. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  25964. if (this._effectiveMaterial.forceDepthWrite) {
  25965. engine.setDepthWrite(true);
  25966. }
  25967. // Bind
  25968. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  25969. if (!hardwareInstancedRendering) {
  25970. this._bind(subMesh, effect, fillMode);
  25971. }
  25972. var world = this.getWorldMatrix();
  25973. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  25974. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  25975. }
  25976. else {
  25977. this._effectiveMaterial.bind(world, this);
  25978. }
  25979. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  25980. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  25981. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25982. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  25983. }
  25984. // Draw
  25985. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  25986. // Unbind
  25987. this._effectiveMaterial.unbind();
  25988. // Outline - step 2
  25989. if (this.renderOutline && savedDepthWrite) {
  25990. engine.setDepthWrite(true);
  25991. engine.setColorWrite(false);
  25992. scene.getOutlineRenderer().render(subMesh, batch);
  25993. engine.setColorWrite(true);
  25994. }
  25995. // Overlay
  25996. if (this.renderOverlay) {
  25997. var currentMode = engine.getAlphaMode();
  25998. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  25999. scene.getOutlineRenderer().render(subMesh, batch, true);
  26000. engine.setAlphaMode(currentMode);
  26001. }
  26002. this.onAfterRenderObservable.notifyObservers(this);
  26003. return this;
  26004. };
  26005. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  26006. if (isInstance && effectiveMaterial) {
  26007. effectiveMaterial.bindOnlyWorldMatrix(world);
  26008. }
  26009. };
  26010. /**
  26011. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  26012. */
  26013. Mesh.prototype.getEmittedParticleSystems = function () {
  26014. var results = new Array();
  26015. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26016. var particleSystem = this.getScene().particleSystems[index];
  26017. if (particleSystem.emitter === this) {
  26018. results.push(particleSystem);
  26019. }
  26020. }
  26021. return results;
  26022. };
  26023. /**
  26024. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  26025. */
  26026. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  26027. var results = new Array();
  26028. var descendants = this.getDescendants();
  26029. descendants.push(this);
  26030. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  26031. var particleSystem = this.getScene().particleSystems[index];
  26032. var emitter = particleSystem.emitter;
  26033. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  26034. results.push(particleSystem);
  26035. }
  26036. }
  26037. return results;
  26038. };
  26039. Mesh.prototype._checkDelayState = function () {
  26040. var scene = this.getScene();
  26041. if (this._geometry) {
  26042. this._geometry.load(scene);
  26043. }
  26044. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26045. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  26046. this._queueLoad(scene);
  26047. }
  26048. return this;
  26049. };
  26050. Mesh.prototype._queueLoad = function (scene) {
  26051. var _this = this;
  26052. scene._addPendingData(this);
  26053. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  26054. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  26055. if (data instanceof ArrayBuffer) {
  26056. _this._delayLoadingFunction(data, _this);
  26057. }
  26058. else {
  26059. _this._delayLoadingFunction(JSON.parse(data), _this);
  26060. }
  26061. _this.instances.forEach(function (instance) {
  26062. instance._syncSubMeshes();
  26063. });
  26064. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26065. scene._removePendingData(_this);
  26066. }, function () { }, scene.database, getBinaryData);
  26067. return this;
  26068. };
  26069. /**
  26070. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  26071. */
  26072. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  26073. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26074. return false;
  26075. }
  26076. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  26077. return false;
  26078. }
  26079. this._checkDelayState();
  26080. return true;
  26081. };
  26082. /**
  26083. * Sets the mesh material by the material or multiMaterial `id` property.
  26084. * The material `id` is a string identifying the material or the multiMaterial.
  26085. * This method returns the Mesh.
  26086. */
  26087. Mesh.prototype.setMaterialByID = function (id) {
  26088. var materials = this.getScene().materials;
  26089. var index;
  26090. for (index = materials.length - 1; index > -1; index--) {
  26091. if (materials[index].id === id) {
  26092. this.material = materials[index];
  26093. return this;
  26094. }
  26095. }
  26096. // Multi
  26097. var multiMaterials = this.getScene().multiMaterials;
  26098. for (index = multiMaterials.length - 1; index > -1; index--) {
  26099. if (multiMaterials[index].id === id) {
  26100. this.material = multiMaterials[index];
  26101. return this;
  26102. }
  26103. }
  26104. return this;
  26105. };
  26106. /**
  26107. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  26108. */
  26109. Mesh.prototype.getAnimatables = function () {
  26110. var results = new Array();
  26111. if (this.material) {
  26112. results.push(this.material);
  26113. }
  26114. if (this.skeleton) {
  26115. results.push(this.skeleton);
  26116. }
  26117. return results;
  26118. };
  26119. /**
  26120. * Modifies the mesh geometry according to the passed transformation matrix.
  26121. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  26122. * The mesh normals are modified accordingly the same transformation.
  26123. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  26124. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26125. * Returns the Mesh.
  26126. */
  26127. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  26128. // Position
  26129. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26130. return this;
  26131. }
  26132. var submeshes = this.subMeshes.splice(0);
  26133. this._resetPointsArrayCache();
  26134. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26135. var temp = new Array();
  26136. var index;
  26137. for (index = 0; index < data.length; index += 3) {
  26138. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  26139. }
  26140. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  26141. // Normals
  26142. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26143. return this;
  26144. }
  26145. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26146. temp = [];
  26147. for (index = 0; index < data.length; index += 3) {
  26148. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  26149. }
  26150. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  26151. // flip faces?
  26152. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  26153. this.flipFaces();
  26154. }
  26155. // Restore submeshes
  26156. this.releaseSubMeshes();
  26157. this.subMeshes = submeshes;
  26158. return this;
  26159. };
  26160. /**
  26161. * Modifies the mesh geometry according to its own current World Matrix.
  26162. * The mesh World Matrix is then reset.
  26163. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  26164. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  26165. * Note that, under the hood, this method sets a new VertexBuffer each call.
  26166. * Returns the Mesh.
  26167. */
  26168. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  26169. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  26170. this.scaling.copyFromFloats(1, 1, 1);
  26171. this.position.copyFromFloats(0, 0, 0);
  26172. this.rotation.copyFromFloats(0, 0, 0);
  26173. //only if quaternion is already set
  26174. if (this.rotationQuaternion) {
  26175. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  26176. }
  26177. this._worldMatrix = BABYLON.Matrix.Identity();
  26178. return this;
  26179. };
  26180. Object.defineProperty(Mesh.prototype, "_positions", {
  26181. // Cache
  26182. get: function () {
  26183. if (this._geometry) {
  26184. return this._geometry._positions;
  26185. }
  26186. return null;
  26187. },
  26188. enumerable: true,
  26189. configurable: true
  26190. });
  26191. Mesh.prototype._resetPointsArrayCache = function () {
  26192. if (this._geometry) {
  26193. this._geometry._resetPointsArrayCache();
  26194. }
  26195. return this;
  26196. };
  26197. Mesh.prototype._generatePointsArray = function () {
  26198. if (this._geometry) {
  26199. return this._geometry._generatePointsArray();
  26200. }
  26201. return false;
  26202. };
  26203. /**
  26204. * Returns a new Mesh object generated from the current mesh properties.
  26205. * This method must not get confused with createInstance().
  26206. * The parameter `name` is a string, the name given to the new mesh.
  26207. * The optional parameter `newParent` can be any Node object (default `null`).
  26208. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  26209. * 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.
  26210. */
  26211. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  26212. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26213. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  26214. };
  26215. /**
  26216. * Disposes the Mesh.
  26217. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  26218. * Returns nothing.
  26219. */
  26220. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  26221. var _this = this;
  26222. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  26223. this.morphTargetManager = null;
  26224. if (this._geometry) {
  26225. this._geometry.releaseForMesh(this, true);
  26226. }
  26227. // Sources
  26228. var meshes = this.getScene().meshes;
  26229. meshes.forEach(function (abstractMesh) {
  26230. var mesh = abstractMesh;
  26231. if (mesh._source && mesh._source === _this) {
  26232. mesh._source = null;
  26233. }
  26234. });
  26235. this._source = null;
  26236. // Instances
  26237. if (this._instancesBuffer) {
  26238. this._instancesBuffer.dispose();
  26239. this._instancesBuffer = null;
  26240. }
  26241. while (this.instances.length) {
  26242. this.instances[0].dispose();
  26243. }
  26244. // Highlight layers.
  26245. var highlightLayers = this.getScene().highlightLayers;
  26246. for (var i = 0; i < highlightLayers.length; i++) {
  26247. var highlightLayer = highlightLayers[i];
  26248. if (highlightLayer) {
  26249. highlightLayer.removeMesh(this);
  26250. highlightLayer.removeExcludedMesh(this);
  26251. }
  26252. }
  26253. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  26254. };
  26255. /**
  26256. * Modifies the mesh geometry according to a displacement map.
  26257. * 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.
  26258. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26259. * This method returns nothing.
  26260. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  26261. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26262. * 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.
  26263. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26264. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26265. *
  26266. * Returns the Mesh.
  26267. */
  26268. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  26269. var _this = this;
  26270. var scene = this.getScene();
  26271. var onload = function (img) {
  26272. // Getting height map data
  26273. var canvas = document.createElement("canvas");
  26274. var context = canvas.getContext("2d");
  26275. var heightMapWidth = img.width;
  26276. var heightMapHeight = img.height;
  26277. canvas.width = heightMapWidth;
  26278. canvas.height = heightMapHeight;
  26279. context.drawImage(img, 0, 0);
  26280. // Create VertexData from map data
  26281. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  26282. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  26283. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  26284. //execute success callback, if set
  26285. if (onSuccess) {
  26286. onSuccess(_this);
  26287. }
  26288. };
  26289. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  26290. return this;
  26291. };
  26292. /**
  26293. * Modifies the mesh geometry according to a displacementMap buffer.
  26294. * 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.
  26295. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  26296. * This method returns nothing.
  26297. * 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.
  26298. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  26299. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  26300. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  26301. * The parameter `uvScale` is an optional vector2 used to scale UV.
  26302. *
  26303. * Returns the Mesh.
  26304. */
  26305. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  26306. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  26307. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  26308. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26309. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  26310. return this;
  26311. }
  26312. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26313. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26314. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26315. var position = BABYLON.Vector3.Zero();
  26316. var normal = BABYLON.Vector3.Zero();
  26317. var uv = BABYLON.Vector2.Zero();
  26318. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  26319. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  26320. for (var index = 0; index < positions.length; index += 3) {
  26321. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  26322. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  26323. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  26324. // Compute height
  26325. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  26326. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  26327. var pos = (u + v * heightMapWidth) * 4;
  26328. var r = buffer[pos] / 255.0;
  26329. var g = buffer[pos + 1] / 255.0;
  26330. var b = buffer[pos + 2] / 255.0;
  26331. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  26332. normal.normalize();
  26333. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  26334. position = position.add(normal);
  26335. position.toArray(positions, index);
  26336. }
  26337. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  26338. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  26339. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  26340. return this;
  26341. };
  26342. /**
  26343. * Modify the mesh to get a flat shading rendering.
  26344. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  26345. * This method returns the Mesh.
  26346. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  26347. */
  26348. Mesh.prototype.convertToFlatShadedMesh = function () {
  26349. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  26350. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26351. var kinds = this.getVerticesDataKinds();
  26352. var vbs = {};
  26353. var data = {};
  26354. var newdata = {};
  26355. var updatableNormals = false;
  26356. var kindIndex;
  26357. var kind;
  26358. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26359. kind = kinds[kindIndex];
  26360. var vertexBuffer = this.getVertexBuffer(kind);
  26361. if (kind === BABYLON.VertexBuffer.NormalKind) {
  26362. updatableNormals = vertexBuffer.isUpdatable();
  26363. kinds.splice(kindIndex, 1);
  26364. kindIndex--;
  26365. continue;
  26366. }
  26367. vbs[kind] = vertexBuffer;
  26368. data[kind] = vbs[kind].getData();
  26369. newdata[kind] = [];
  26370. }
  26371. // Save previous submeshes
  26372. var previousSubmeshes = this.subMeshes.slice(0);
  26373. var indices = this.getIndices();
  26374. var totalIndices = this.getTotalIndices();
  26375. // Generating unique vertices per face
  26376. var index;
  26377. for (index = 0; index < totalIndices; index++) {
  26378. var vertexIndex = indices[index];
  26379. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26380. kind = kinds[kindIndex];
  26381. var stride = vbs[kind].getStrideSize();
  26382. for (var offset = 0; offset < stride; offset++) {
  26383. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26384. }
  26385. }
  26386. }
  26387. // Updating faces & normal
  26388. var normals = [];
  26389. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  26390. for (index = 0; index < totalIndices; index += 3) {
  26391. indices[index] = index;
  26392. indices[index + 1] = index + 1;
  26393. indices[index + 2] = index + 2;
  26394. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  26395. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  26396. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  26397. var p1p2 = p1.subtract(p2);
  26398. var p3p2 = p3.subtract(p2);
  26399. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  26400. // Store same normals for every vertex
  26401. for (var localIndex = 0; localIndex < 3; localIndex++) {
  26402. normals.push(normal.x);
  26403. normals.push(normal.y);
  26404. normals.push(normal.z);
  26405. }
  26406. }
  26407. this.setIndices(indices);
  26408. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  26409. // Updating vertex buffers
  26410. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26411. kind = kinds[kindIndex];
  26412. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26413. }
  26414. // Updating submeshes
  26415. this.releaseSubMeshes();
  26416. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26417. var previousOne = previousSubmeshes[submeshIndex];
  26418. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26419. }
  26420. this.synchronizeInstances();
  26421. return this;
  26422. };
  26423. /**
  26424. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  26425. * In other words, more vertices, no more indices and a single bigger VBO.
  26426. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  26427. * Returns the Mesh.
  26428. */
  26429. Mesh.prototype.convertToUnIndexedMesh = function () {
  26430. /// <summary>Remove indices by unfolding faces into buffers</summary>
  26431. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  26432. var kinds = this.getVerticesDataKinds();
  26433. var vbs = {};
  26434. var data = {};
  26435. var newdata = {};
  26436. var kindIndex;
  26437. var kind;
  26438. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26439. kind = kinds[kindIndex];
  26440. var vertexBuffer = this.getVertexBuffer(kind);
  26441. vbs[kind] = vertexBuffer;
  26442. data[kind] = vbs[kind].getData();
  26443. newdata[kind] = [];
  26444. }
  26445. // Save previous submeshes
  26446. var previousSubmeshes = this.subMeshes.slice(0);
  26447. var indices = this.getIndices();
  26448. var totalIndices = this.getTotalIndices();
  26449. // Generating unique vertices per face
  26450. var index;
  26451. for (index = 0; index < totalIndices; index++) {
  26452. var vertexIndex = indices[index];
  26453. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26454. kind = kinds[kindIndex];
  26455. var stride = vbs[kind].getStrideSize();
  26456. for (var offset = 0; offset < stride; offset++) {
  26457. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  26458. }
  26459. }
  26460. }
  26461. // Updating indices
  26462. for (index = 0; index < totalIndices; index += 3) {
  26463. indices[index] = index;
  26464. indices[index + 1] = index + 1;
  26465. indices[index + 2] = index + 2;
  26466. }
  26467. this.setIndices(indices);
  26468. // Updating vertex buffers
  26469. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  26470. kind = kinds[kindIndex];
  26471. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  26472. }
  26473. // Updating submeshes
  26474. this.releaseSubMeshes();
  26475. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  26476. var previousOne = previousSubmeshes[submeshIndex];
  26477. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  26478. }
  26479. this._unIndexed = true;
  26480. this.synchronizeInstances();
  26481. return this;
  26482. };
  26483. /**
  26484. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  26485. * This method returns the Mesh.
  26486. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  26487. */
  26488. Mesh.prototype.flipFaces = function (flipNormals) {
  26489. if (flipNormals === void 0) { flipNormals = false; }
  26490. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  26491. var i;
  26492. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  26493. for (i = 0; i < vertex_data.normals.length; i++) {
  26494. vertex_data.normals[i] *= -1;
  26495. }
  26496. }
  26497. if (vertex_data.indices) {
  26498. var temp;
  26499. for (i = 0; i < vertex_data.indices.length; i += 3) {
  26500. // reassign indices
  26501. temp = vertex_data.indices[i + 1];
  26502. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  26503. vertex_data.indices[i + 2] = temp;
  26504. }
  26505. }
  26506. vertex_data.applyToMesh(this);
  26507. return this;
  26508. };
  26509. // Instances
  26510. /**
  26511. * Creates a new InstancedMesh object from the mesh model.
  26512. * An instance shares the same properties and the same material than its model.
  26513. * Only these properties of each instance can then be set individually :
  26514. * - position
  26515. * - rotation
  26516. * - rotationQuaternion
  26517. * - setPivotMatrix
  26518. * - scaling
  26519. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  26520. * Warning : this method is not supported for Line mesh and LineSystem
  26521. */
  26522. Mesh.prototype.createInstance = function (name) {
  26523. return new BABYLON.InstancedMesh(name, this);
  26524. };
  26525. /**
  26526. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  26527. * After this call, all the mesh instances have the same submeshes than the current mesh.
  26528. * This method returns the Mesh.
  26529. */
  26530. Mesh.prototype.synchronizeInstances = function () {
  26531. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  26532. var instance = this.instances[instanceIndex];
  26533. instance._syncSubMeshes();
  26534. }
  26535. return this;
  26536. };
  26537. /**
  26538. * Simplify the mesh according to the given array of settings.
  26539. * Function will return immediately and will simplify async. It returns the Mesh.
  26540. * @param settings a collection of simplification settings.
  26541. * @param parallelProcessing should all levels calculate parallel or one after the other.
  26542. * @param type the type of simplification to run.
  26543. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  26544. */
  26545. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  26546. if (parallelProcessing === void 0) { parallelProcessing = true; }
  26547. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  26548. this.getScene().simplificationQueue.addTask({
  26549. settings: settings,
  26550. parallelProcessing: parallelProcessing,
  26551. mesh: this,
  26552. simplificationType: simplificationType,
  26553. successCallback: successCallback
  26554. });
  26555. return this;
  26556. };
  26557. /**
  26558. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  26559. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  26560. * This should be used together with the simplification to avoid disappearing triangles.
  26561. * Returns the Mesh.
  26562. * @param successCallback an optional success callback to be called after the optimization finished.
  26563. */
  26564. Mesh.prototype.optimizeIndices = function (successCallback) {
  26565. var _this = this;
  26566. var indices = this.getIndices();
  26567. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26568. if (!positions || !indices) {
  26569. return this;
  26570. }
  26571. var vectorPositions = new Array();
  26572. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  26573. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  26574. }
  26575. var dupes = new Array();
  26576. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  26577. var realPos = vectorPositions.length - 1 - iteration;
  26578. var testedPosition = vectorPositions[realPos];
  26579. for (var j = 0; j < realPos; ++j) {
  26580. var againstPosition = vectorPositions[j];
  26581. if (testedPosition.equals(againstPosition)) {
  26582. dupes[realPos] = j;
  26583. break;
  26584. }
  26585. }
  26586. }, function () {
  26587. for (var i = 0; i < indices.length; ++i) {
  26588. indices[i] = dupes[indices[i]] || indices[i];
  26589. }
  26590. //indices are now reordered
  26591. var originalSubMeshes = _this.subMeshes.slice(0);
  26592. _this.setIndices(indices);
  26593. _this.subMeshes = originalSubMeshes;
  26594. if (successCallback) {
  26595. successCallback(_this);
  26596. }
  26597. });
  26598. return this;
  26599. };
  26600. Mesh.prototype.serialize = function (serializationObject) {
  26601. serializationObject.name = this.name;
  26602. serializationObject.id = this.id;
  26603. serializationObject.type = this.getClassName();
  26604. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  26605. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26606. }
  26607. serializationObject.position = this.position.asArray();
  26608. if (this.rotationQuaternion) {
  26609. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  26610. }
  26611. else if (this.rotation) {
  26612. serializationObject.rotation = this.rotation.asArray();
  26613. }
  26614. serializationObject.scaling = this.scaling.asArray();
  26615. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  26616. serializationObject.isEnabled = this.isEnabled(false);
  26617. serializationObject.isVisible = this.isVisible;
  26618. serializationObject.infiniteDistance = this.infiniteDistance;
  26619. serializationObject.pickable = this.isPickable;
  26620. serializationObject.receiveShadows = this.receiveShadows;
  26621. serializationObject.billboardMode = this.billboardMode;
  26622. serializationObject.visibility = this.visibility;
  26623. serializationObject.checkCollisions = this.checkCollisions;
  26624. serializationObject.isBlocker = this.isBlocker;
  26625. // Parent
  26626. if (this.parent) {
  26627. serializationObject.parentId = this.parent.id;
  26628. }
  26629. // Geometry
  26630. serializationObject.isUnIndexed = this.isUnIndexed;
  26631. var geometry = this._geometry;
  26632. if (geometry) {
  26633. var geometryId = geometry.id;
  26634. serializationObject.geometryId = geometryId;
  26635. // SubMeshes
  26636. serializationObject.subMeshes = [];
  26637. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  26638. var subMesh = this.subMeshes[subIndex];
  26639. serializationObject.subMeshes.push({
  26640. materialIndex: subMesh.materialIndex,
  26641. verticesStart: subMesh.verticesStart,
  26642. verticesCount: subMesh.verticesCount,
  26643. indexStart: subMesh.indexStart,
  26644. indexCount: subMesh.indexCount
  26645. });
  26646. }
  26647. }
  26648. // Material
  26649. if (this.material) {
  26650. serializationObject.materialId = this.material.id;
  26651. }
  26652. else {
  26653. this.material = null;
  26654. }
  26655. // Morph targets
  26656. if (this.morphTargetManager) {
  26657. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  26658. }
  26659. // Skeleton
  26660. if (this.skeleton) {
  26661. serializationObject.skeletonId = this.skeleton.id;
  26662. }
  26663. // Physics
  26664. //TODO implement correct serialization for physics impostors.
  26665. var impostor = this.getPhysicsImpostor();
  26666. if (impostor) {
  26667. serializationObject.physicsMass = impostor.getParam("mass");
  26668. serializationObject.physicsFriction = impostor.getParam("friction");
  26669. serializationObject.physicsRestitution = impostor.getParam("mass");
  26670. serializationObject.physicsImpostor = impostor.type;
  26671. }
  26672. // Metadata
  26673. if (this.metadata) {
  26674. serializationObject.metadata = this.metadata;
  26675. }
  26676. // Instances
  26677. serializationObject.instances = [];
  26678. for (var index = 0; index < this.instances.length; index++) {
  26679. var instance = this.instances[index];
  26680. var serializationInstance = {
  26681. name: instance.name,
  26682. id: instance.id,
  26683. position: instance.position.asArray(),
  26684. scaling: instance.scaling.asArray()
  26685. };
  26686. if (instance.rotationQuaternion) {
  26687. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  26688. }
  26689. else if (instance.rotation) {
  26690. serializationInstance.rotation = instance.rotation.asArray();
  26691. }
  26692. serializationObject.instances.push(serializationInstance);
  26693. // Animations
  26694. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  26695. serializationInstance.ranges = instance.serializeAnimationRanges();
  26696. }
  26697. //
  26698. // Animations
  26699. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26700. serializationObject.ranges = this.serializeAnimationRanges();
  26701. // Layer mask
  26702. serializationObject.layerMask = this.layerMask;
  26703. // Alpha
  26704. serializationObject.alphaIndex = this.alphaIndex;
  26705. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  26706. // Overlay
  26707. serializationObject.overlayAlpha = this.overlayAlpha;
  26708. serializationObject.overlayColor = this.overlayColor.asArray();
  26709. serializationObject.renderOverlay = this.renderOverlay;
  26710. // Fog
  26711. serializationObject.applyFog = this.applyFog;
  26712. // Action Manager
  26713. if (this.actionManager) {
  26714. serializationObject.actions = this.actionManager.serialize(this.name);
  26715. }
  26716. };
  26717. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  26718. if (!this.geometry) {
  26719. return;
  26720. }
  26721. this._markSubMeshesAsAttributesDirty();
  26722. var morphTargetManager = this._morphTargetManager;
  26723. if (morphTargetManager && morphTargetManager.vertexCount) {
  26724. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  26725. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  26726. this.morphTargetManager = null;
  26727. return;
  26728. }
  26729. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  26730. var morphTarget = morphTargetManager.getActiveTarget(index);
  26731. var positions = morphTarget.getPositions();
  26732. if (!positions) {
  26733. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  26734. return;
  26735. }
  26736. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  26737. var normals = morphTarget.getNormals();
  26738. if (normals) {
  26739. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  26740. }
  26741. var tangents = morphTarget.getTangents();
  26742. if (tangents) {
  26743. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  26744. }
  26745. }
  26746. }
  26747. else {
  26748. var index = 0;
  26749. // Positions
  26750. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  26751. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  26752. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  26753. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  26754. }
  26755. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  26756. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  26757. }
  26758. index++;
  26759. }
  26760. }
  26761. };
  26762. // Statics
  26763. /**
  26764. * Returns a new Mesh object parsed from the source provided.
  26765. * The parameter `parsedMesh` is the source.
  26766. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  26767. */
  26768. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  26769. var mesh;
  26770. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  26771. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  26772. }
  26773. else {
  26774. mesh = new Mesh(parsedMesh.name, scene);
  26775. }
  26776. mesh.id = parsedMesh.id;
  26777. if (BABYLON.Tags) {
  26778. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  26779. }
  26780. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  26781. if (parsedMesh.metadata !== undefined) {
  26782. mesh.metadata = parsedMesh.metadata;
  26783. }
  26784. if (parsedMesh.rotationQuaternion) {
  26785. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  26786. }
  26787. else if (parsedMesh.rotation) {
  26788. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  26789. }
  26790. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  26791. if (parsedMesh.localMatrix) {
  26792. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  26793. }
  26794. else if (parsedMesh.pivotMatrix) {
  26795. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  26796. }
  26797. mesh.setEnabled(parsedMesh.isEnabled);
  26798. mesh.isVisible = parsedMesh.isVisible;
  26799. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  26800. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  26801. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  26802. if (parsedMesh.applyFog !== undefined) {
  26803. mesh.applyFog = parsedMesh.applyFog;
  26804. }
  26805. if (parsedMesh.pickable !== undefined) {
  26806. mesh.isPickable = parsedMesh.pickable;
  26807. }
  26808. if (parsedMesh.alphaIndex !== undefined) {
  26809. mesh.alphaIndex = parsedMesh.alphaIndex;
  26810. }
  26811. mesh.receiveShadows = parsedMesh.receiveShadows;
  26812. mesh.billboardMode = parsedMesh.billboardMode;
  26813. if (parsedMesh.visibility !== undefined) {
  26814. mesh.visibility = parsedMesh.visibility;
  26815. }
  26816. mesh.checkCollisions = parsedMesh.checkCollisions;
  26817. if (parsedMesh.isBlocker !== undefined) {
  26818. mesh.isBlocker = parsedMesh.isBlocker;
  26819. }
  26820. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  26821. // freezeWorldMatrix
  26822. if (parsedMesh.freezeWorldMatrix) {
  26823. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  26824. }
  26825. // Parent
  26826. if (parsedMesh.parentId) {
  26827. mesh._waitingParentId = parsedMesh.parentId;
  26828. }
  26829. // Actions
  26830. if (parsedMesh.actions !== undefined) {
  26831. mesh._waitingActions = parsedMesh.actions;
  26832. }
  26833. // Overlay
  26834. if (parsedMesh.overlayAlpha !== undefined) {
  26835. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  26836. }
  26837. if (parsedMesh.overlayColor !== undefined) {
  26838. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  26839. }
  26840. if (parsedMesh.renderOverlay !== undefined) {
  26841. mesh.renderOverlay = parsedMesh.renderOverlay;
  26842. }
  26843. // Geometry
  26844. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  26845. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  26846. if (parsedMesh.delayLoadingFile) {
  26847. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26848. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  26849. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  26850. if (parsedMesh._binaryInfo) {
  26851. mesh._binaryInfo = parsedMesh._binaryInfo;
  26852. }
  26853. mesh._delayInfo = [];
  26854. if (parsedMesh.hasUVs) {
  26855. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  26856. }
  26857. if (parsedMesh.hasUVs2) {
  26858. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  26859. }
  26860. if (parsedMesh.hasUVs3) {
  26861. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  26862. }
  26863. if (parsedMesh.hasUVs4) {
  26864. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  26865. }
  26866. if (parsedMesh.hasUVs5) {
  26867. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  26868. }
  26869. if (parsedMesh.hasUVs6) {
  26870. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  26871. }
  26872. if (parsedMesh.hasColors) {
  26873. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  26874. }
  26875. if (parsedMesh.hasMatricesIndices) {
  26876. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26877. }
  26878. if (parsedMesh.hasMatricesWeights) {
  26879. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26880. }
  26881. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  26882. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  26883. mesh._checkDelayState();
  26884. }
  26885. }
  26886. else {
  26887. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  26888. }
  26889. // Material
  26890. if (parsedMesh.materialId) {
  26891. mesh.setMaterialByID(parsedMesh.materialId);
  26892. }
  26893. else {
  26894. mesh.material = null;
  26895. }
  26896. // Morph targets
  26897. if (parsedMesh.morphTargetManagerId > -1) {
  26898. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  26899. }
  26900. // Skeleton
  26901. if (parsedMesh.skeletonId > -1) {
  26902. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  26903. if (parsedMesh.numBoneInfluencers) {
  26904. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  26905. }
  26906. }
  26907. // Animations
  26908. if (parsedMesh.animations) {
  26909. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26910. var parsedAnimation = parsedMesh.animations[animationIndex];
  26911. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26912. }
  26913. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  26914. }
  26915. if (parsedMesh.autoAnimate) {
  26916. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  26917. }
  26918. // Layer Mask
  26919. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  26920. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  26921. }
  26922. else {
  26923. mesh.layerMask = 0x0FFFFFFF;
  26924. }
  26925. // Physics
  26926. if (parsedMesh.physicsImpostor) {
  26927. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  26928. mass: parsedMesh.physicsMass,
  26929. friction: parsedMesh.physicsFriction,
  26930. restitution: parsedMesh.physicsRestitution
  26931. }, scene);
  26932. }
  26933. // Instances
  26934. if (parsedMesh.instances) {
  26935. for (var index = 0; index < parsedMesh.instances.length; index++) {
  26936. var parsedInstance = parsedMesh.instances[index];
  26937. var instance = mesh.createInstance(parsedInstance.name);
  26938. if (parsedInstance.id) {
  26939. instance.id = parsedInstance.id;
  26940. }
  26941. if (BABYLON.Tags) {
  26942. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  26943. }
  26944. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  26945. if (parsedInstance.parentId) {
  26946. instance._waitingParentId = parsedInstance.parentId;
  26947. }
  26948. if (parsedInstance.rotationQuaternion) {
  26949. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  26950. }
  26951. else if (parsedInstance.rotation) {
  26952. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  26953. }
  26954. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  26955. instance.checkCollisions = mesh.checkCollisions;
  26956. if (parsedMesh.animations) {
  26957. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  26958. parsedAnimation = parsedMesh.animations[animationIndex];
  26959. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26960. }
  26961. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  26962. }
  26963. }
  26964. }
  26965. return mesh;
  26966. };
  26967. /**
  26968. * Creates a ribbon mesh.
  26969. * Please consider using the same method from the MeshBuilder class instead.
  26970. * 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.
  26971. *
  26972. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  26973. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  26974. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  26975. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  26976. * 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.
  26977. * 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.
  26978. * 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
  26979. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26980. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26981. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26982. */
  26983. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  26984. if (closeArray === void 0) { closeArray = false; }
  26985. if (updatable === void 0) { updatable = false; }
  26986. return BABYLON.MeshBuilder.CreateRibbon(name, {
  26987. pathArray: pathArray,
  26988. closeArray: closeArray,
  26989. closePath: closePath,
  26990. offset: offset,
  26991. updatable: updatable,
  26992. sideOrientation: sideOrientation,
  26993. instance: instance
  26994. }, scene);
  26995. };
  26996. /**
  26997. * Creates a plane polygonal mesh. By default, this is a disc.
  26998. * Please consider using the same method from the MeshBuilder class instead.
  26999. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  27000. * 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.
  27001. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27002. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27003. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27004. */
  27005. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  27006. if (scene === void 0) { scene = null; }
  27007. var options = {
  27008. radius: radius,
  27009. tessellation: tessellation,
  27010. sideOrientation: sideOrientation,
  27011. updatable: updatable
  27012. };
  27013. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  27014. };
  27015. /**
  27016. * Creates a box mesh.
  27017. * Please consider using the same method from the MeshBuilder class instead.
  27018. * The parameter `size` sets the size (float) of each box side (default 1).
  27019. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27020. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27021. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27022. */
  27023. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  27024. if (scene === void 0) { scene = null; }
  27025. var options = {
  27026. size: size,
  27027. sideOrientation: sideOrientation,
  27028. updatable: updatable
  27029. };
  27030. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  27031. };
  27032. /**
  27033. * Creates a sphere mesh.
  27034. * Please consider using the same method from the MeshBuilder class instead.
  27035. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  27036. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  27037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27038. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27040. */
  27041. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  27042. var options = {
  27043. segments: segments,
  27044. diameterX: diameter,
  27045. diameterY: diameter,
  27046. diameterZ: diameter,
  27047. sideOrientation: sideOrientation,
  27048. updatable: updatable
  27049. };
  27050. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  27051. };
  27052. /**
  27053. * Creates a cylinder or a cone mesh.
  27054. * Please consider using the same method from the MeshBuilder class instead.
  27055. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  27056. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  27057. * 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.
  27058. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  27059. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  27060. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27061. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27063. */
  27064. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  27065. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  27066. if (scene !== undefined) {
  27067. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  27068. updatable = scene;
  27069. }
  27070. scene = subdivisions;
  27071. subdivisions = 1;
  27072. }
  27073. var options = {
  27074. height: height,
  27075. diameterTop: diameterTop,
  27076. diameterBottom: diameterBottom,
  27077. tessellation: tessellation,
  27078. subdivisions: subdivisions,
  27079. sideOrientation: sideOrientation,
  27080. updatable: updatable
  27081. };
  27082. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  27083. };
  27084. // Torus (Code from SharpDX.org)
  27085. /**
  27086. * Creates a torus mesh.
  27087. * Please consider using the same method from the MeshBuilder class instead.
  27088. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  27089. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  27090. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  27091. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27092. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27093. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27094. */
  27095. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  27096. var options = {
  27097. diameter: diameter,
  27098. thickness: thickness,
  27099. tessellation: tessellation,
  27100. sideOrientation: sideOrientation,
  27101. updatable: updatable
  27102. };
  27103. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  27104. };
  27105. /**
  27106. * Creates a torus knot mesh.
  27107. * Please consider using the same method from the MeshBuilder class instead.
  27108. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  27109. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  27110. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  27111. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  27112. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27113. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27114. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27115. */
  27116. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  27117. var options = {
  27118. radius: radius,
  27119. tube: tube,
  27120. radialSegments: radialSegments,
  27121. tubularSegments: tubularSegments,
  27122. p: p,
  27123. q: q,
  27124. sideOrientation: sideOrientation,
  27125. updatable: updatable
  27126. };
  27127. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  27128. };
  27129. /**
  27130. * Creates a line mesh.
  27131. * Please consider using the same method from the MeshBuilder class instead.
  27132. * 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.
  27133. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27134. * The parameter `points` is an array successive Vector3.
  27135. * 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
  27136. * When updating an instance, remember that only point positions can change, not the number of points.
  27137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27138. */
  27139. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  27140. if (scene === void 0) { scene = null; }
  27141. if (updatable === void 0) { updatable = false; }
  27142. if (instance === void 0) { instance = null; }
  27143. var options = {
  27144. points: points,
  27145. updatable: updatable,
  27146. instance: instance
  27147. };
  27148. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  27149. };
  27150. /**
  27151. * Creates a dashed line mesh.
  27152. * Please consider using the same method from the MeshBuilder class instead.
  27153. * 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.
  27154. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  27155. * The parameter `points` is an array successive Vector3.
  27156. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  27157. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  27158. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  27159. * 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
  27160. * When updating an instance, remember that only point positions can change, not the number of points.
  27161. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27162. */
  27163. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  27164. if (scene === void 0) { scene = null; }
  27165. var options = {
  27166. points: points,
  27167. dashSize: dashSize,
  27168. gapSize: gapSize,
  27169. dashNb: dashNb,
  27170. updatable: updatable,
  27171. instance: instance
  27172. };
  27173. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  27174. };
  27175. /**
  27176. * Creates a polygon mesh.
  27177. * Please consider using the same method from the MeshBuilder class instead.
  27178. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  27179. * 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.
  27180. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27181. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27182. * Remember you can only change the shape positions, not their number when updating a polygon.
  27183. */
  27184. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  27185. var options = {
  27186. shape: shape,
  27187. holes: holes,
  27188. updatable: updatable,
  27189. sideOrientation: sideOrientation
  27190. };
  27191. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  27192. };
  27193. /**
  27194. * Creates an extruded polygon mesh, with depth in the Y direction.
  27195. * Please consider using the same method from the MeshBuilder class instead.
  27196. */
  27197. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  27198. var options = {
  27199. shape: shape,
  27200. holes: holes,
  27201. depth: depth,
  27202. updatable: updatable,
  27203. sideOrientation: sideOrientation
  27204. };
  27205. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  27206. };
  27207. /**
  27208. * Creates an extruded shape mesh.
  27209. * 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.
  27210. * Please consider using the same method from the MeshBuilder class instead.
  27211. *
  27212. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27213. * 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
  27214. * extruded along the Z axis.
  27215. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27216. * 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.
  27217. * The parameter `scale` (float, default 1) is the value to scale the shape.
  27218. * 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
  27219. * 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
  27220. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27221. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27222. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27223. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27224. */
  27225. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  27226. if (scene === void 0) { scene = null; }
  27227. var options = {
  27228. shape: shape,
  27229. path: path,
  27230. scale: scale,
  27231. rotation: rotation,
  27232. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27233. sideOrientation: sideOrientation,
  27234. instance: instance,
  27235. updatable: updatable
  27236. };
  27237. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  27238. };
  27239. /**
  27240. * Creates an custom extruded shape mesh.
  27241. * 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.
  27242. * Please consider using the same method from the MeshBuilder class instead.
  27243. *
  27244. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  27245. * 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
  27246. * extruded along the Z axis.
  27247. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  27248. * 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
  27249. * and the distance of this point from the begining of the path :
  27250. * ```javascript
  27251. * var rotationFunction = function(i, distance) {
  27252. * // do things
  27253. * return rotationValue; }
  27254. * ```
  27255. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  27256. * 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
  27257. * and the distance of this point from the begining of the path :
  27258. * ```javascript
  27259. * var scaleFunction = function(i, distance) {
  27260. * // do things
  27261. * return scaleValue;}
  27262. * ```
  27263. * It must returns a float value that will be the scale value applied to the shape on each path point.
  27264. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  27265. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  27266. * 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
  27267. * 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
  27268. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  27269. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27270. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27271. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27272. */
  27273. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  27274. var options = {
  27275. shape: shape,
  27276. path: path,
  27277. scaleFunction: scaleFunction,
  27278. rotationFunction: rotationFunction,
  27279. ribbonCloseArray: ribbonCloseArray,
  27280. ribbonClosePath: ribbonClosePath,
  27281. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  27282. sideOrientation: sideOrientation,
  27283. instance: instance,
  27284. updatable: updatable
  27285. };
  27286. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  27287. };
  27288. /**
  27289. * Creates lathe mesh.
  27290. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  27291. * Please consider using the same method from the MeshBuilder class instead.
  27292. * 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
  27293. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  27294. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  27295. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  27296. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27297. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27298. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27299. */
  27300. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  27301. var options = {
  27302. shape: shape,
  27303. radius: radius,
  27304. tessellation: tessellation,
  27305. sideOrientation: sideOrientation,
  27306. updatable: updatable
  27307. };
  27308. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  27309. };
  27310. /**
  27311. * Creates a plane mesh.
  27312. * Please consider using the same method from the MeshBuilder class instead.
  27313. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  27314. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27315. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27317. */
  27318. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  27319. var options = {
  27320. size: size,
  27321. width: size,
  27322. height: size,
  27323. sideOrientation: sideOrientation,
  27324. updatable: updatable
  27325. };
  27326. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  27327. };
  27328. /**
  27329. * Creates a ground mesh.
  27330. * Please consider using the same method from the MeshBuilder class instead.
  27331. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  27332. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  27333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27334. */
  27335. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  27336. var options = {
  27337. width: width,
  27338. height: height,
  27339. subdivisions: subdivisions,
  27340. updatable: updatable
  27341. };
  27342. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  27343. };
  27344. /**
  27345. * Creates a tiled ground mesh.
  27346. * Please consider using the same method from the MeshBuilder class instead.
  27347. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  27348. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  27349. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  27350. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  27351. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  27352. * numbers of subdivisions on the ground width and height of each tile.
  27353. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27354. */
  27355. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  27356. var options = {
  27357. xmin: xmin,
  27358. zmin: zmin,
  27359. xmax: xmax,
  27360. zmax: zmax,
  27361. subdivisions: subdivisions,
  27362. precision: precision,
  27363. updatable: updatable
  27364. };
  27365. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  27366. };
  27367. /**
  27368. * Creates a ground mesh from a height map.
  27369. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  27370. * Please consider using the same method from the MeshBuilder class instead.
  27371. * The parameter `url` sets the URL of the height map image resource.
  27372. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  27373. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  27374. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  27375. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  27376. * 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).
  27377. * This function is passed the newly built mesh :
  27378. * ```javascript
  27379. * function(mesh) { // do things
  27380. * return; }
  27381. * ```
  27382. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27383. */
  27384. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  27385. var options = {
  27386. width: width,
  27387. height: height,
  27388. subdivisions: subdivisions,
  27389. minHeight: minHeight,
  27390. maxHeight: maxHeight,
  27391. updatable: updatable,
  27392. onReady: onReady
  27393. };
  27394. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  27395. };
  27396. /**
  27397. * Creates a tube mesh.
  27398. * 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.
  27399. * Please consider using the same method from the MeshBuilder class instead.
  27400. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  27401. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  27402. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  27403. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  27404. * 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.
  27405. * It must return a radius value (positive float) :
  27406. * ```javascript
  27407. * var radiusFunction = function(i, distance) {
  27408. * // do things
  27409. * return radius; }
  27410. * ```
  27411. * 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
  27412. * 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
  27413. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27414. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27415. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27416. */
  27417. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  27418. var options = {
  27419. path: path,
  27420. radius: radius,
  27421. tessellation: tessellation,
  27422. radiusFunction: radiusFunction,
  27423. arc: 1,
  27424. cap: cap,
  27425. updatable: updatable,
  27426. sideOrientation: sideOrientation,
  27427. instance: instance
  27428. };
  27429. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  27430. };
  27431. /**
  27432. * Creates a polyhedron mesh.
  27433. * Please consider using the same method from the MeshBuilder class instead.
  27434. * 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
  27435. * to choose the wanted type.
  27436. * The parameter `size` (positive float, default 1) sets the polygon size.
  27437. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  27438. * 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`.
  27439. * 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
  27440. * 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)`).
  27441. * 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
  27442. * 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.
  27443. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27444. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27446. */
  27447. Mesh.CreatePolyhedron = function (name, options, scene) {
  27448. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  27449. };
  27450. /**
  27451. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  27452. * Please consider using the same method from the MeshBuilder class instead.
  27453. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  27454. * 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`).
  27455. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  27456. * 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.
  27457. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  27458. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  27459. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  27460. */
  27461. Mesh.CreateIcoSphere = function (name, options, scene) {
  27462. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  27463. };
  27464. /**
  27465. * Creates a decal mesh.
  27466. * Please consider using the same method from the MeshBuilder class instead.
  27467. * 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.
  27468. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  27469. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  27470. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  27471. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  27472. */
  27473. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  27474. var options = {
  27475. position: position,
  27476. normal: normal,
  27477. size: size,
  27478. angle: angle
  27479. };
  27480. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  27481. };
  27482. // Skeletons
  27483. /**
  27484. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27485. */
  27486. Mesh.prototype.setPositionsForCPUSkinning = function () {
  27487. if (!this._sourcePositions) {
  27488. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27489. if (!source) {
  27490. return this._sourcePositions;
  27491. }
  27492. this._sourcePositions = new Float32Array(source);
  27493. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  27494. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  27495. }
  27496. }
  27497. return this._sourcePositions;
  27498. };
  27499. /**
  27500. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  27501. */
  27502. Mesh.prototype.setNormalsForCPUSkinning = function () {
  27503. if (!this._sourceNormals) {
  27504. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27505. if (!source) {
  27506. return this._sourceNormals;
  27507. }
  27508. this._sourceNormals = new Float32Array(source);
  27509. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  27510. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  27511. }
  27512. }
  27513. return this._sourceNormals;
  27514. };
  27515. /**
  27516. * Updates the vertex buffer by applying transformation from the bones.
  27517. * Returns the Mesh.
  27518. *
  27519. * @param {skeleton} skeleton to apply
  27520. */
  27521. Mesh.prototype.applySkeleton = function (skeleton) {
  27522. if (!this.geometry) {
  27523. return this;
  27524. }
  27525. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  27526. return this;
  27527. }
  27528. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  27529. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  27530. return this;
  27531. }
  27532. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27533. return this;
  27534. }
  27535. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  27536. return this;
  27537. }
  27538. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  27539. return this;
  27540. }
  27541. if (!this._sourcePositions) {
  27542. var submeshes = this.subMeshes.slice();
  27543. this.setPositionsForCPUSkinning();
  27544. this.subMeshes = submeshes;
  27545. }
  27546. if (!this._sourceNormals) {
  27547. this.setNormalsForCPUSkinning();
  27548. }
  27549. // positionsData checks for not being Float32Array will only pass at most once
  27550. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27551. if (!positionsData) {
  27552. return this;
  27553. }
  27554. if (!(positionsData instanceof Float32Array)) {
  27555. positionsData = new Float32Array(positionsData);
  27556. }
  27557. // normalsData checks for not being Float32Array will only pass at most once
  27558. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27559. if (!normalsData) {
  27560. return this;
  27561. }
  27562. if (!(normalsData instanceof Float32Array)) {
  27563. normalsData = new Float32Array(normalsData);
  27564. }
  27565. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27566. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27567. if (!matricesWeightsData || !matricesIndicesData) {
  27568. return this;
  27569. }
  27570. var needExtras = this.numBoneInfluencers > 4;
  27571. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27572. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27573. var skeletonMatrices = skeleton.getTransformMatrices(this);
  27574. var tempVector3 = BABYLON.Vector3.Zero();
  27575. var finalMatrix = new BABYLON.Matrix();
  27576. var tempMatrix = new BABYLON.Matrix();
  27577. var matWeightIdx = 0;
  27578. var inf;
  27579. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  27580. var weight;
  27581. for (inf = 0; inf < 4; inf++) {
  27582. weight = matricesWeightsData[matWeightIdx + inf];
  27583. if (weight > 0) {
  27584. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27585. finalMatrix.addToSelf(tempMatrix);
  27586. }
  27587. else
  27588. break;
  27589. }
  27590. if (needExtras) {
  27591. for (inf = 0; inf < 4; inf++) {
  27592. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27593. if (weight > 0) {
  27594. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27595. finalMatrix.addToSelf(tempMatrix);
  27596. }
  27597. else
  27598. break;
  27599. }
  27600. }
  27601. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  27602. tempVector3.toArray(positionsData, index);
  27603. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  27604. tempVector3.toArray(normalsData, index);
  27605. finalMatrix.reset();
  27606. }
  27607. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  27608. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  27609. return this;
  27610. };
  27611. // Tools
  27612. /**
  27613. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  27614. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  27615. */
  27616. Mesh.MinMax = function (meshes) {
  27617. var minVector = null;
  27618. var maxVector = null;
  27619. meshes.forEach(function (mesh, index, array) {
  27620. var boundingInfo = mesh.getBoundingInfo();
  27621. var boundingBox = boundingInfo.boundingBox;
  27622. if (!minVector || !maxVector) {
  27623. minVector = boundingBox.minimumWorld;
  27624. maxVector = boundingBox.maximumWorld;
  27625. }
  27626. else {
  27627. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  27628. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  27629. }
  27630. });
  27631. if (!minVector || !maxVector) {
  27632. return {
  27633. min: BABYLON.Vector3.Zero(),
  27634. max: BABYLON.Vector3.Zero()
  27635. };
  27636. }
  27637. return {
  27638. min: minVector,
  27639. max: maxVector
  27640. };
  27641. };
  27642. /**
  27643. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  27644. */
  27645. Mesh.Center = function (meshesOrMinMaxVector) {
  27646. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  27647. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  27648. };
  27649. /**
  27650. * Merge the array of meshes into a single mesh for performance reasons.
  27651. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  27652. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  27653. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  27654. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  27655. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  27656. */
  27657. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  27658. if (disposeSource === void 0) { disposeSource = true; }
  27659. var index;
  27660. if (!allow32BitsIndices) {
  27661. var totalVertices = 0;
  27662. // Counting vertices
  27663. for (index = 0; index < meshes.length; index++) {
  27664. if (meshes[index]) {
  27665. totalVertices += meshes[index].getTotalVertices();
  27666. if (totalVertices > 65536) {
  27667. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  27668. return null;
  27669. }
  27670. }
  27671. }
  27672. }
  27673. // Merge
  27674. var vertexData = null;
  27675. var otherVertexData;
  27676. var indiceArray = new Array();
  27677. var source = null;
  27678. for (index = 0; index < meshes.length; index++) {
  27679. if (meshes[index]) {
  27680. meshes[index].computeWorldMatrix(true);
  27681. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  27682. otherVertexData.transform(meshes[index].getWorldMatrix());
  27683. if (vertexData) {
  27684. vertexData.merge(otherVertexData);
  27685. }
  27686. else {
  27687. vertexData = otherVertexData;
  27688. source = meshes[index];
  27689. }
  27690. if (subdivideWithSubMeshes) {
  27691. indiceArray.push(meshes[index].getTotalIndices());
  27692. }
  27693. }
  27694. }
  27695. source = source;
  27696. if (!meshSubclass) {
  27697. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  27698. }
  27699. vertexData.applyToMesh(meshSubclass);
  27700. // Setting properties
  27701. meshSubclass.material = source.material;
  27702. meshSubclass.checkCollisions = source.checkCollisions;
  27703. // Cleaning
  27704. if (disposeSource) {
  27705. for (index = 0; index < meshes.length; index++) {
  27706. if (meshes[index]) {
  27707. meshes[index].dispose();
  27708. }
  27709. }
  27710. }
  27711. // Subdivide
  27712. if (subdivideWithSubMeshes) {
  27713. //-- Suppresions du submesh global
  27714. meshSubclass.releaseSubMeshes();
  27715. index = 0;
  27716. var offset = 0;
  27717. //-- aplique la subdivision en fonction du tableau d'indices
  27718. while (index < indiceArray.length) {
  27719. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  27720. offset += indiceArray[index];
  27721. index++;
  27722. }
  27723. }
  27724. return meshSubclass;
  27725. };
  27726. // Consts
  27727. Mesh._FRONTSIDE = 0;
  27728. Mesh._BACKSIDE = 1;
  27729. Mesh._DOUBLESIDE = 2;
  27730. Mesh._DEFAULTSIDE = 0;
  27731. Mesh._NO_CAP = 0;
  27732. Mesh._CAP_START = 1;
  27733. Mesh._CAP_END = 2;
  27734. Mesh._CAP_ALL = 3;
  27735. return Mesh;
  27736. }(BABYLON.AbstractMesh));
  27737. BABYLON.Mesh = Mesh;
  27738. })(BABYLON || (BABYLON = {}));
  27739. //# sourceMappingURL=babylon.mesh.js.map
  27740. var BABYLON;
  27741. (function (BABYLON) {
  27742. var BaseSubMesh = /** @class */ (function () {
  27743. function BaseSubMesh() {
  27744. }
  27745. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  27746. get: function () {
  27747. return this._materialEffect;
  27748. },
  27749. enumerable: true,
  27750. configurable: true
  27751. });
  27752. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  27753. if (defines === void 0) { defines = null; }
  27754. if (this._materialEffect === effect) {
  27755. if (!effect) {
  27756. this._materialDefines = null;
  27757. }
  27758. return;
  27759. }
  27760. this._materialDefines = defines;
  27761. this._materialEffect = effect;
  27762. };
  27763. return BaseSubMesh;
  27764. }());
  27765. BABYLON.BaseSubMesh = BaseSubMesh;
  27766. var SubMesh = /** @class */ (function (_super) {
  27767. __extends(SubMesh, _super);
  27768. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27769. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27770. var _this = _super.call(this) || this;
  27771. _this.materialIndex = materialIndex;
  27772. _this.verticesStart = verticesStart;
  27773. _this.verticesCount = verticesCount;
  27774. _this.indexStart = indexStart;
  27775. _this.indexCount = indexCount;
  27776. _this._renderId = 0;
  27777. _this._mesh = mesh;
  27778. _this._renderingMesh = renderingMesh || mesh;
  27779. mesh.subMeshes.push(_this);
  27780. _this._trianglePlanes = [];
  27781. _this._id = mesh.subMeshes.length - 1;
  27782. if (createBoundingBox) {
  27783. _this.refreshBoundingInfo();
  27784. mesh.computeWorldMatrix(true);
  27785. }
  27786. return _this;
  27787. }
  27788. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  27789. if (createBoundingBox === void 0) { createBoundingBox = true; }
  27790. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  27791. };
  27792. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  27793. get: function () {
  27794. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  27795. },
  27796. enumerable: true,
  27797. configurable: true
  27798. });
  27799. /**
  27800. * Returns the submesh BoudingInfo object.
  27801. */
  27802. SubMesh.prototype.getBoundingInfo = function () {
  27803. if (this.IsGlobal) {
  27804. return this._mesh.getBoundingInfo();
  27805. }
  27806. return this._boundingInfo;
  27807. };
  27808. /**
  27809. * Sets the submesh BoundingInfo.
  27810. * Return the SubMesh.
  27811. */
  27812. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  27813. this._boundingInfo = boundingInfo;
  27814. return this;
  27815. };
  27816. /**
  27817. * Returns the mesh of the current submesh.
  27818. */
  27819. SubMesh.prototype.getMesh = function () {
  27820. return this._mesh;
  27821. };
  27822. /**
  27823. * Returns the rendering mesh of the submesh.
  27824. */
  27825. SubMesh.prototype.getRenderingMesh = function () {
  27826. return this._renderingMesh;
  27827. };
  27828. /**
  27829. * Returns the submesh material.
  27830. */
  27831. SubMesh.prototype.getMaterial = function () {
  27832. var rootMaterial = this._renderingMesh.material;
  27833. if (rootMaterial === null || rootMaterial === undefined) {
  27834. return this._mesh.getScene().defaultMaterial;
  27835. }
  27836. else if (rootMaterial.getSubMaterial) {
  27837. var multiMaterial = rootMaterial;
  27838. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  27839. if (this._currentMaterial !== effectiveMaterial) {
  27840. this._currentMaterial = effectiveMaterial;
  27841. this._materialDefines = null;
  27842. }
  27843. return effectiveMaterial;
  27844. }
  27845. return rootMaterial;
  27846. };
  27847. // Methods
  27848. /**
  27849. * Sets a new updated BoundingInfo object to the submesh.
  27850. * Returns the SubMesh.
  27851. */
  27852. SubMesh.prototype.refreshBoundingInfo = function () {
  27853. this._lastColliderWorldVertices = null;
  27854. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  27855. return this;
  27856. }
  27857. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27858. if (!data) {
  27859. this._boundingInfo = this._mesh.getBoundingInfo();
  27860. return this;
  27861. }
  27862. var indices = this._renderingMesh.getIndices();
  27863. var extend;
  27864. //is this the only submesh?
  27865. if (this.indexStart === 0 && this.indexCount === indices.length) {
  27866. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27867. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  27868. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  27869. }
  27870. else {
  27871. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  27872. }
  27873. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27874. return this;
  27875. };
  27876. SubMesh.prototype._checkCollision = function (collider) {
  27877. var boundingInfo = this._renderingMesh.getBoundingInfo();
  27878. return boundingInfo._checkCollision(collider);
  27879. };
  27880. /**
  27881. * Updates the submesh BoundingInfo.
  27882. * Returns the Submesh.
  27883. */
  27884. SubMesh.prototype.updateBoundingInfo = function (world) {
  27885. var boundingInfo = this.getBoundingInfo();
  27886. if (!boundingInfo) {
  27887. this.refreshBoundingInfo();
  27888. boundingInfo = this.getBoundingInfo();
  27889. }
  27890. boundingInfo.update(world);
  27891. return this;
  27892. };
  27893. /**
  27894. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  27895. * Boolean returned.
  27896. */
  27897. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  27898. var boundingInfo = this.getBoundingInfo();
  27899. if (!boundingInfo) {
  27900. return false;
  27901. }
  27902. return boundingInfo.isInFrustum(frustumPlanes);
  27903. };
  27904. /**
  27905. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  27906. * Boolean returned.
  27907. */
  27908. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  27909. var boundingInfo = this.getBoundingInfo();
  27910. if (!boundingInfo) {
  27911. return false;
  27912. }
  27913. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  27914. };
  27915. /**
  27916. * Renders the submesh.
  27917. * Returns it.
  27918. */
  27919. SubMesh.prototype.render = function (enableAlphaMode) {
  27920. this._renderingMesh.render(this, enableAlphaMode);
  27921. return this;
  27922. };
  27923. /**
  27924. * Returns a new Index Buffer.
  27925. * Type returned : WebGLBuffer.
  27926. */
  27927. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  27928. if (!this._linesIndexBuffer) {
  27929. var linesIndices = [];
  27930. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27931. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  27932. }
  27933. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  27934. this.linesIndexCount = linesIndices.length;
  27935. }
  27936. return this._linesIndexBuffer;
  27937. };
  27938. /**
  27939. * True is the passed Ray intersects the submesh bounding box.
  27940. * Boolean returned.
  27941. */
  27942. SubMesh.prototype.canIntersects = function (ray) {
  27943. var boundingInfo = this.getBoundingInfo();
  27944. if (!boundingInfo) {
  27945. return false;
  27946. }
  27947. return ray.intersectsBox(boundingInfo.boundingBox);
  27948. };
  27949. /**
  27950. * Returns an object IntersectionInfo.
  27951. */
  27952. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  27953. var intersectInfo = null;
  27954. // LineMesh first as it's also a Mesh...
  27955. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  27956. var lineMesh = this._mesh;
  27957. // Line test
  27958. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  27959. var p0 = positions[indices[index]];
  27960. var p1 = positions[indices[index + 1]];
  27961. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  27962. if (length < 0) {
  27963. continue;
  27964. }
  27965. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  27966. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  27967. if (fastCheck) {
  27968. break;
  27969. }
  27970. }
  27971. }
  27972. }
  27973. else {
  27974. // Triangles test
  27975. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  27976. var p0 = positions[indices[index]];
  27977. var p1 = positions[indices[index + 1]];
  27978. var p2 = positions[indices[index + 2]];
  27979. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  27980. if (currentIntersectInfo) {
  27981. if (currentIntersectInfo.distance < 0) {
  27982. continue;
  27983. }
  27984. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  27985. intersectInfo = currentIntersectInfo;
  27986. intersectInfo.faceId = index / 3;
  27987. if (fastCheck) {
  27988. break;
  27989. }
  27990. }
  27991. }
  27992. }
  27993. }
  27994. return intersectInfo;
  27995. };
  27996. SubMesh.prototype._rebuild = function () {
  27997. if (this._linesIndexBuffer) {
  27998. this._linesIndexBuffer = null;
  27999. }
  28000. };
  28001. // Clone
  28002. /**
  28003. * Creates a new Submesh from the passed Mesh.
  28004. */
  28005. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  28006. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  28007. if (!this.IsGlobal) {
  28008. var boundingInfo = this.getBoundingInfo();
  28009. if (!boundingInfo) {
  28010. return result;
  28011. }
  28012. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  28013. }
  28014. return result;
  28015. };
  28016. // Dispose
  28017. /**
  28018. * Disposes the Submesh.
  28019. * Returns nothing.
  28020. */
  28021. SubMesh.prototype.dispose = function () {
  28022. if (this._linesIndexBuffer) {
  28023. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  28024. this._linesIndexBuffer = null;
  28025. }
  28026. // Remove from mesh
  28027. var index = this._mesh.subMeshes.indexOf(this);
  28028. this._mesh.subMeshes.splice(index, 1);
  28029. };
  28030. // Statics
  28031. /**
  28032. * Creates a new Submesh from the passed parameters :
  28033. * - materialIndex (integer) : the index of the main mesh material.
  28034. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  28035. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  28036. * - mesh (Mesh) : the main mesh to create the submesh from.
  28037. * - renderingMesh (optional Mesh) : rendering mesh.
  28038. */
  28039. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  28040. var minVertexIndex = Number.MAX_VALUE;
  28041. var maxVertexIndex = -Number.MAX_VALUE;
  28042. renderingMesh = (renderingMesh || mesh);
  28043. var indices = renderingMesh.getIndices();
  28044. for (var index = startIndex; index < startIndex + indexCount; index++) {
  28045. var vertexIndex = indices[index];
  28046. if (vertexIndex < minVertexIndex)
  28047. minVertexIndex = vertexIndex;
  28048. if (vertexIndex > maxVertexIndex)
  28049. maxVertexIndex = vertexIndex;
  28050. }
  28051. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  28052. };
  28053. return SubMesh;
  28054. }(BaseSubMesh));
  28055. BABYLON.SubMesh = SubMesh;
  28056. })(BABYLON || (BABYLON = {}));
  28057. //# sourceMappingURL=babylon.subMesh.js.map
  28058. var __assign = (this && this.__assign) || Object.assign || function(t) {
  28059. for (var s, i = 1, n = arguments.length; i < n; i++) {
  28060. s = arguments[i];
  28061. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  28062. t[p] = s[p];
  28063. }
  28064. return t;
  28065. };
  28066. var BABYLON;
  28067. (function (BABYLON) {
  28068. var MaterialDefines = /** @class */ (function () {
  28069. function MaterialDefines() {
  28070. this._isDirty = true;
  28071. this._areLightsDirty = true;
  28072. this._areAttributesDirty = true;
  28073. this._areTexturesDirty = true;
  28074. this._areFresnelDirty = true;
  28075. this._areMiscDirty = true;
  28076. this._areImageProcessingDirty = true;
  28077. this._normals = false;
  28078. this._uvs = false;
  28079. this._needNormals = false;
  28080. this._needUVs = false;
  28081. }
  28082. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  28083. get: function () {
  28084. return this._isDirty;
  28085. },
  28086. enumerable: true,
  28087. configurable: true
  28088. });
  28089. MaterialDefines.prototype.markAsProcessed = function () {
  28090. this._isDirty = false;
  28091. this._areAttributesDirty = false;
  28092. this._areTexturesDirty = false;
  28093. this._areFresnelDirty = false;
  28094. this._areLightsDirty = false;
  28095. this._areMiscDirty = false;
  28096. this._areImageProcessingDirty = false;
  28097. };
  28098. MaterialDefines.prototype.markAsUnprocessed = function () {
  28099. this._isDirty = true;
  28100. };
  28101. MaterialDefines.prototype.markAllAsDirty = function () {
  28102. this._areTexturesDirty = true;
  28103. this._areAttributesDirty = true;
  28104. this._areLightsDirty = true;
  28105. this._areFresnelDirty = true;
  28106. this._areMiscDirty = true;
  28107. this._areImageProcessingDirty = true;
  28108. this._isDirty = true;
  28109. };
  28110. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  28111. this._areImageProcessingDirty = true;
  28112. this._isDirty = true;
  28113. };
  28114. MaterialDefines.prototype.markAsLightDirty = function () {
  28115. this._areLightsDirty = true;
  28116. this._isDirty = true;
  28117. };
  28118. MaterialDefines.prototype.markAsAttributesDirty = function () {
  28119. this._areAttributesDirty = true;
  28120. this._isDirty = true;
  28121. };
  28122. MaterialDefines.prototype.markAsTexturesDirty = function () {
  28123. this._areTexturesDirty = true;
  28124. this._isDirty = true;
  28125. };
  28126. MaterialDefines.prototype.markAsFresnelDirty = function () {
  28127. this._areFresnelDirty = true;
  28128. this._isDirty = true;
  28129. };
  28130. MaterialDefines.prototype.markAsMiscDirty = function () {
  28131. this._areMiscDirty = true;
  28132. this._isDirty = true;
  28133. };
  28134. MaterialDefines.prototype.rebuild = function () {
  28135. if (this._keys) {
  28136. delete this._keys;
  28137. }
  28138. this._keys = [];
  28139. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  28140. var key = _a[_i];
  28141. if (key[0] === "_") {
  28142. continue;
  28143. }
  28144. this._keys.push(key);
  28145. }
  28146. };
  28147. MaterialDefines.prototype.isEqual = function (other) {
  28148. if (this._keys.length !== other._keys.length) {
  28149. return false;
  28150. }
  28151. for (var index = 0; index < this._keys.length; index++) {
  28152. var prop = this._keys[index];
  28153. if (this[prop] !== other[prop]) {
  28154. return false;
  28155. }
  28156. }
  28157. return true;
  28158. };
  28159. MaterialDefines.prototype.cloneTo = function (other) {
  28160. if (this._keys.length !== other._keys.length) {
  28161. other._keys = this._keys.slice(0);
  28162. }
  28163. for (var index = 0; index < this._keys.length; index++) {
  28164. var prop = this._keys[index];
  28165. other[prop] = this[prop];
  28166. }
  28167. };
  28168. MaterialDefines.prototype.reset = function () {
  28169. for (var index = 0; index < this._keys.length; index++) {
  28170. var prop = this._keys[index];
  28171. if (typeof (this[prop]) === "number") {
  28172. this[prop] = 0;
  28173. }
  28174. else {
  28175. this[prop] = false;
  28176. }
  28177. }
  28178. };
  28179. MaterialDefines.prototype.toString = function () {
  28180. var result = "";
  28181. for (var index = 0; index < this._keys.length; index++) {
  28182. var prop = this._keys[index];
  28183. var value = this[prop];
  28184. if (typeof (value) === "number") {
  28185. result += "#define " + prop + " " + this[prop] + "\n";
  28186. }
  28187. else if (value) {
  28188. result += "#define " + prop + "\n";
  28189. }
  28190. }
  28191. return result;
  28192. };
  28193. return MaterialDefines;
  28194. }());
  28195. BABYLON.MaterialDefines = MaterialDefines;
  28196. var Material = /** @class */ (function () {
  28197. function Material(name, scene, doNotAdd) {
  28198. this.checkReadyOnEveryCall = false;
  28199. this.checkReadyOnlyOnce = false;
  28200. this.state = "";
  28201. this.alpha = 1.0;
  28202. this._backFaceCulling = true;
  28203. this.doNotSerialize = false;
  28204. this.storeEffectOnSubMeshes = false;
  28205. /**
  28206. * An event triggered when the material is disposed.
  28207. * @type {BABYLON.Observable}
  28208. */
  28209. this.onDisposeObservable = new BABYLON.Observable();
  28210. /**
  28211. * An event triggered when the material is bound.
  28212. * @type {BABYLON.Observable}
  28213. */
  28214. this.onBindObservable = new BABYLON.Observable();
  28215. /**
  28216. * An event triggered when the material is unbound.
  28217. * @type {BABYLON.Observable}
  28218. */
  28219. this.onUnBindObservable = new BABYLON.Observable();
  28220. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  28221. this._needDepthPrePass = false;
  28222. this.disableDepthWrite = false;
  28223. this.forceDepthWrite = false;
  28224. this.separateCullingPass = false;
  28225. this._fogEnabled = true;
  28226. this.pointSize = 1.0;
  28227. this.zOffset = 0;
  28228. this._wasPreviouslyReady = false;
  28229. this._fillMode = Material.TriangleFillMode;
  28230. this.name = name;
  28231. this.id = name || BABYLON.Tools.RandomId();
  28232. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  28233. if (this._scene.useRightHandedSystem) {
  28234. this.sideOrientation = Material.ClockWiseSideOrientation;
  28235. }
  28236. else {
  28237. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  28238. }
  28239. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  28240. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  28241. if (!doNotAdd) {
  28242. this._scene.materials.push(this);
  28243. }
  28244. }
  28245. Object.defineProperty(Material, "TriangleFillMode", {
  28246. get: function () {
  28247. return Material._TriangleFillMode;
  28248. },
  28249. enumerable: true,
  28250. configurable: true
  28251. });
  28252. Object.defineProperty(Material, "WireFrameFillMode", {
  28253. get: function () {
  28254. return Material._WireFrameFillMode;
  28255. },
  28256. enumerable: true,
  28257. configurable: true
  28258. });
  28259. Object.defineProperty(Material, "PointFillMode", {
  28260. get: function () {
  28261. return Material._PointFillMode;
  28262. },
  28263. enumerable: true,
  28264. configurable: true
  28265. });
  28266. Object.defineProperty(Material, "PointListDrawMode", {
  28267. get: function () {
  28268. return Material._PointListDrawMode;
  28269. },
  28270. enumerable: true,
  28271. configurable: true
  28272. });
  28273. Object.defineProperty(Material, "LineListDrawMode", {
  28274. get: function () {
  28275. return Material._LineListDrawMode;
  28276. },
  28277. enumerable: true,
  28278. configurable: true
  28279. });
  28280. Object.defineProperty(Material, "LineLoopDrawMode", {
  28281. get: function () {
  28282. return Material._LineLoopDrawMode;
  28283. },
  28284. enumerable: true,
  28285. configurable: true
  28286. });
  28287. Object.defineProperty(Material, "LineStripDrawMode", {
  28288. get: function () {
  28289. return Material._LineStripDrawMode;
  28290. },
  28291. enumerable: true,
  28292. configurable: true
  28293. });
  28294. Object.defineProperty(Material, "TriangleStripDrawMode", {
  28295. get: function () {
  28296. return Material._TriangleStripDrawMode;
  28297. },
  28298. enumerable: true,
  28299. configurable: true
  28300. });
  28301. Object.defineProperty(Material, "TriangleFanDrawMode", {
  28302. get: function () {
  28303. return Material._TriangleFanDrawMode;
  28304. },
  28305. enumerable: true,
  28306. configurable: true
  28307. });
  28308. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  28309. get: function () {
  28310. return Material._ClockWiseSideOrientation;
  28311. },
  28312. enumerable: true,
  28313. configurable: true
  28314. });
  28315. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  28316. get: function () {
  28317. return Material._CounterClockWiseSideOrientation;
  28318. },
  28319. enumerable: true,
  28320. configurable: true
  28321. });
  28322. Object.defineProperty(Material, "TextureDirtyFlag", {
  28323. get: function () {
  28324. return Material._TextureDirtyFlag;
  28325. },
  28326. enumerable: true,
  28327. configurable: true
  28328. });
  28329. Object.defineProperty(Material, "LightDirtyFlag", {
  28330. get: function () {
  28331. return Material._LightDirtyFlag;
  28332. },
  28333. enumerable: true,
  28334. configurable: true
  28335. });
  28336. Object.defineProperty(Material, "FresnelDirtyFlag", {
  28337. get: function () {
  28338. return Material._FresnelDirtyFlag;
  28339. },
  28340. enumerable: true,
  28341. configurable: true
  28342. });
  28343. Object.defineProperty(Material, "AttributesDirtyFlag", {
  28344. get: function () {
  28345. return Material._AttributesDirtyFlag;
  28346. },
  28347. enumerable: true,
  28348. configurable: true
  28349. });
  28350. Object.defineProperty(Material, "MiscDirtyFlag", {
  28351. get: function () {
  28352. return Material._MiscDirtyFlag;
  28353. },
  28354. enumerable: true,
  28355. configurable: true
  28356. });
  28357. Object.defineProperty(Material.prototype, "backFaceCulling", {
  28358. get: function () {
  28359. return this._backFaceCulling;
  28360. },
  28361. set: function (value) {
  28362. if (this._backFaceCulling === value) {
  28363. return;
  28364. }
  28365. this._backFaceCulling = value;
  28366. this.markAsDirty(Material.TextureDirtyFlag);
  28367. },
  28368. enumerable: true,
  28369. configurable: true
  28370. });
  28371. Object.defineProperty(Material.prototype, "onDispose", {
  28372. set: function (callback) {
  28373. if (this._onDisposeObserver) {
  28374. this.onDisposeObservable.remove(this._onDisposeObserver);
  28375. }
  28376. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28377. },
  28378. enumerable: true,
  28379. configurable: true
  28380. });
  28381. Object.defineProperty(Material.prototype, "onBind", {
  28382. set: function (callback) {
  28383. if (this._onBindObserver) {
  28384. this.onBindObservable.remove(this._onBindObserver);
  28385. }
  28386. this._onBindObserver = this.onBindObservable.add(callback);
  28387. },
  28388. enumerable: true,
  28389. configurable: true
  28390. });
  28391. Object.defineProperty(Material.prototype, "alphaMode", {
  28392. get: function () {
  28393. return this._alphaMode;
  28394. },
  28395. set: function (value) {
  28396. if (this._alphaMode === value) {
  28397. return;
  28398. }
  28399. this._alphaMode = value;
  28400. this.markAsDirty(Material.TextureDirtyFlag);
  28401. },
  28402. enumerable: true,
  28403. configurable: true
  28404. });
  28405. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  28406. get: function () {
  28407. return this._needDepthPrePass;
  28408. },
  28409. set: function (value) {
  28410. if (this._needDepthPrePass === value) {
  28411. return;
  28412. }
  28413. this._needDepthPrePass = value;
  28414. if (this._needDepthPrePass) {
  28415. this.checkReadyOnEveryCall = true;
  28416. }
  28417. },
  28418. enumerable: true,
  28419. configurable: true
  28420. });
  28421. Object.defineProperty(Material.prototype, "fogEnabled", {
  28422. get: function () {
  28423. return this._fogEnabled;
  28424. },
  28425. set: function (value) {
  28426. if (this._fogEnabled === value) {
  28427. return;
  28428. }
  28429. this._fogEnabled = value;
  28430. this.markAsDirty(Material.MiscDirtyFlag);
  28431. },
  28432. enumerable: true,
  28433. configurable: true
  28434. });
  28435. Object.defineProperty(Material.prototype, "wireframe", {
  28436. get: function () {
  28437. return this._fillMode === Material.WireFrameFillMode;
  28438. },
  28439. set: function (value) {
  28440. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28441. },
  28442. enumerable: true,
  28443. configurable: true
  28444. });
  28445. Object.defineProperty(Material.prototype, "pointsCloud", {
  28446. get: function () {
  28447. return this._fillMode === Material.PointFillMode;
  28448. },
  28449. set: function (value) {
  28450. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28451. },
  28452. enumerable: true,
  28453. configurable: true
  28454. });
  28455. Object.defineProperty(Material.prototype, "fillMode", {
  28456. get: function () {
  28457. return this._fillMode;
  28458. },
  28459. set: function (value) {
  28460. if (this._fillMode === value) {
  28461. return;
  28462. }
  28463. this._fillMode = value;
  28464. this.markAsDirty(Material.MiscDirtyFlag);
  28465. },
  28466. enumerable: true,
  28467. configurable: true
  28468. });
  28469. /**
  28470. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28471. * subclasses should override adding information pertainent to themselves
  28472. */
  28473. Material.prototype.toString = function (fullDetails) {
  28474. var ret = "Name: " + this.name;
  28475. if (fullDetails) {
  28476. }
  28477. return ret;
  28478. };
  28479. /**
  28480. * Child classes can use it to update shaders
  28481. */
  28482. Material.prototype.getClassName = function () {
  28483. return "Material";
  28484. };
  28485. Object.defineProperty(Material.prototype, "isFrozen", {
  28486. get: function () {
  28487. return this.checkReadyOnlyOnce;
  28488. },
  28489. enumerable: true,
  28490. configurable: true
  28491. });
  28492. Material.prototype.freeze = function () {
  28493. this.checkReadyOnlyOnce = true;
  28494. };
  28495. Material.prototype.unfreeze = function () {
  28496. this.checkReadyOnlyOnce = false;
  28497. };
  28498. Material.prototype.isReady = function (mesh, useInstances) {
  28499. return true;
  28500. };
  28501. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28502. return false;
  28503. };
  28504. Material.prototype.getEffect = function () {
  28505. return this._effect;
  28506. };
  28507. Material.prototype.getScene = function () {
  28508. return this._scene;
  28509. };
  28510. Material.prototype.needAlphaBlending = function () {
  28511. return (this.alpha < 1.0);
  28512. };
  28513. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28514. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28515. };
  28516. Material.prototype.needAlphaTesting = function () {
  28517. return false;
  28518. };
  28519. Material.prototype.getAlphaTestTexture = function () {
  28520. return null;
  28521. };
  28522. Material.prototype.markDirty = function () {
  28523. this._wasPreviouslyReady = false;
  28524. };
  28525. Material.prototype._preBind = function (effect, overrideOrientation) {
  28526. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28527. var engine = this._scene.getEngine();
  28528. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28529. var reverse = orientation === Material.ClockWiseSideOrientation;
  28530. engine.enableEffect(effect ? effect : this._effect);
  28531. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28532. return reverse;
  28533. };
  28534. Material.prototype.bind = function (world, mesh) {
  28535. };
  28536. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28537. };
  28538. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28539. };
  28540. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28541. sceneUbo.bindToEffect(effect, "Scene");
  28542. };
  28543. Material.prototype.bindView = function (effect) {
  28544. if (!this._useUBO) {
  28545. effect.setMatrix("view", this.getScene().getViewMatrix());
  28546. }
  28547. else {
  28548. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28549. }
  28550. };
  28551. Material.prototype.bindViewProjection = function (effect) {
  28552. if (!this._useUBO) {
  28553. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28554. }
  28555. else {
  28556. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28557. }
  28558. };
  28559. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  28560. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  28561. };
  28562. Material.prototype._afterBind = function (mesh) {
  28563. this._scene._cachedMaterial = this;
  28564. if (mesh) {
  28565. this._scene._cachedVisibility = mesh.visibility;
  28566. }
  28567. else {
  28568. this._scene._cachedVisibility = 1;
  28569. }
  28570. if (mesh) {
  28571. this.onBindObservable.notifyObservers(mesh);
  28572. }
  28573. if (this.disableDepthWrite) {
  28574. var engine = this._scene.getEngine();
  28575. this._cachedDepthWriteState = engine.getDepthWrite();
  28576. engine.setDepthWrite(false);
  28577. }
  28578. };
  28579. Material.prototype.unbind = function () {
  28580. this.onUnBindObservable.notifyObservers(this);
  28581. if (this.disableDepthWrite) {
  28582. var engine = this._scene.getEngine();
  28583. engine.setDepthWrite(this._cachedDepthWriteState);
  28584. }
  28585. };
  28586. Material.prototype.getActiveTextures = function () {
  28587. return [];
  28588. };
  28589. Material.prototype.hasTexture = function (texture) {
  28590. return false;
  28591. };
  28592. Material.prototype.clone = function (name) {
  28593. return null;
  28594. };
  28595. Material.prototype.getBindedMeshes = function () {
  28596. var result = new Array();
  28597. for (var index = 0; index < this._scene.meshes.length; index++) {
  28598. var mesh = this._scene.meshes[index];
  28599. if (mesh.material === this) {
  28600. result.push(mesh);
  28601. }
  28602. }
  28603. return result;
  28604. };
  28605. /**
  28606. * Force shader compilation including textures ready check
  28607. */
  28608. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28609. var _this = this;
  28610. var localOptions = __assign({ clipPlane: false }, options);
  28611. var subMesh = new BABYLON.BaseSubMesh();
  28612. var scene = this.getScene();
  28613. var checkReady = function () {
  28614. if (!_this._scene || !_this._scene.getEngine()) {
  28615. return;
  28616. }
  28617. if (subMesh._materialDefines) {
  28618. subMesh._materialDefines._renderId = -1;
  28619. }
  28620. var clipPlaneState = scene.clipPlane;
  28621. if (localOptions.clipPlane) {
  28622. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28623. }
  28624. if (_this.storeEffectOnSubMeshes) {
  28625. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28626. if (onCompiled) {
  28627. onCompiled(_this);
  28628. }
  28629. }
  28630. else {
  28631. setTimeout(checkReady, 16);
  28632. }
  28633. }
  28634. else {
  28635. if (_this.isReady(mesh)) {
  28636. if (onCompiled) {
  28637. onCompiled(_this);
  28638. }
  28639. }
  28640. else {
  28641. setTimeout(checkReady, 16);
  28642. }
  28643. }
  28644. if (options && options.clipPlane) {
  28645. scene.clipPlane = clipPlaneState;
  28646. }
  28647. };
  28648. checkReady();
  28649. };
  28650. Material.prototype.markAsDirty = function (flag) {
  28651. if (flag & Material.TextureDirtyFlag) {
  28652. this._markAllSubMeshesAsTexturesDirty();
  28653. }
  28654. if (flag & Material.LightDirtyFlag) {
  28655. this._markAllSubMeshesAsLightsDirty();
  28656. }
  28657. if (flag & Material.FresnelDirtyFlag) {
  28658. this._markAllSubMeshesAsFresnelDirty();
  28659. }
  28660. if (flag & Material.AttributesDirtyFlag) {
  28661. this._markAllSubMeshesAsAttributesDirty();
  28662. }
  28663. if (flag & Material.MiscDirtyFlag) {
  28664. this._markAllSubMeshesAsMiscDirty();
  28665. }
  28666. this.getScene().resetCachedMaterial();
  28667. };
  28668. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28669. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28670. var mesh = _a[_i];
  28671. if (!mesh.subMeshes) {
  28672. continue;
  28673. }
  28674. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28675. var subMesh = _c[_b];
  28676. if (subMesh.getMaterial() !== this) {
  28677. continue;
  28678. }
  28679. if (!subMesh._materialDefines) {
  28680. continue;
  28681. }
  28682. func(subMesh._materialDefines);
  28683. }
  28684. }
  28685. };
  28686. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28687. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28688. };
  28689. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28690. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28691. };
  28692. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28693. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28694. };
  28695. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28696. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28697. };
  28698. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28699. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28700. };
  28701. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28702. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28703. };
  28704. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28705. // Animations
  28706. this.getScene().stopAnimation(this);
  28707. // Remove from scene
  28708. var index = this._scene.materials.indexOf(this);
  28709. if (index >= 0) {
  28710. this._scene.materials.splice(index, 1);
  28711. }
  28712. // Remove from meshes
  28713. for (index = 0; index < this._scene.meshes.length; index++) {
  28714. var mesh = this._scene.meshes[index];
  28715. if (mesh.material === this) {
  28716. mesh.material = null;
  28717. if (mesh.geometry) {
  28718. var geometry = (mesh.geometry);
  28719. if (this.storeEffectOnSubMeshes) {
  28720. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28721. var subMesh = _a[_i];
  28722. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28723. if (forceDisposeEffect && subMesh._materialEffect) {
  28724. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28725. }
  28726. }
  28727. }
  28728. else {
  28729. geometry._releaseVertexArrayObject(this._effect);
  28730. }
  28731. }
  28732. }
  28733. }
  28734. this._uniformBuffer.dispose();
  28735. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28736. if (forceDisposeEffect && this._effect) {
  28737. if (!this.storeEffectOnSubMeshes) {
  28738. this._scene.getEngine()._releaseEffect(this._effect);
  28739. }
  28740. this._effect = null;
  28741. }
  28742. // Callback
  28743. this.onDisposeObservable.notifyObservers(this);
  28744. this.onDisposeObservable.clear();
  28745. this.onBindObservable.clear();
  28746. this.onUnBindObservable.clear();
  28747. };
  28748. Material.prototype.serialize = function () {
  28749. return BABYLON.SerializationHelper.Serialize(this);
  28750. };
  28751. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28752. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28753. multiMaterial.id = parsedMultiMaterial.id;
  28754. if (BABYLON.Tags) {
  28755. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28756. }
  28757. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28758. var subMatId = parsedMultiMaterial.materials[matIndex];
  28759. if (subMatId) {
  28760. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28761. }
  28762. else {
  28763. multiMaterial.subMaterials.push(null);
  28764. }
  28765. }
  28766. return multiMaterial;
  28767. };
  28768. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28769. if (!parsedMaterial.customType) {
  28770. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28771. }
  28772. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28773. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28774. if (!BABYLON.LegacyPBRMaterial) {
  28775. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28776. return;
  28777. }
  28778. }
  28779. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28780. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28781. ;
  28782. };
  28783. // Triangle views
  28784. Material._TriangleFillMode = 0;
  28785. Material._WireFrameFillMode = 1;
  28786. Material._PointFillMode = 2;
  28787. // Draw modes
  28788. Material._PointListDrawMode = 3;
  28789. Material._LineListDrawMode = 4;
  28790. Material._LineLoopDrawMode = 5;
  28791. Material._LineStripDrawMode = 6;
  28792. Material._TriangleStripDrawMode = 7;
  28793. Material._TriangleFanDrawMode = 8;
  28794. Material._ClockWiseSideOrientation = 0;
  28795. Material._CounterClockWiseSideOrientation = 1;
  28796. Material._TextureDirtyFlag = 1;
  28797. Material._LightDirtyFlag = 2;
  28798. Material._FresnelDirtyFlag = 4;
  28799. Material._AttributesDirtyFlag = 8;
  28800. Material._MiscDirtyFlag = 16;
  28801. __decorate([
  28802. BABYLON.serialize()
  28803. ], Material.prototype, "id", void 0);
  28804. __decorate([
  28805. BABYLON.serialize()
  28806. ], Material.prototype, "name", void 0);
  28807. __decorate([
  28808. BABYLON.serialize()
  28809. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28810. __decorate([
  28811. BABYLON.serialize()
  28812. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28813. __decorate([
  28814. BABYLON.serialize()
  28815. ], Material.prototype, "state", void 0);
  28816. __decorate([
  28817. BABYLON.serialize()
  28818. ], Material.prototype, "alpha", void 0);
  28819. __decorate([
  28820. BABYLON.serialize("backFaceCulling")
  28821. ], Material.prototype, "_backFaceCulling", void 0);
  28822. __decorate([
  28823. BABYLON.serialize()
  28824. ], Material.prototype, "sideOrientation", void 0);
  28825. __decorate([
  28826. BABYLON.serialize("alphaMode")
  28827. ], Material.prototype, "_alphaMode", void 0);
  28828. __decorate([
  28829. BABYLON.serialize()
  28830. ], Material.prototype, "_needDepthPrePass", void 0);
  28831. __decorate([
  28832. BABYLON.serialize()
  28833. ], Material.prototype, "disableDepthWrite", void 0);
  28834. __decorate([
  28835. BABYLON.serialize()
  28836. ], Material.prototype, "forceDepthWrite", void 0);
  28837. __decorate([
  28838. BABYLON.serialize()
  28839. ], Material.prototype, "separateCullingPass", void 0);
  28840. __decorate([
  28841. BABYLON.serialize("fogEnabled")
  28842. ], Material.prototype, "_fogEnabled", void 0);
  28843. __decorate([
  28844. BABYLON.serialize()
  28845. ], Material.prototype, "pointSize", void 0);
  28846. __decorate([
  28847. BABYLON.serialize()
  28848. ], Material.prototype, "zOffset", void 0);
  28849. __decorate([
  28850. BABYLON.serialize()
  28851. ], Material.prototype, "wireframe", null);
  28852. __decorate([
  28853. BABYLON.serialize()
  28854. ], Material.prototype, "pointsCloud", null);
  28855. __decorate([
  28856. BABYLON.serialize()
  28857. ], Material.prototype, "fillMode", null);
  28858. return Material;
  28859. }());
  28860. BABYLON.Material = Material;
  28861. })(BABYLON || (BABYLON = {}));
  28862. //# sourceMappingURL=babylon.material.js.map
  28863. var BABYLON;
  28864. (function (BABYLON) {
  28865. var UniformBuffer = /** @class */ (function () {
  28866. /**
  28867. * Uniform buffer objects.
  28868. *
  28869. * Handles blocks of uniform on the GPU.
  28870. *
  28871. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28872. *
  28873. * For more information, please refer to :
  28874. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28875. */
  28876. function UniformBuffer(engine, data, dynamic) {
  28877. this._engine = engine;
  28878. this._noUBO = !engine.supportsUniformBuffers;
  28879. this._dynamic = dynamic;
  28880. this._data = data || [];
  28881. this._uniformLocations = {};
  28882. this._uniformSizes = {};
  28883. this._uniformLocationPointer = 0;
  28884. this._needSync = false;
  28885. if (this._noUBO) {
  28886. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28887. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28888. this.updateFloat = this._updateFloatForEffect;
  28889. this.updateFloat2 = this._updateFloat2ForEffect;
  28890. this.updateFloat3 = this._updateFloat3ForEffect;
  28891. this.updateFloat4 = this._updateFloat4ForEffect;
  28892. this.updateMatrix = this._updateMatrixForEffect;
  28893. this.updateVector3 = this._updateVector3ForEffect;
  28894. this.updateVector4 = this._updateVector4ForEffect;
  28895. this.updateColor3 = this._updateColor3ForEffect;
  28896. this.updateColor4 = this._updateColor4ForEffect;
  28897. }
  28898. else {
  28899. this._engine._uniformBuffers.push(this);
  28900. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28901. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28902. this.updateFloat = this._updateFloatForUniform;
  28903. this.updateFloat2 = this._updateFloat2ForUniform;
  28904. this.updateFloat3 = this._updateFloat3ForUniform;
  28905. this.updateFloat4 = this._updateFloat4ForUniform;
  28906. this.updateMatrix = this._updateMatrixForUniform;
  28907. this.updateVector3 = this._updateVector3ForUniform;
  28908. this.updateVector4 = this._updateVector4ForUniform;
  28909. this.updateColor3 = this._updateColor3ForUniform;
  28910. this.updateColor4 = this._updateColor4ForUniform;
  28911. }
  28912. }
  28913. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28914. // Properties
  28915. /**
  28916. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28917. * or just falling back on setUniformXXX calls.
  28918. */
  28919. get: function () {
  28920. return !this._noUBO;
  28921. },
  28922. enumerable: true,
  28923. configurable: true
  28924. });
  28925. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28926. /**
  28927. * Indicates if the WebGL underlying uniform buffer is in sync
  28928. * with the javascript cache data.
  28929. */
  28930. get: function () {
  28931. return !this._needSync;
  28932. },
  28933. enumerable: true,
  28934. configurable: true
  28935. });
  28936. /**
  28937. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28938. * Also, a dynamic UniformBuffer will disable cache verification and always
  28939. * update the underlying WebGL uniform buffer to the GPU.
  28940. */
  28941. UniformBuffer.prototype.isDynamic = function () {
  28942. return this._dynamic !== undefined;
  28943. };
  28944. /**
  28945. * The data cache on JS side.
  28946. */
  28947. UniformBuffer.prototype.getData = function () {
  28948. return this._bufferData;
  28949. };
  28950. /**
  28951. * The underlying WebGL Uniform buffer.
  28952. */
  28953. UniformBuffer.prototype.getBuffer = function () {
  28954. return this._buffer;
  28955. };
  28956. /**
  28957. * std140 layout specifies how to align data within an UBO structure.
  28958. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28959. * for specs.
  28960. */
  28961. UniformBuffer.prototype._fillAlignment = function (size) {
  28962. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28963. // and 4x4 matrices
  28964. // TODO : change if other types are used
  28965. var alignment;
  28966. if (size <= 2) {
  28967. alignment = size;
  28968. }
  28969. else {
  28970. alignment = 4;
  28971. }
  28972. if ((this._uniformLocationPointer % alignment) !== 0) {
  28973. var oldPointer = this._uniformLocationPointer;
  28974. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28975. var diff = this._uniformLocationPointer - oldPointer;
  28976. for (var i = 0; i < diff; i++) {
  28977. this._data.push(0);
  28978. }
  28979. }
  28980. };
  28981. /**
  28982. * Adds an uniform in the buffer.
  28983. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28984. * for the layout to be correct !
  28985. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28986. * @param {number|number[]} size Data size, or data directly.
  28987. */
  28988. UniformBuffer.prototype.addUniform = function (name, size) {
  28989. if (this._noUBO) {
  28990. return;
  28991. }
  28992. if (this._uniformLocations[name] !== undefined) {
  28993. // Already existing uniform
  28994. return;
  28995. }
  28996. // This function must be called in the order of the shader layout !
  28997. // size can be the size of the uniform, or data directly
  28998. var data;
  28999. if (size instanceof Array) {
  29000. data = size;
  29001. size = data.length;
  29002. }
  29003. else {
  29004. size = size;
  29005. data = [];
  29006. // Fill with zeros
  29007. for (var i = 0; i < size; i++) {
  29008. data.push(0);
  29009. }
  29010. }
  29011. this._fillAlignment(size);
  29012. this._uniformSizes[name] = size;
  29013. this._uniformLocations[name] = this._uniformLocationPointer;
  29014. this._uniformLocationPointer += size;
  29015. for (var i = 0; i < size; i++) {
  29016. this._data.push(data[i]);
  29017. }
  29018. this._needSync = true;
  29019. };
  29020. /**
  29021. * Wrapper for addUniform.
  29022. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29023. * @param {Matrix} mat A 4x4 matrix.
  29024. */
  29025. UniformBuffer.prototype.addMatrix = function (name, mat) {
  29026. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  29027. };
  29028. /**
  29029. * Wrapper for addUniform.
  29030. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29031. * @param {number} x
  29032. * @param {number} y
  29033. */
  29034. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  29035. var temp = [x, y];
  29036. this.addUniform(name, temp);
  29037. };
  29038. /**
  29039. * Wrapper for addUniform.
  29040. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29041. * @param {number} x
  29042. * @param {number} y
  29043. * @param {number} z
  29044. */
  29045. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  29046. var temp = [x, y, z];
  29047. this.addUniform(name, temp);
  29048. };
  29049. /**
  29050. * Wrapper for addUniform.
  29051. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29052. * @param {Color3} color
  29053. */
  29054. UniformBuffer.prototype.addColor3 = function (name, color) {
  29055. var temp = new Array();
  29056. color.toArray(temp);
  29057. this.addUniform(name, temp);
  29058. };
  29059. /**
  29060. * Wrapper for addUniform.
  29061. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29062. * @param {Color3} color
  29063. * @param {number} alpha
  29064. */
  29065. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  29066. var temp = new Array();
  29067. color.toArray(temp);
  29068. temp.push(alpha);
  29069. this.addUniform(name, temp);
  29070. };
  29071. /**
  29072. * Wrapper for addUniform.
  29073. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29074. * @param {Vector3} vector
  29075. */
  29076. UniformBuffer.prototype.addVector3 = function (name, vector) {
  29077. var temp = new Array();
  29078. vector.toArray(temp);
  29079. this.addUniform(name, temp);
  29080. };
  29081. /**
  29082. * Wrapper for addUniform.
  29083. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29084. */
  29085. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  29086. this.addUniform(name, 12);
  29087. };
  29088. /**
  29089. * Wrapper for addUniform.
  29090. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  29091. */
  29092. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  29093. this.addUniform(name, 8);
  29094. };
  29095. /**
  29096. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  29097. */
  29098. UniformBuffer.prototype.create = function () {
  29099. if (this._noUBO) {
  29100. return;
  29101. }
  29102. if (this._buffer) {
  29103. return; // nothing to do
  29104. }
  29105. // See spec, alignment must be filled as a vec4
  29106. this._fillAlignment(4);
  29107. this._bufferData = new Float32Array(this._data);
  29108. this._rebuild();
  29109. this._needSync = true;
  29110. };
  29111. UniformBuffer.prototype._rebuild = function () {
  29112. if (this._noUBO) {
  29113. return;
  29114. }
  29115. if (this._dynamic) {
  29116. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  29117. }
  29118. else {
  29119. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  29120. }
  29121. };
  29122. /**
  29123. * Updates the WebGL Uniform Buffer on the GPU.
  29124. * If the `dynamic` flag is set to true, no cache comparison is done.
  29125. * Otherwise, the buffer will be updated only if the cache differs.
  29126. */
  29127. UniformBuffer.prototype.update = function () {
  29128. if (!this._buffer) {
  29129. this.create();
  29130. return;
  29131. }
  29132. if (!this._dynamic && !this._needSync) {
  29133. return;
  29134. }
  29135. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  29136. this._needSync = false;
  29137. };
  29138. /**
  29139. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  29140. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29141. * @param {number[]|Float32Array} data Flattened data
  29142. * @param {number} size Size of the data.
  29143. */
  29144. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  29145. var location = this._uniformLocations[uniformName];
  29146. if (location === undefined) {
  29147. if (this._buffer) {
  29148. // Cannot add an uniform if the buffer is already created
  29149. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  29150. return;
  29151. }
  29152. this.addUniform(uniformName, size);
  29153. location = this._uniformLocations[uniformName];
  29154. }
  29155. if (!this._buffer) {
  29156. this.create();
  29157. }
  29158. if (!this._dynamic) {
  29159. // Cache for static uniform buffers
  29160. var changed = false;
  29161. for (var i = 0; i < size; i++) {
  29162. if (this._bufferData[location + i] !== data[i]) {
  29163. changed = true;
  29164. this._bufferData[location + i] = data[i];
  29165. }
  29166. }
  29167. this._needSync = this._needSync || changed;
  29168. }
  29169. else {
  29170. // No cache for dynamic
  29171. for (var i = 0; i < size; i++) {
  29172. this._bufferData[location + i] = data[i];
  29173. }
  29174. }
  29175. };
  29176. // Update methods
  29177. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  29178. // To match std140, matrix must be realigned
  29179. for (var i = 0; i < 3; i++) {
  29180. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  29181. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  29182. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  29183. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29184. }
  29185. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  29186. };
  29187. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  29188. this._currentEffect.setMatrix3x3(name, matrix);
  29189. };
  29190. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  29191. this._currentEffect.setMatrix2x2(name, matrix);
  29192. };
  29193. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  29194. // To match std140, matrix must be realigned
  29195. for (var i = 0; i < 2; i++) {
  29196. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  29197. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  29198. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  29199. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  29200. }
  29201. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  29202. };
  29203. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  29204. this._currentEffect.setFloat(name, x);
  29205. };
  29206. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  29207. UniformBuffer._tempBuffer[0] = x;
  29208. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  29209. };
  29210. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  29211. if (suffix === void 0) { suffix = ""; }
  29212. this._currentEffect.setFloat2(name + suffix, x, y);
  29213. };
  29214. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  29215. if (suffix === void 0) { suffix = ""; }
  29216. UniformBuffer._tempBuffer[0] = x;
  29217. UniformBuffer._tempBuffer[1] = y;
  29218. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  29219. };
  29220. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  29221. if (suffix === void 0) { suffix = ""; }
  29222. this._currentEffect.setFloat3(name + suffix, x, y, z);
  29223. };
  29224. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  29225. if (suffix === void 0) { suffix = ""; }
  29226. UniformBuffer._tempBuffer[0] = x;
  29227. UniformBuffer._tempBuffer[1] = y;
  29228. UniformBuffer._tempBuffer[2] = z;
  29229. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29230. };
  29231. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  29232. if (suffix === void 0) { suffix = ""; }
  29233. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  29234. };
  29235. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  29236. if (suffix === void 0) { suffix = ""; }
  29237. UniformBuffer._tempBuffer[0] = x;
  29238. UniformBuffer._tempBuffer[1] = y;
  29239. UniformBuffer._tempBuffer[2] = z;
  29240. UniformBuffer._tempBuffer[3] = w;
  29241. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29242. };
  29243. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  29244. this._currentEffect.setMatrix(name, mat);
  29245. };
  29246. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  29247. this.updateUniform(name, mat.toArray(), 16);
  29248. };
  29249. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  29250. this._currentEffect.setVector3(name, vector);
  29251. };
  29252. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  29253. vector.toArray(UniformBuffer._tempBuffer);
  29254. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29255. };
  29256. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  29257. this._currentEffect.setVector4(name, vector);
  29258. };
  29259. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  29260. vector.toArray(UniformBuffer._tempBuffer);
  29261. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29262. };
  29263. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  29264. if (suffix === void 0) { suffix = ""; }
  29265. this._currentEffect.setColor3(name + suffix, color);
  29266. };
  29267. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  29268. if (suffix === void 0) { suffix = ""; }
  29269. color.toArray(UniformBuffer._tempBuffer);
  29270. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  29271. };
  29272. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  29273. if (suffix === void 0) { suffix = ""; }
  29274. this._currentEffect.setColor4(name + suffix, color, alpha);
  29275. };
  29276. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  29277. if (suffix === void 0) { suffix = ""; }
  29278. color.toArray(UniformBuffer._tempBuffer);
  29279. UniformBuffer._tempBuffer[3] = alpha;
  29280. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  29281. };
  29282. /**
  29283. * Sets a sampler uniform on the effect.
  29284. * @param {string} name Name of the sampler.
  29285. * @param {Texture} texture
  29286. */
  29287. UniformBuffer.prototype.setTexture = function (name, texture) {
  29288. this._currentEffect.setTexture(name, texture);
  29289. };
  29290. /**
  29291. * Directly updates the value of the uniform in the cache AND on the GPU.
  29292. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  29293. * @param {number[]|Float32Array} data Flattened data
  29294. */
  29295. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  29296. this.updateUniform(uniformName, data, data.length);
  29297. this.update();
  29298. };
  29299. /**
  29300. * Binds this uniform buffer to an effect.
  29301. * @param {Effect} effect
  29302. * @param {string} name Name of the uniform block in the shader.
  29303. */
  29304. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  29305. this._currentEffect = effect;
  29306. if (this._noUBO || !this._buffer) {
  29307. return;
  29308. }
  29309. effect.bindUniformBuffer(this._buffer, name);
  29310. };
  29311. /**
  29312. * Disposes the uniform buffer.
  29313. */
  29314. UniformBuffer.prototype.dispose = function () {
  29315. if (this._noUBO) {
  29316. return;
  29317. }
  29318. var index = this._engine._uniformBuffers.indexOf(this);
  29319. if (index !== -1) {
  29320. this._engine._uniformBuffers.splice(index, 1);
  29321. }
  29322. if (!this._buffer) {
  29323. return;
  29324. }
  29325. if (this._engine._releaseBuffer(this._buffer)) {
  29326. this._buffer = null;
  29327. }
  29328. };
  29329. // Pool for avoiding memory leaks
  29330. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  29331. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  29332. return UniformBuffer;
  29333. }());
  29334. BABYLON.UniformBuffer = UniformBuffer;
  29335. })(BABYLON || (BABYLON = {}));
  29336. //# sourceMappingURL=babylon.uniformBuffer.js.map
  29337. var BABYLON;
  29338. (function (BABYLON) {
  29339. var VertexData = /** @class */ (function () {
  29340. function VertexData() {
  29341. }
  29342. VertexData.prototype.set = function (data, kind) {
  29343. switch (kind) {
  29344. case BABYLON.VertexBuffer.PositionKind:
  29345. this.positions = data;
  29346. break;
  29347. case BABYLON.VertexBuffer.NormalKind:
  29348. this.normals = data;
  29349. break;
  29350. case BABYLON.VertexBuffer.TangentKind:
  29351. this.tangents = data;
  29352. break;
  29353. case BABYLON.VertexBuffer.UVKind:
  29354. this.uvs = data;
  29355. break;
  29356. case BABYLON.VertexBuffer.UV2Kind:
  29357. this.uvs2 = data;
  29358. break;
  29359. case BABYLON.VertexBuffer.UV3Kind:
  29360. this.uvs3 = data;
  29361. break;
  29362. case BABYLON.VertexBuffer.UV4Kind:
  29363. this.uvs4 = data;
  29364. break;
  29365. case BABYLON.VertexBuffer.UV5Kind:
  29366. this.uvs5 = data;
  29367. break;
  29368. case BABYLON.VertexBuffer.UV6Kind:
  29369. this.uvs6 = data;
  29370. break;
  29371. case BABYLON.VertexBuffer.ColorKind:
  29372. this.colors = data;
  29373. break;
  29374. case BABYLON.VertexBuffer.MatricesIndicesKind:
  29375. this.matricesIndices = data;
  29376. break;
  29377. case BABYLON.VertexBuffer.MatricesWeightsKind:
  29378. this.matricesWeights = data;
  29379. break;
  29380. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  29381. this.matricesIndicesExtra = data;
  29382. break;
  29383. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  29384. this.matricesWeightsExtra = data;
  29385. break;
  29386. }
  29387. };
  29388. /**
  29389. * Associates the vertexData to the passed Mesh.
  29390. * Sets it as updatable or not (default `false`).
  29391. * Returns the VertexData.
  29392. */
  29393. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  29394. this._applyTo(mesh, updatable);
  29395. return this;
  29396. };
  29397. /**
  29398. * Associates the vertexData to the passed Geometry.
  29399. * Sets it as updatable or not (default `false`).
  29400. * Returns the VertexData.
  29401. */
  29402. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  29403. this._applyTo(geometry, updatable);
  29404. return this;
  29405. };
  29406. /**
  29407. * Updates the associated mesh.
  29408. * Returns the VertexData.
  29409. */
  29410. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  29411. this._update(mesh);
  29412. return this;
  29413. };
  29414. /**
  29415. * Updates the associated geometry.
  29416. * Returns the VertexData.
  29417. */
  29418. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  29419. this._update(geometry);
  29420. return this;
  29421. };
  29422. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29423. if (updatable === void 0) { updatable = false; }
  29424. if (this.positions) {
  29425. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29426. }
  29427. if (this.normals) {
  29428. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29429. }
  29430. if (this.tangents) {
  29431. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29432. }
  29433. if (this.uvs) {
  29434. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29435. }
  29436. if (this.uvs2) {
  29437. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29438. }
  29439. if (this.uvs3) {
  29440. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29441. }
  29442. if (this.uvs4) {
  29443. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29444. }
  29445. if (this.uvs5) {
  29446. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29447. }
  29448. if (this.uvs6) {
  29449. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29450. }
  29451. if (this.colors) {
  29452. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29453. }
  29454. if (this.matricesIndices) {
  29455. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29456. }
  29457. if (this.matricesWeights) {
  29458. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29459. }
  29460. if (this.matricesIndicesExtra) {
  29461. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29462. }
  29463. if (this.matricesWeightsExtra) {
  29464. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29465. }
  29466. if (this.indices) {
  29467. meshOrGeometry.setIndices(this.indices, null, updatable);
  29468. }
  29469. return this;
  29470. };
  29471. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29472. if (this.positions) {
  29473. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29474. }
  29475. if (this.normals) {
  29476. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29477. }
  29478. if (this.tangents) {
  29479. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29480. }
  29481. if (this.uvs) {
  29482. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29483. }
  29484. if (this.uvs2) {
  29485. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29486. }
  29487. if (this.uvs3) {
  29488. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29489. }
  29490. if (this.uvs4) {
  29491. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29492. }
  29493. if (this.uvs5) {
  29494. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29495. }
  29496. if (this.uvs6) {
  29497. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29498. }
  29499. if (this.colors) {
  29500. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29501. }
  29502. if (this.matricesIndices) {
  29503. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29504. }
  29505. if (this.matricesWeights) {
  29506. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29507. }
  29508. if (this.matricesIndicesExtra) {
  29509. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29510. }
  29511. if (this.matricesWeightsExtra) {
  29512. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29513. }
  29514. if (this.indices) {
  29515. meshOrGeometry.setIndices(this.indices, null);
  29516. }
  29517. return this;
  29518. };
  29519. /**
  29520. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29521. * Returns the VertexData.
  29522. */
  29523. VertexData.prototype.transform = function (matrix) {
  29524. var transformed = BABYLON.Vector3.Zero();
  29525. var index;
  29526. if (this.positions) {
  29527. var position = BABYLON.Vector3.Zero();
  29528. for (index = 0; index < this.positions.length; index += 3) {
  29529. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29530. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29531. this.positions[index] = transformed.x;
  29532. this.positions[index + 1] = transformed.y;
  29533. this.positions[index + 2] = transformed.z;
  29534. }
  29535. }
  29536. if (this.normals) {
  29537. var normal = BABYLON.Vector3.Zero();
  29538. for (index = 0; index < this.normals.length; index += 3) {
  29539. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29540. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29541. this.normals[index] = transformed.x;
  29542. this.normals[index + 1] = transformed.y;
  29543. this.normals[index + 2] = transformed.z;
  29544. }
  29545. }
  29546. if (this.tangents) {
  29547. var tangent = BABYLON.Vector4.Zero();
  29548. var tangentTransformed = BABYLON.Vector4.Zero();
  29549. for (index = 0; index < this.tangents.length; index += 4) {
  29550. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29551. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29552. this.tangents[index] = tangentTransformed.x;
  29553. this.tangents[index + 1] = tangentTransformed.y;
  29554. this.tangents[index + 2] = tangentTransformed.z;
  29555. this.tangents[index + 3] = tangentTransformed.w;
  29556. }
  29557. }
  29558. return this;
  29559. };
  29560. /**
  29561. * Merges the passed VertexData into the current one.
  29562. * Returns the modified VertexData.
  29563. */
  29564. VertexData.prototype.merge = function (other, options) {
  29565. options = options || {};
  29566. if (other.indices) {
  29567. if (!this.indices) {
  29568. this.indices = [];
  29569. }
  29570. var offset = this.positions ? this.positions.length / 3 : 0;
  29571. for (var index = 0; index < other.indices.length; index++) {
  29572. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29573. this.indices.push(other.indices[index] + offset);
  29574. }
  29575. }
  29576. this.positions = this._mergeElement(this.positions, other.positions);
  29577. if (!this.positions) {
  29578. return this;
  29579. }
  29580. var count = this.positions.length / 3;
  29581. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29582. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29583. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29584. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29585. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29586. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29587. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29588. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29589. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29590. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29591. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29592. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29593. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29594. return this;
  29595. };
  29596. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29597. if (length === void 0) { length = 0; }
  29598. if (defaultValue === void 0) { defaultValue = 0; }
  29599. if (!other && !source) {
  29600. return null;
  29601. }
  29602. if (!other) {
  29603. var padding = new Float32Array(source.length);
  29604. padding.fill(defaultValue);
  29605. return this._mergeElement(source, padding, length);
  29606. }
  29607. if (!source) {
  29608. if (length === 0 || length === other.length) {
  29609. return other;
  29610. }
  29611. var padding = new Float32Array(length - other.length);
  29612. padding.fill(defaultValue);
  29613. return this._mergeElement(padding, other, length);
  29614. }
  29615. var len = other.length + source.length;
  29616. var isSrcTypedArray = source instanceof Float32Array;
  29617. var isOthTypedArray = other instanceof Float32Array;
  29618. // use non-loop method when the source is Float32Array
  29619. if (isSrcTypedArray) {
  29620. var ret32 = new Float32Array(len);
  29621. ret32.set(source);
  29622. ret32.set(other, source.length);
  29623. return ret32;
  29624. // source is number[], when other is also use concat
  29625. }
  29626. else if (!isOthTypedArray) {
  29627. return source.concat(other);
  29628. // source is a number[], but other is a Float32Array, loop required
  29629. }
  29630. else {
  29631. var ret = source.slice(0); // copy source to a separate array
  29632. for (var i = 0, len = other.length; i < len; i++) {
  29633. ret.push(other[i]);
  29634. }
  29635. return ret;
  29636. }
  29637. };
  29638. /**
  29639. * Serializes the VertexData.
  29640. * Returns a serialized object.
  29641. */
  29642. VertexData.prototype.serialize = function () {
  29643. var serializationObject = this.serialize();
  29644. if (this.positions) {
  29645. serializationObject.positions = this.positions;
  29646. }
  29647. if (this.normals) {
  29648. serializationObject.normals = this.normals;
  29649. }
  29650. if (this.tangents) {
  29651. serializationObject.tangents = this.tangents;
  29652. }
  29653. if (this.uvs) {
  29654. serializationObject.uvs = this.uvs;
  29655. }
  29656. if (this.uvs2) {
  29657. serializationObject.uvs2 = this.uvs2;
  29658. }
  29659. if (this.uvs3) {
  29660. serializationObject.uvs3 = this.uvs3;
  29661. }
  29662. if (this.uvs4) {
  29663. serializationObject.uvs4 = this.uvs4;
  29664. }
  29665. if (this.uvs5) {
  29666. serializationObject.uvs5 = this.uvs5;
  29667. }
  29668. if (this.uvs6) {
  29669. serializationObject.uvs6 = this.uvs6;
  29670. }
  29671. if (this.colors) {
  29672. serializationObject.colors = this.colors;
  29673. }
  29674. if (this.matricesIndices) {
  29675. serializationObject.matricesIndices = this.matricesIndices;
  29676. serializationObject.matricesIndices._isExpanded = true;
  29677. }
  29678. if (this.matricesWeights) {
  29679. serializationObject.matricesWeights = this.matricesWeights;
  29680. }
  29681. if (this.matricesIndicesExtra) {
  29682. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29683. serializationObject.matricesIndicesExtra._isExpanded = true;
  29684. }
  29685. if (this.matricesWeightsExtra) {
  29686. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29687. }
  29688. serializationObject.indices = this.indices;
  29689. return serializationObject;
  29690. };
  29691. // Statics
  29692. /**
  29693. * Returns the object VertexData associated to the passed mesh.
  29694. */
  29695. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29696. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29697. };
  29698. /**
  29699. * Returns the object VertexData associated to the passed geometry.
  29700. */
  29701. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29702. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29703. };
  29704. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29705. var result = new VertexData();
  29706. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29707. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29708. }
  29709. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29710. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29711. }
  29712. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29713. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29714. }
  29715. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29716. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29717. }
  29718. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29719. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29720. }
  29721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29722. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29723. }
  29724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29725. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29726. }
  29727. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29728. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29729. }
  29730. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29731. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29732. }
  29733. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29734. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29735. }
  29736. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29737. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29738. }
  29739. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29740. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29741. }
  29742. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29743. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29744. }
  29745. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29746. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29747. }
  29748. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29749. return result;
  29750. };
  29751. /**
  29752. * Creates the vertexData of the Ribbon.
  29753. */
  29754. VertexData.CreateRibbon = function (options) {
  29755. var pathArray = options.pathArray;
  29756. var closeArray = options.closeArray || false;
  29757. var closePath = options.closePath || false;
  29758. var invertUV = options.invertUV || false;
  29759. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29760. var offset = options.offset || defaultOffset;
  29761. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29762. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29763. var customUV = options.uvs;
  29764. var customColors = options.colors;
  29765. var positions = [];
  29766. var indices = [];
  29767. var normals = [];
  29768. var uvs = [];
  29769. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29770. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29771. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29772. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29773. var minlg; // minimal length among all paths from pathArray
  29774. var lg = []; // array of path lengths : nb of vertex per path
  29775. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29776. var p; // path iterator
  29777. var i; // point iterator
  29778. var j; // point iterator
  29779. // if single path in pathArray
  29780. if (pathArray.length < 2) {
  29781. var ar1 = [];
  29782. var ar2 = [];
  29783. for (i = 0; i < pathArray[0].length - offset; i++) {
  29784. ar1.push(pathArray[0][i]);
  29785. ar2.push(pathArray[0][i + offset]);
  29786. }
  29787. pathArray = [ar1, ar2];
  29788. }
  29789. // positions and horizontal distances (u)
  29790. var idc = 0;
  29791. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29792. var path;
  29793. var l;
  29794. minlg = pathArray[0].length;
  29795. var vectlg;
  29796. var dist;
  29797. for (p = 0; p < pathArray.length; p++) {
  29798. uTotalDistance[p] = 0;
  29799. us[p] = [0];
  29800. path = pathArray[p];
  29801. l = path.length;
  29802. minlg = (minlg < l) ? minlg : l;
  29803. j = 0;
  29804. while (j < l) {
  29805. positions.push(path[j].x, path[j].y, path[j].z);
  29806. if (j > 0) {
  29807. vectlg = path[j].subtract(path[j - 1]).length();
  29808. dist = vectlg + uTotalDistance[p];
  29809. us[p].push(dist);
  29810. uTotalDistance[p] = dist;
  29811. }
  29812. j++;
  29813. }
  29814. if (closePath) {
  29815. j--;
  29816. positions.push(path[0].x, path[0].y, path[0].z);
  29817. vectlg = path[j].subtract(path[0]).length();
  29818. dist = vectlg + uTotalDistance[p];
  29819. us[p].push(dist);
  29820. uTotalDistance[p] = dist;
  29821. }
  29822. lg[p] = l + closePathCorr;
  29823. idx[p] = idc;
  29824. idc += (l + closePathCorr);
  29825. }
  29826. // vertical distances (v)
  29827. var path1;
  29828. var path2;
  29829. var vertex1 = null;
  29830. var vertex2 = null;
  29831. for (i = 0; i < minlg + closePathCorr; i++) {
  29832. vTotalDistance[i] = 0;
  29833. vs[i] = [0];
  29834. for (p = 0; p < pathArray.length - 1; p++) {
  29835. path1 = pathArray[p];
  29836. path2 = pathArray[p + 1];
  29837. if (i === minlg) {
  29838. vertex1 = path1[0];
  29839. vertex2 = path2[0];
  29840. }
  29841. else {
  29842. vertex1 = path1[i];
  29843. vertex2 = path2[i];
  29844. }
  29845. vectlg = vertex2.subtract(vertex1).length();
  29846. dist = vectlg + vTotalDistance[i];
  29847. vs[i].push(dist);
  29848. vTotalDistance[i] = dist;
  29849. }
  29850. if (closeArray && vertex2 && vertex1) {
  29851. path1 = pathArray[p];
  29852. path2 = pathArray[0];
  29853. if (i === minlg) {
  29854. vertex2 = path2[0];
  29855. }
  29856. vectlg = vertex2.subtract(vertex1).length();
  29857. dist = vectlg + vTotalDistance[i];
  29858. vTotalDistance[i] = dist;
  29859. }
  29860. }
  29861. // uvs
  29862. var u;
  29863. var v;
  29864. if (customUV) {
  29865. for (p = 0; p < customUV.length; p++) {
  29866. uvs.push(customUV[p].x, customUV[p].y);
  29867. }
  29868. }
  29869. else {
  29870. for (p = 0; p < pathArray.length; p++) {
  29871. for (i = 0; i < minlg + closePathCorr; i++) {
  29872. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29873. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29874. if (invertUV) {
  29875. uvs.push(v, u);
  29876. }
  29877. else {
  29878. uvs.push(u, v);
  29879. }
  29880. }
  29881. }
  29882. }
  29883. // indices
  29884. p = 0; // path index
  29885. var pi = 0; // positions array index
  29886. var l1 = lg[p] - 1; // path1 length
  29887. var l2 = lg[p + 1] - 1; // path2 length
  29888. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29889. var shft = idx[1] - idx[0]; // shift
  29890. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29891. while (pi <= min && p < path1nb) {
  29892. // 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
  29893. indices.push(pi, pi + shft, pi + 1);
  29894. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29895. pi += 1;
  29896. if (pi === min) {
  29897. p++;
  29898. if (p === lg.length - 1) {
  29899. shft = idx[0] - idx[p];
  29900. l1 = lg[p] - 1;
  29901. l2 = lg[0] - 1;
  29902. }
  29903. else {
  29904. shft = idx[p + 1] - idx[p];
  29905. l1 = lg[p] - 1;
  29906. l2 = lg[p + 1] - 1;
  29907. }
  29908. pi = idx[p];
  29909. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29910. }
  29911. }
  29912. // normals
  29913. VertexData.ComputeNormals(positions, indices, normals);
  29914. if (closePath) {
  29915. var indexFirst = 0;
  29916. var indexLast = 0;
  29917. for (p = 0; p < pathArray.length; p++) {
  29918. indexFirst = idx[p] * 3;
  29919. if (p + 1 < pathArray.length) {
  29920. indexLast = (idx[p + 1] - 1) * 3;
  29921. }
  29922. else {
  29923. indexLast = normals.length - 3;
  29924. }
  29925. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29926. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29927. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29928. normals[indexLast] = normals[indexFirst];
  29929. normals[indexLast + 1] = normals[indexFirst + 1];
  29930. normals[indexLast + 2] = normals[indexFirst + 2];
  29931. }
  29932. }
  29933. // sides
  29934. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29935. // Colors
  29936. var colors = null;
  29937. if (customColors) {
  29938. colors = new Float32Array(customColors.length * 4);
  29939. for (var c = 0; c < customColors.length; c++) {
  29940. colors[c * 4] = customColors[c].r;
  29941. colors[c * 4 + 1] = customColors[c].g;
  29942. colors[c * 4 + 2] = customColors[c].b;
  29943. colors[c * 4 + 3] = customColors[c].a;
  29944. }
  29945. }
  29946. // Result
  29947. var vertexData = new VertexData();
  29948. var positions32 = new Float32Array(positions);
  29949. var normals32 = new Float32Array(normals);
  29950. var uvs32 = new Float32Array(uvs);
  29951. vertexData.indices = indices;
  29952. vertexData.positions = positions32;
  29953. vertexData.normals = normals32;
  29954. vertexData.uvs = uvs32;
  29955. if (colors) {
  29956. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29957. }
  29958. if (closePath) {
  29959. vertexData._idx = idx;
  29960. }
  29961. return vertexData;
  29962. };
  29963. /**
  29964. * Creates the VertexData of the Box.
  29965. */
  29966. VertexData.CreateBox = function (options) {
  29967. var normalsSource = [
  29968. new BABYLON.Vector3(0, 0, 1),
  29969. new BABYLON.Vector3(0, 0, -1),
  29970. new BABYLON.Vector3(1, 0, 0),
  29971. new BABYLON.Vector3(-1, 0, 0),
  29972. new BABYLON.Vector3(0, 1, 0),
  29973. new BABYLON.Vector3(0, -1, 0)
  29974. ];
  29975. var indices = [];
  29976. var positions = [];
  29977. var normals = [];
  29978. var uvs = [];
  29979. var width = options.width || options.size || 1;
  29980. var height = options.height || options.size || 1;
  29981. var depth = options.depth || options.size || 1;
  29982. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29983. var faceUV = options.faceUV || new Array(6);
  29984. var faceColors = options.faceColors;
  29985. var colors = [];
  29986. // default face colors and UV if undefined
  29987. for (var f = 0; f < 6; f++) {
  29988. if (faceUV[f] === undefined) {
  29989. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29990. }
  29991. if (faceColors && faceColors[f] === undefined) {
  29992. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29993. }
  29994. }
  29995. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29996. // Create each face in turn.
  29997. for (var index = 0; index < normalsSource.length; index++) {
  29998. var normal = normalsSource[index];
  29999. // Get two vectors perpendicular to the face normal and to each other.
  30000. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30001. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30002. // Six indices (two triangles) per face.
  30003. var verticesLength = positions.length / 3;
  30004. indices.push(verticesLength);
  30005. indices.push(verticesLength + 1);
  30006. indices.push(verticesLength + 2);
  30007. indices.push(verticesLength);
  30008. indices.push(verticesLength + 2);
  30009. indices.push(verticesLength + 3);
  30010. // Four vertices per face.
  30011. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30012. positions.push(vertex.x, vertex.y, vertex.z);
  30013. normals.push(normal.x, normal.y, normal.z);
  30014. uvs.push(faceUV[index].z, faceUV[index].w);
  30015. if (faceColors) {
  30016. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30017. }
  30018. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30019. positions.push(vertex.x, vertex.y, vertex.z);
  30020. normals.push(normal.x, normal.y, normal.z);
  30021. uvs.push(faceUV[index].x, faceUV[index].w);
  30022. if (faceColors) {
  30023. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30024. }
  30025. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30026. positions.push(vertex.x, vertex.y, vertex.z);
  30027. normals.push(normal.x, normal.y, normal.z);
  30028. uvs.push(faceUV[index].x, faceUV[index].y);
  30029. if (faceColors) {
  30030. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30031. }
  30032. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30033. positions.push(vertex.x, vertex.y, vertex.z);
  30034. normals.push(normal.x, normal.y, normal.z);
  30035. uvs.push(faceUV[index].z, faceUV[index].y);
  30036. if (faceColors) {
  30037. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30038. }
  30039. }
  30040. // sides
  30041. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30042. // Result
  30043. var vertexData = new VertexData();
  30044. vertexData.indices = indices;
  30045. vertexData.positions = positions;
  30046. vertexData.normals = normals;
  30047. vertexData.uvs = uvs;
  30048. if (faceColors) {
  30049. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30050. vertexData.colors = totalColors;
  30051. }
  30052. return vertexData;
  30053. };
  30054. /**
  30055. * Creates the VertexData of the Sphere.
  30056. */
  30057. VertexData.CreateSphere = function (options) {
  30058. var segments = options.segments || 32;
  30059. var diameterX = options.diameterX || options.diameter || 1;
  30060. var diameterY = options.diameterY || options.diameter || 1;
  30061. var diameterZ = options.diameterZ || options.diameter || 1;
  30062. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30063. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30064. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30065. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30066. var totalZRotationSteps = 2 + segments;
  30067. var totalYRotationSteps = 2 * totalZRotationSteps;
  30068. var indices = [];
  30069. var positions = [];
  30070. var normals = [];
  30071. var uvs = [];
  30072. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30073. var normalizedZ = zRotationStep / totalZRotationSteps;
  30074. var angleZ = normalizedZ * Math.PI * slice;
  30075. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30076. var normalizedY = yRotationStep / totalYRotationSteps;
  30077. var angleY = normalizedY * Math.PI * 2 * arc;
  30078. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30079. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30080. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30081. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30082. var vertex = complete.multiply(radius);
  30083. var normal = complete.divide(radius).normalize();
  30084. positions.push(vertex.x, vertex.y, vertex.z);
  30085. normals.push(normal.x, normal.y, normal.z);
  30086. uvs.push(normalizedY, normalizedZ);
  30087. }
  30088. if (zRotationStep > 0) {
  30089. var verticesCount = positions.length / 3;
  30090. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30091. indices.push((firstIndex));
  30092. indices.push((firstIndex + 1));
  30093. indices.push(firstIndex + totalYRotationSteps + 1);
  30094. indices.push((firstIndex + totalYRotationSteps + 1));
  30095. indices.push((firstIndex + 1));
  30096. indices.push((firstIndex + totalYRotationSteps + 2));
  30097. }
  30098. }
  30099. }
  30100. // Sides
  30101. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30102. // Result
  30103. var vertexData = new VertexData();
  30104. vertexData.indices = indices;
  30105. vertexData.positions = positions;
  30106. vertexData.normals = normals;
  30107. vertexData.uvs = uvs;
  30108. return vertexData;
  30109. };
  30110. /**
  30111. * Creates the VertexData of the Cylinder or Cone.
  30112. */
  30113. VertexData.CreateCylinder = function (options) {
  30114. var height = options.height || 2;
  30115. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30116. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  30117. var tessellation = options.tessellation || 24;
  30118. var subdivisions = options.subdivisions || 1;
  30119. var hasRings = options.hasRings ? true : false;
  30120. var enclose = options.enclose ? true : false;
  30121. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30122. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30123. var faceUV = options.faceUV || new Array(3);
  30124. var faceColors = options.faceColors;
  30125. // default face colors and UV if undefined
  30126. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30127. var ringNb = (hasRings) ? subdivisions : 1;
  30128. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30129. var f;
  30130. for (f = 0; f < surfaceNb; f++) {
  30131. if (faceColors && faceColors[f] === undefined) {
  30132. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30133. }
  30134. }
  30135. for (f = 0; f < surfaceNb; f++) {
  30136. if (faceUV && faceUV[f] === undefined) {
  30137. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30138. }
  30139. }
  30140. var indices = new Array();
  30141. var positions = new Array();
  30142. var normals = new Array();
  30143. var uvs = new Array();
  30144. var colors = new Array();
  30145. var angle_step = Math.PI * 2 * arc / tessellation;
  30146. var angle;
  30147. var h;
  30148. var radius;
  30149. var tan = (diameterBottom - diameterTop) / 2 / height;
  30150. var ringVertex = BABYLON.Vector3.Zero();
  30151. var ringNormal = BABYLON.Vector3.Zero();
  30152. var ringFirstVertex = BABYLON.Vector3.Zero();
  30153. var ringFirstNormal = BABYLON.Vector3.Zero();
  30154. var quadNormal = BABYLON.Vector3.Zero();
  30155. var Y = BABYLON.Axis.Y;
  30156. // positions, normals, uvs
  30157. var i;
  30158. var j;
  30159. var r;
  30160. var ringIdx = 1;
  30161. var s = 1; // surface index
  30162. var cs = 0;
  30163. var v = 0;
  30164. for (i = 0; i <= subdivisions; i++) {
  30165. h = i / subdivisions;
  30166. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30167. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30168. for (r = 0; r < ringIdx; r++) {
  30169. if (hasRings) {
  30170. s += r;
  30171. }
  30172. if (enclose) {
  30173. s += 2 * r;
  30174. }
  30175. for (j = 0; j <= tessellation; j++) {
  30176. angle = j * angle_step;
  30177. // position
  30178. ringVertex.x = Math.cos(-angle) * radius;
  30179. ringVertex.y = -height / 2 + h * height;
  30180. ringVertex.z = Math.sin(-angle) * radius;
  30181. // normal
  30182. if (diameterTop === 0 && i === subdivisions) {
  30183. // if no top cap, reuse former normals
  30184. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30185. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30186. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30187. }
  30188. else {
  30189. ringNormal.x = ringVertex.x;
  30190. ringNormal.z = ringVertex.z;
  30191. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30192. ringNormal.normalize();
  30193. }
  30194. // keep first ring vertex values for enclose
  30195. if (j === 0) {
  30196. ringFirstVertex.copyFrom(ringVertex);
  30197. ringFirstNormal.copyFrom(ringNormal);
  30198. }
  30199. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30200. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30201. if (hasRings) {
  30202. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30203. }
  30204. else {
  30205. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30206. }
  30207. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30208. if (faceColors) {
  30209. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30210. }
  30211. }
  30212. // if enclose, add four vertices and their dedicated normals
  30213. if (arc !== 1 && enclose) {
  30214. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30215. positions.push(0, ringVertex.y, 0);
  30216. positions.push(0, ringVertex.y, 0);
  30217. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30218. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30219. quadNormal.normalize();
  30220. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30221. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30222. quadNormal.normalize();
  30223. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30224. if (hasRings) {
  30225. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30226. }
  30227. else {
  30228. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30229. }
  30230. uvs.push(faceUV[s + 1].x, v);
  30231. uvs.push(faceUV[s + 1].z, v);
  30232. if (hasRings) {
  30233. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30234. }
  30235. else {
  30236. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30237. }
  30238. uvs.push(faceUV[s + 2].x, v);
  30239. uvs.push(faceUV[s + 2].z, v);
  30240. if (faceColors) {
  30241. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30242. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30243. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30244. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30245. }
  30246. }
  30247. if (cs !== s) {
  30248. cs = s;
  30249. }
  30250. }
  30251. }
  30252. // indices
  30253. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30254. var s;
  30255. i = 0;
  30256. for (s = 0; s < subdivisions; s++) {
  30257. var i0 = 0;
  30258. var i1 = 0;
  30259. var i2 = 0;
  30260. var i3 = 0;
  30261. for (j = 0; j < tessellation; j++) {
  30262. i0 = i * (e + 1) + j;
  30263. i1 = (i + 1) * (e + 1) + j;
  30264. i2 = i * (e + 1) + (j + 1);
  30265. i3 = (i + 1) * (e + 1) + (j + 1);
  30266. indices.push(i0, i1, i2);
  30267. indices.push(i3, i2, i1);
  30268. }
  30269. if (arc !== 1 && enclose) {
  30270. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30271. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30272. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30273. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30274. }
  30275. i = (hasRings) ? (i + 2) : (i + 1);
  30276. }
  30277. // Caps
  30278. var createCylinderCap = function (isTop) {
  30279. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30280. if (radius === 0) {
  30281. return;
  30282. }
  30283. // Cap positions, normals & uvs
  30284. var angle;
  30285. var circleVector;
  30286. var i;
  30287. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30288. var c = null;
  30289. if (faceColors) {
  30290. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30291. }
  30292. // cap center
  30293. var vbase = positions.length / 3;
  30294. var offset = isTop ? height / 2 : -height / 2;
  30295. var center = new BABYLON.Vector3(0, offset, 0);
  30296. positions.push(center.x, center.y, center.z);
  30297. normals.push(0, isTop ? 1 : -1, 0);
  30298. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30299. if (c) {
  30300. colors.push(c.r, c.g, c.b, c.a);
  30301. }
  30302. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30303. for (i = 0; i <= tessellation; i++) {
  30304. angle = Math.PI * 2 * i * arc / tessellation;
  30305. var cos = Math.cos(-angle);
  30306. var sin = Math.sin(-angle);
  30307. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30308. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30309. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30310. normals.push(0, isTop ? 1 : -1, 0);
  30311. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30312. if (c) {
  30313. colors.push(c.r, c.g, c.b, c.a);
  30314. }
  30315. }
  30316. // Cap indices
  30317. for (i = 0; i < tessellation; i++) {
  30318. if (!isTop) {
  30319. indices.push(vbase);
  30320. indices.push(vbase + (i + 1));
  30321. indices.push(vbase + (i + 2));
  30322. }
  30323. else {
  30324. indices.push(vbase);
  30325. indices.push(vbase + (i + 2));
  30326. indices.push(vbase + (i + 1));
  30327. }
  30328. }
  30329. };
  30330. // add caps to geometry
  30331. createCylinderCap(false);
  30332. createCylinderCap(true);
  30333. // Sides
  30334. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30335. var vertexData = new VertexData();
  30336. vertexData.indices = indices;
  30337. vertexData.positions = positions;
  30338. vertexData.normals = normals;
  30339. vertexData.uvs = uvs;
  30340. if (faceColors) {
  30341. vertexData.colors = colors;
  30342. }
  30343. return vertexData;
  30344. };
  30345. /**
  30346. * Creates the VertexData of the Torus.
  30347. */
  30348. VertexData.CreateTorus = function (options) {
  30349. var indices = [];
  30350. var positions = [];
  30351. var normals = [];
  30352. var uvs = [];
  30353. var diameter = options.diameter || 1;
  30354. var thickness = options.thickness || 0.5;
  30355. var tessellation = options.tessellation || 16;
  30356. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30357. var stride = tessellation + 1;
  30358. for (var i = 0; i <= tessellation; i++) {
  30359. var u = i / tessellation;
  30360. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30361. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  30362. for (var j = 0; j <= tessellation; j++) {
  30363. var v = 1 - j / tessellation;
  30364. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  30365. var dx = Math.cos(innerAngle);
  30366. var dy = Math.sin(innerAngle);
  30367. // Create a vertex.
  30368. var normal = new BABYLON.Vector3(dx, dy, 0);
  30369. var position = normal.scale(thickness / 2);
  30370. var textureCoordinate = new BABYLON.Vector2(u, v);
  30371. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  30372. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  30373. positions.push(position.x, position.y, position.z);
  30374. normals.push(normal.x, normal.y, normal.z);
  30375. uvs.push(textureCoordinate.x, textureCoordinate.y);
  30376. // And create indices for two triangles.
  30377. var nextI = (i + 1) % stride;
  30378. var nextJ = (j + 1) % stride;
  30379. indices.push(i * stride + j);
  30380. indices.push(i * stride + nextJ);
  30381. indices.push(nextI * stride + j);
  30382. indices.push(i * stride + nextJ);
  30383. indices.push(nextI * stride + nextJ);
  30384. indices.push(nextI * stride + j);
  30385. }
  30386. }
  30387. // Sides
  30388. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30389. // Result
  30390. var vertexData = new VertexData();
  30391. vertexData.indices = indices;
  30392. vertexData.positions = positions;
  30393. vertexData.normals = normals;
  30394. vertexData.uvs = uvs;
  30395. return vertexData;
  30396. };
  30397. /**
  30398. * Creates the VertexData of the LineSystem.
  30399. */
  30400. VertexData.CreateLineSystem = function (options) {
  30401. var indices = [];
  30402. var positions = [];
  30403. var lines = options.lines;
  30404. var colors = options.colors;
  30405. var vertexColors = [];
  30406. var idx = 0;
  30407. for (var l = 0; l < lines.length; l++) {
  30408. var points = lines[l];
  30409. for (var index = 0; index < points.length; index++) {
  30410. positions.push(points[index].x, points[index].y, points[index].z);
  30411. if (colors) {
  30412. var color = colors[l];
  30413. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  30414. }
  30415. if (index > 0) {
  30416. indices.push(idx - 1);
  30417. indices.push(idx);
  30418. }
  30419. idx++;
  30420. }
  30421. }
  30422. var vertexData = new VertexData();
  30423. vertexData.indices = indices;
  30424. vertexData.positions = positions;
  30425. if (colors) {
  30426. vertexData.colors = vertexColors;
  30427. }
  30428. return vertexData;
  30429. };
  30430. /**
  30431. * Create the VertexData of the DashedLines.
  30432. */
  30433. VertexData.CreateDashedLines = function (options) {
  30434. var dashSize = options.dashSize || 3;
  30435. var gapSize = options.gapSize || 1;
  30436. var dashNb = options.dashNb || 200;
  30437. var points = options.points;
  30438. var positions = new Array();
  30439. var indices = new Array();
  30440. var curvect = BABYLON.Vector3.Zero();
  30441. var lg = 0;
  30442. var nb = 0;
  30443. var shft = 0;
  30444. var dashshft = 0;
  30445. var curshft = 0;
  30446. var idx = 0;
  30447. var i = 0;
  30448. for (i = 0; i < points.length - 1; i++) {
  30449. points[i + 1].subtractToRef(points[i], curvect);
  30450. lg += curvect.length();
  30451. }
  30452. shft = lg / dashNb;
  30453. dashshft = dashSize * shft / (dashSize + gapSize);
  30454. for (i = 0; i < points.length - 1; i++) {
  30455. points[i + 1].subtractToRef(points[i], curvect);
  30456. nb = Math.floor(curvect.length() / shft);
  30457. curvect.normalize();
  30458. for (var j = 0; j < nb; j++) {
  30459. curshft = shft * j;
  30460. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30461. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30462. indices.push(idx, idx + 1);
  30463. idx += 2;
  30464. }
  30465. }
  30466. // Result
  30467. var vertexData = new VertexData();
  30468. vertexData.positions = positions;
  30469. vertexData.indices = indices;
  30470. return vertexData;
  30471. };
  30472. /**
  30473. * Creates the VertexData of the Ground.
  30474. */
  30475. VertexData.CreateGround = function (options) {
  30476. var indices = [];
  30477. var positions = [];
  30478. var normals = [];
  30479. var uvs = [];
  30480. var row, col;
  30481. var width = options.width || 1;
  30482. var height = options.height || 1;
  30483. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30484. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30485. for (row = 0; row <= subdivisionsY; row++) {
  30486. for (col = 0; col <= subdivisionsX; col++) {
  30487. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30488. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30489. positions.push(position.x, position.y, position.z);
  30490. normals.push(normal.x, normal.y, normal.z);
  30491. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30492. }
  30493. }
  30494. for (row = 0; row < subdivisionsY; row++) {
  30495. for (col = 0; col < subdivisionsX; col++) {
  30496. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30497. indices.push(col + 1 + row * (subdivisionsX + 1));
  30498. indices.push(col + row * (subdivisionsX + 1));
  30499. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30500. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30501. indices.push(col + row * (subdivisionsX + 1));
  30502. }
  30503. }
  30504. // Result
  30505. var vertexData = new VertexData();
  30506. vertexData.indices = indices;
  30507. vertexData.positions = positions;
  30508. vertexData.normals = normals;
  30509. vertexData.uvs = uvs;
  30510. return vertexData;
  30511. };
  30512. /**
  30513. * Creates the VertexData of the TiledGround.
  30514. */
  30515. VertexData.CreateTiledGround = function (options) {
  30516. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  30517. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  30518. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  30519. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  30520. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30521. var precision = options.precision || { w: 1, h: 1 };
  30522. var indices = new Array();
  30523. var positions = new Array();
  30524. var normals = new Array();
  30525. var uvs = new Array();
  30526. var row, col, tileRow, tileCol;
  30527. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30528. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30529. precision.w = (precision.w < 1) ? 1 : precision.w;
  30530. precision.h = (precision.h < 1) ? 1 : precision.h;
  30531. var tileSize = {
  30532. 'w': (xmax - xmin) / subdivisions.w,
  30533. 'h': (zmax - zmin) / subdivisions.h
  30534. };
  30535. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30536. // Indices
  30537. var base = positions.length / 3;
  30538. var rowLength = precision.w + 1;
  30539. for (row = 0; row < precision.h; row++) {
  30540. for (col = 0; col < precision.w; col++) {
  30541. var square = [
  30542. base + col + row * rowLength,
  30543. base + (col + 1) + row * rowLength,
  30544. base + (col + 1) + (row + 1) * rowLength,
  30545. base + col + (row + 1) * rowLength
  30546. ];
  30547. indices.push(square[1]);
  30548. indices.push(square[2]);
  30549. indices.push(square[3]);
  30550. indices.push(square[0]);
  30551. indices.push(square[1]);
  30552. indices.push(square[3]);
  30553. }
  30554. }
  30555. // Position, normals and uvs
  30556. var position = BABYLON.Vector3.Zero();
  30557. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30558. for (row = 0; row <= precision.h; row++) {
  30559. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30560. for (col = 0; col <= precision.w; col++) {
  30561. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30562. position.y = 0;
  30563. positions.push(position.x, position.y, position.z);
  30564. normals.push(normal.x, normal.y, normal.z);
  30565. uvs.push(col / precision.w, row / precision.h);
  30566. }
  30567. }
  30568. }
  30569. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30570. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30571. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30572. }
  30573. }
  30574. // Result
  30575. var vertexData = new VertexData();
  30576. vertexData.indices = indices;
  30577. vertexData.positions = positions;
  30578. vertexData.normals = normals;
  30579. vertexData.uvs = uvs;
  30580. return vertexData;
  30581. };
  30582. /**
  30583. * Creates the VertexData of the Ground designed from a heightmap.
  30584. */
  30585. VertexData.CreateGroundFromHeightMap = function (options) {
  30586. var indices = [];
  30587. var positions = [];
  30588. var normals = [];
  30589. var uvs = [];
  30590. var row, col;
  30591. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30592. // Vertices
  30593. for (row = 0; row <= options.subdivisions; row++) {
  30594. for (col = 0; col <= options.subdivisions; col++) {
  30595. 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));
  30596. // Compute height
  30597. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30598. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30599. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30600. var r = options.buffer[pos] / 255.0;
  30601. var g = options.buffer[pos + 1] / 255.0;
  30602. var b = options.buffer[pos + 2] / 255.0;
  30603. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30604. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30605. // Add vertex
  30606. positions.push(position.x, position.y, position.z);
  30607. normals.push(0, 0, 0);
  30608. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30609. }
  30610. }
  30611. // Indices
  30612. for (row = 0; row < options.subdivisions; row++) {
  30613. for (col = 0; col < options.subdivisions; col++) {
  30614. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30615. indices.push(col + 1 + row * (options.subdivisions + 1));
  30616. indices.push(col + row * (options.subdivisions + 1));
  30617. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30618. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30619. indices.push(col + row * (options.subdivisions + 1));
  30620. }
  30621. }
  30622. // Normals
  30623. VertexData.ComputeNormals(positions, indices, normals);
  30624. // Result
  30625. var vertexData = new VertexData();
  30626. vertexData.indices = indices;
  30627. vertexData.positions = positions;
  30628. vertexData.normals = normals;
  30629. vertexData.uvs = uvs;
  30630. return vertexData;
  30631. };
  30632. /**
  30633. * Creates the VertexData of the Plane.
  30634. */
  30635. VertexData.CreatePlane = function (options) {
  30636. var indices = [];
  30637. var positions = [];
  30638. var normals = [];
  30639. var uvs = [];
  30640. var width = options.width || options.size || 1;
  30641. var height = options.height || options.size || 1;
  30642. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30643. // Vertices
  30644. var halfWidth = width / 2.0;
  30645. var halfHeight = height / 2.0;
  30646. positions.push(-halfWidth, -halfHeight, 0);
  30647. normals.push(0, 0, -1.0);
  30648. uvs.push(0.0, 0.0);
  30649. positions.push(halfWidth, -halfHeight, 0);
  30650. normals.push(0, 0, -1.0);
  30651. uvs.push(1.0, 0.0);
  30652. positions.push(halfWidth, halfHeight, 0);
  30653. normals.push(0, 0, -1.0);
  30654. uvs.push(1.0, 1.0);
  30655. positions.push(-halfWidth, halfHeight, 0);
  30656. normals.push(0, 0, -1.0);
  30657. uvs.push(0.0, 1.0);
  30658. // Indices
  30659. indices.push(0);
  30660. indices.push(1);
  30661. indices.push(2);
  30662. indices.push(0);
  30663. indices.push(2);
  30664. indices.push(3);
  30665. // Sides
  30666. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30667. // Result
  30668. var vertexData = new VertexData();
  30669. vertexData.indices = indices;
  30670. vertexData.positions = positions;
  30671. vertexData.normals = normals;
  30672. vertexData.uvs = uvs;
  30673. return vertexData;
  30674. };
  30675. /**
  30676. * Creates the VertexData of the Disc or regular Polygon.
  30677. */
  30678. VertexData.CreateDisc = function (options) {
  30679. var positions = new Array();
  30680. var indices = new Array();
  30681. var normals = new Array();
  30682. var uvs = new Array();
  30683. var radius = options.radius || 0.5;
  30684. var tessellation = options.tessellation || 64;
  30685. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30686. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30687. // positions and uvs
  30688. positions.push(0, 0, 0); // disc center first
  30689. uvs.push(0.5, 0.5);
  30690. var theta = Math.PI * 2 * arc;
  30691. var step = theta / tessellation;
  30692. for (var a = 0; a < theta; a += step) {
  30693. var x = Math.cos(a);
  30694. var y = Math.sin(a);
  30695. var u = (x + 1) / 2;
  30696. var v = (1 - y) / 2;
  30697. positions.push(radius * x, radius * y, 0);
  30698. uvs.push(u, v);
  30699. }
  30700. if (arc === 1) {
  30701. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30702. uvs.push(uvs[2], uvs[3]);
  30703. }
  30704. //indices
  30705. var vertexNb = positions.length / 3;
  30706. for (var i = 1; i < vertexNb - 1; i++) {
  30707. indices.push(i + 1, 0, i);
  30708. }
  30709. // result
  30710. VertexData.ComputeNormals(positions, indices, normals);
  30711. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30712. var vertexData = new VertexData();
  30713. vertexData.indices = indices;
  30714. vertexData.positions = positions;
  30715. vertexData.normals = normals;
  30716. vertexData.uvs = uvs;
  30717. return vertexData;
  30718. };
  30719. /**
  30720. * Re-creates the VertexData of the Polygon for sideOrientation.
  30721. */
  30722. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30723. var faceUV = fUV || new Array(3);
  30724. var faceColors = fColors;
  30725. var colors = [];
  30726. // default face colors and UV if undefined
  30727. for (var f = 0; f < 3; f++) {
  30728. if (faceUV[f] === undefined) {
  30729. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30730. }
  30731. if (faceColors && faceColors[f] === undefined) {
  30732. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30733. }
  30734. }
  30735. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30736. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30737. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30738. var indices = polygon.getIndices();
  30739. // set face colours and textures
  30740. var idx = 0;
  30741. var face = 0;
  30742. for (var index = 0; index < normals.length; index += 3) {
  30743. //Edge Face no. 1
  30744. if (Math.abs(normals[index + 1]) < 0.001) {
  30745. face = 1;
  30746. }
  30747. //Top Face no. 0
  30748. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30749. face = 0;
  30750. }
  30751. //Bottom Face no. 2
  30752. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30753. face = 2;
  30754. }
  30755. idx = index / 3;
  30756. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30757. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30758. if (faceColors) {
  30759. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30760. }
  30761. }
  30762. // sides
  30763. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30764. // Result
  30765. var vertexData = new VertexData();
  30766. vertexData.indices = indices;
  30767. vertexData.positions = positions;
  30768. vertexData.normals = normals;
  30769. vertexData.uvs = uvs;
  30770. if (faceColors) {
  30771. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30772. vertexData.colors = totalColors;
  30773. }
  30774. return vertexData;
  30775. };
  30776. /**
  30777. * Creates the VertexData of the IcoSphere.
  30778. */
  30779. VertexData.CreateIcoSphere = function (options) {
  30780. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30781. var radius = options.radius || 1;
  30782. var flat = (options.flat === undefined) ? true : options.flat;
  30783. var subdivisions = options.subdivisions || 4;
  30784. var radiusX = options.radiusX || radius;
  30785. var radiusY = options.radiusY || radius;
  30786. var radiusZ = options.radiusZ || radius;
  30787. var t = (1 + Math.sqrt(5)) / 2;
  30788. // 12 vertex x,y,z
  30789. var ico_vertices = [
  30790. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30791. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30792. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30793. ];
  30794. // index of 3 vertex makes a face of icopshere
  30795. var ico_indices = [
  30796. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30797. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30798. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30799. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30800. ];
  30801. // vertex for uv have aliased position, not for UV
  30802. var vertices_unalias_id = [
  30803. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30804. // vertex alias
  30805. 0,
  30806. 2,
  30807. 3,
  30808. 3,
  30809. 3,
  30810. 4,
  30811. 7,
  30812. 8,
  30813. 9,
  30814. 9,
  30815. 10,
  30816. 11 // 23: B + 12
  30817. ];
  30818. // uv as integer step (not pixels !)
  30819. var ico_vertexuv = [
  30820. 5, 1, 3, 1, 6, 4, 0, 0,
  30821. 5, 3, 4, 2, 2, 2, 4, 0,
  30822. 2, 0, 1, 1, 6, 0, 6, 2,
  30823. // vertex alias (for same vertex on different faces)
  30824. 0, 4,
  30825. 3, 3,
  30826. 4, 4,
  30827. 3, 1,
  30828. 4, 2,
  30829. 4, 4,
  30830. 0, 2,
  30831. 1, 1,
  30832. 2, 2,
  30833. 3, 3,
  30834. 1, 3,
  30835. 2, 4 // 23: B + 12
  30836. ];
  30837. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30838. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30839. // First island of uv mapping
  30840. // v = 4h 3+ 2
  30841. // v = 3h 9+ 4
  30842. // v = 2h 9+ 5 B
  30843. // v = 1h 9 1 0
  30844. // v = 0h 3 8 7 A
  30845. // u = 0 1 2 3 4 5 6 *a
  30846. // Second island of uv mapping
  30847. // v = 4h 0+ B+ 4+
  30848. // v = 3h A+ 2+
  30849. // v = 2h 7+ 6 3+
  30850. // v = 1h 8+ 3+
  30851. // v = 0h
  30852. // u = 0 1 2 3 4 5 6 *a
  30853. // Face layout on texture UV mapping
  30854. // ============
  30855. // \ 4 /\ 16 / ======
  30856. // \ / \ / /\ 11 /
  30857. // \/ 7 \/ / \ /
  30858. // ======= / 10 \/
  30859. // /\ 17 /\ =======
  30860. // / \ / \ \ 15 /\
  30861. // / 8 \/ 12 \ \ / \
  30862. // ============ \/ 6 \
  30863. // \ 18 /\ ============
  30864. // \ / \ \ 5 /\ 0 /
  30865. // \/ 13 \ \ / \ /
  30866. // ======= \/ 1 \/
  30867. // =============
  30868. // /\ 19 /\ 2 /\
  30869. // / \ / \ / \
  30870. // / 14 \/ 9 \/ 3 \
  30871. // ===================
  30872. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30873. var ustep = 138 / 1024;
  30874. var vstep = 239 / 1024;
  30875. var uoffset = 60 / 1024;
  30876. var voffset = 26 / 1024;
  30877. // Second island should have margin, not to touch the first island
  30878. // avoid any borderline artefact in pixel rounding
  30879. var island_u_offset = -40 / 1024;
  30880. var island_v_offset = +20 / 1024;
  30881. // face is either island 0 or 1 :
  30882. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30883. var island = [
  30884. 0, 0, 0, 0, 1,
  30885. 0, 0, 1, 1, 0,
  30886. 0, 0, 1, 1, 0,
  30887. 0, 1, 1, 1, 0 // 15 - 19
  30888. ];
  30889. var indices = new Array();
  30890. var positions = new Array();
  30891. var normals = new Array();
  30892. var uvs = new Array();
  30893. var current_indice = 0;
  30894. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30895. var face_vertex_pos = new Array(3);
  30896. var face_vertex_uv = new Array(3);
  30897. var v012;
  30898. for (v012 = 0; v012 < 3; v012++) {
  30899. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30900. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30901. }
  30902. // create all with normals
  30903. for (var face = 0; face < 20; face++) {
  30904. // 3 vertex per face
  30905. for (v012 = 0; v012 < 3; v012++) {
  30906. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30907. var v_id = ico_indices[3 * face + v012];
  30908. // vertex have 3D position (x,y,z)
  30909. 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]);
  30910. // Normalize to get normal, then scale to radius
  30911. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30912. // uv Coordinates from vertex ID
  30913. 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);
  30914. }
  30915. // Subdivide the face (interpolate pos, norm, uv)
  30916. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30917. // - norm is linear interpolation of vertex corner normal
  30918. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30919. // - uv is linear interpolation
  30920. //
  30921. // Topology is as below for sub-divide by 2
  30922. // vertex shown as v0,v1,v2
  30923. // interp index is i1 to progress in range [v0,v1[
  30924. // interp index is i2 to progress in range [v0,v2[
  30925. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30926. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30927. //
  30928. //
  30929. // i2 v2
  30930. // ^ ^
  30931. // / / \
  30932. // / / \
  30933. // / / \
  30934. // / / (0,1) \
  30935. // / #---------\
  30936. // / / \ (0,0)'/ \
  30937. // / / \ / \
  30938. // / / \ / \
  30939. // / / (0,0) \ / (1,0) \
  30940. // / #---------#---------\
  30941. // v0 v1
  30942. //
  30943. // --------------------> i1
  30944. //
  30945. // interp of (i1,i2):
  30946. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30947. // along i1 : lerp(x0,x1, i1/(S-i2))
  30948. //
  30949. // centroid of triangle is needed to get help normal computation
  30950. // (c1,c2) are used for centroid location
  30951. var interp_vertex = function (i1, i2, c1, c2) {
  30952. // vertex is interpolated from
  30953. // - face_vertex_pos[0..2]
  30954. // - face_vertex_uv[0..2]
  30955. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30956. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30957. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30958. pos_interp.normalize();
  30959. var vertex_normal;
  30960. if (flat) {
  30961. // in flat mode, recalculate normal as face centroid normal
  30962. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30963. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30964. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30965. }
  30966. else {
  30967. // in smooth mode, recalculate normal from each single vertex position
  30968. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30969. }
  30970. // Vertex normal need correction due to X,Y,Z radius scaling
  30971. vertex_normal.x /= radiusX;
  30972. vertex_normal.y /= radiusY;
  30973. vertex_normal.z /= radiusZ;
  30974. vertex_normal.normalize();
  30975. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30976. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30977. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30978. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30979. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30980. uvs.push(uv_interp.x, uv_interp.y);
  30981. // push each vertex has member of a face
  30982. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30983. indices.push(current_indice);
  30984. current_indice++;
  30985. };
  30986. for (var i2 = 0; i2 < subdivisions; i2++) {
  30987. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30988. // face : (i1,i2) for /\ :
  30989. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30990. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30991. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30992. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30993. if (i1 + i2 + 1 < subdivisions) {
  30994. // face : (i1,i2)' for \/ :
  30995. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30996. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30997. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30998. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30999. }
  31000. }
  31001. }
  31002. }
  31003. // Sides
  31004. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31005. // Result
  31006. var vertexData = new VertexData();
  31007. vertexData.indices = indices;
  31008. vertexData.positions = positions;
  31009. vertexData.normals = normals;
  31010. vertexData.uvs = uvs;
  31011. return vertexData;
  31012. };
  31013. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31014. /**
  31015. * Creates the VertexData of the Polyhedron.
  31016. */
  31017. VertexData.CreatePolyhedron = function (options) {
  31018. // provided polyhedron types :
  31019. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31020. // 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)
  31021. var polyhedra = [];
  31022. 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]] };
  31023. 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]] };
  31024. polyhedra[2] = {
  31025. 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]],
  31026. 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]]
  31027. };
  31028. polyhedra[3] = {
  31029. 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]],
  31030. 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]]
  31031. };
  31032. polyhedra[4] = {
  31033. 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]],
  31034. 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]]
  31035. };
  31036. 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]] };
  31037. 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]] };
  31038. 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]] };
  31039. 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]] };
  31040. 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]] };
  31041. 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]] };
  31042. 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]] };
  31043. 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]] };
  31044. 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]] };
  31045. polyhedra[14] = {
  31046. 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]],
  31047. 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]]
  31048. };
  31049. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31050. var size = options.size;
  31051. var sizeX = options.sizeX || size || 1;
  31052. var sizeY = options.sizeY || size || 1;
  31053. var sizeZ = options.sizeZ || size || 1;
  31054. var data = options.custom || polyhedra[type];
  31055. var nbfaces = data.face.length;
  31056. var faceUV = options.faceUV || new Array(nbfaces);
  31057. var faceColors = options.faceColors;
  31058. var flat = (options.flat === undefined) ? true : options.flat;
  31059. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31060. var positions = new Array();
  31061. var indices = new Array();
  31062. var normals = new Array();
  31063. var uvs = new Array();
  31064. var colors = new Array();
  31065. var index = 0;
  31066. var faceIdx = 0; // face cursor in the array "indexes"
  31067. var indexes = new Array();
  31068. var i = 0;
  31069. var f = 0;
  31070. var u, v, ang, x, y, tmp;
  31071. // default face colors and UV if undefined
  31072. if (flat) {
  31073. for (f = 0; f < nbfaces; f++) {
  31074. if (faceColors && faceColors[f] === undefined) {
  31075. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31076. }
  31077. if (faceUV && faceUV[f] === undefined) {
  31078. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31079. }
  31080. }
  31081. }
  31082. if (!flat) {
  31083. for (i = 0; i < data.vertex.length; i++) {
  31084. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31085. uvs.push(0, 0);
  31086. }
  31087. for (f = 0; f < nbfaces; f++) {
  31088. for (i = 0; i < data.face[f].length - 2; i++) {
  31089. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31090. }
  31091. }
  31092. }
  31093. else {
  31094. for (f = 0; f < nbfaces; f++) {
  31095. var fl = data.face[f].length; // number of vertices of the current face
  31096. ang = 2 * Math.PI / fl;
  31097. x = 0.5 * Math.tan(ang / 2);
  31098. y = 0.5;
  31099. // positions, uvs, colors
  31100. for (i = 0; i < fl; i++) {
  31101. // positions
  31102. 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);
  31103. indexes.push(index);
  31104. index++;
  31105. // uvs
  31106. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31107. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31108. uvs.push(u, v);
  31109. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31110. y = x * Math.sin(ang) + y * Math.cos(ang);
  31111. x = tmp;
  31112. // colors
  31113. if (faceColors) {
  31114. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31115. }
  31116. }
  31117. // indices from indexes
  31118. for (i = 0; i < fl - 2; i++) {
  31119. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31120. }
  31121. faceIdx += fl;
  31122. }
  31123. }
  31124. VertexData.ComputeNormals(positions, indices, normals);
  31125. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31126. var vertexData = new VertexData();
  31127. vertexData.positions = positions;
  31128. vertexData.indices = indices;
  31129. vertexData.normals = normals;
  31130. vertexData.uvs = uvs;
  31131. if (faceColors && flat) {
  31132. vertexData.colors = colors;
  31133. }
  31134. return vertexData;
  31135. };
  31136. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31137. /**
  31138. * Creates the VertexData of the Torus Knot.
  31139. */
  31140. VertexData.CreateTorusKnot = function (options) {
  31141. var indices = new Array();
  31142. var positions = new Array();
  31143. var normals = new Array();
  31144. var uvs = new Array();
  31145. var radius = options.radius || 2;
  31146. var tube = options.tube || 0.5;
  31147. var radialSegments = options.radialSegments || 32;
  31148. var tubularSegments = options.tubularSegments || 32;
  31149. var p = options.p || 2;
  31150. var q = options.q || 3;
  31151. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31152. // Helper
  31153. var getPos = function (angle) {
  31154. var cu = Math.cos(angle);
  31155. var su = Math.sin(angle);
  31156. var quOverP = q / p * angle;
  31157. var cs = Math.cos(quOverP);
  31158. var tx = radius * (2 + cs) * 0.5 * cu;
  31159. var ty = radius * (2 + cs) * su * 0.5;
  31160. var tz = radius * Math.sin(quOverP) * 0.5;
  31161. return new BABYLON.Vector3(tx, ty, tz);
  31162. };
  31163. // Vertices
  31164. var i;
  31165. var j;
  31166. for (i = 0; i <= radialSegments; i++) {
  31167. var modI = i % radialSegments;
  31168. var u = modI / radialSegments * 2 * p * Math.PI;
  31169. var p1 = getPos(u);
  31170. var p2 = getPos(u + 0.01);
  31171. var tang = p2.subtract(p1);
  31172. var n = p2.add(p1);
  31173. var bitan = BABYLON.Vector3.Cross(tang, n);
  31174. n = BABYLON.Vector3.Cross(bitan, tang);
  31175. bitan.normalize();
  31176. n.normalize();
  31177. for (j = 0; j < tubularSegments; j++) {
  31178. var modJ = j % tubularSegments;
  31179. var v = modJ / tubularSegments * 2 * Math.PI;
  31180. var cx = -tube * Math.cos(v);
  31181. var cy = tube * Math.sin(v);
  31182. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31183. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31184. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31185. uvs.push(i / radialSegments);
  31186. uvs.push(j / tubularSegments);
  31187. }
  31188. }
  31189. for (i = 0; i < radialSegments; i++) {
  31190. for (j = 0; j < tubularSegments; j++) {
  31191. var jNext = (j + 1) % tubularSegments;
  31192. var a = i * tubularSegments + j;
  31193. var b = (i + 1) * tubularSegments + j;
  31194. var c = (i + 1) * tubularSegments + jNext;
  31195. var d = i * tubularSegments + jNext;
  31196. indices.push(d);
  31197. indices.push(b);
  31198. indices.push(a);
  31199. indices.push(d);
  31200. indices.push(c);
  31201. indices.push(b);
  31202. }
  31203. }
  31204. // Normals
  31205. VertexData.ComputeNormals(positions, indices, normals);
  31206. // Sides
  31207. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  31208. // Result
  31209. var vertexData = new VertexData();
  31210. vertexData.indices = indices;
  31211. vertexData.positions = positions;
  31212. vertexData.normals = normals;
  31213. vertexData.uvs = uvs;
  31214. return vertexData;
  31215. };
  31216. // Tools
  31217. /**
  31218. * @param {any} - positions (number[] or Float32Array)
  31219. * @param {any} - indices (number[] or Uint16Array)
  31220. * @param {any} - normals (number[] or Float32Array)
  31221. * options (optional) :
  31222. * facetPositions : optional array of facet positions (vector3)
  31223. * facetNormals : optional array of facet normals (vector3)
  31224. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  31225. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  31226. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  31227. * bbSize : optional bounding box size data, required for facetPartitioning computation
  31228. * bInfo : optional bounding info, required for facetPartitioning computation
  31229. * useRightHandedSystem: optional boolean to for right handed system computation
  31230. * depthSort : optional boolean to enable the facet depth sort computation
  31231. * distanceTo : optional Vector3 to compute the facet depth from this location
  31232. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  31233. */
  31234. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  31235. // temporary scalar variables
  31236. var index = 0; // facet index
  31237. var p1p2x = 0.0; // p1p2 vector x coordinate
  31238. var p1p2y = 0.0; // p1p2 vector y coordinate
  31239. var p1p2z = 0.0; // p1p2 vector z coordinate
  31240. var p3p2x = 0.0; // p3p2 vector x coordinate
  31241. var p3p2y = 0.0; // p3p2 vector y coordinate
  31242. var p3p2z = 0.0; // p3p2 vector z coordinate
  31243. var faceNormalx = 0.0; // facet normal x coordinate
  31244. var faceNormaly = 0.0; // facet normal y coordinate
  31245. var faceNormalz = 0.0; // facet normal z coordinate
  31246. var length = 0.0; // facet normal length before normalization
  31247. var v1x = 0; // vector1 x index in the positions array
  31248. var v1y = 0; // vector1 y index in the positions array
  31249. var v1z = 0; // vector1 z index in the positions array
  31250. var v2x = 0; // vector2 x index in the positions array
  31251. var v2y = 0; // vector2 y index in the positions array
  31252. var v2z = 0; // vector2 z index in the positions array
  31253. var v3x = 0; // vector3 x index in the positions array
  31254. var v3y = 0; // vector3 y index in the positions array
  31255. var v3z = 0; // vector3 z index in the positions array
  31256. var computeFacetNormals = false;
  31257. var computeFacetPositions = false;
  31258. var computeFacetPartitioning = false;
  31259. var computeDepthSort = false;
  31260. var faceNormalSign = 1;
  31261. var ratio = 0;
  31262. var distanceTo = null;
  31263. if (options) {
  31264. computeFacetNormals = (options.facetNormals) ? true : false;
  31265. computeFacetPositions = (options.facetPositions) ? true : false;
  31266. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  31267. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  31268. ratio = options.ratio || 0;
  31269. computeDepthSort = (options.depthSort) ? true : false;
  31270. distanceTo = (options.distanceTo);
  31271. if (computeDepthSort) {
  31272. if (distanceTo === undefined) {
  31273. distanceTo = BABYLON.Vector3.Zero();
  31274. }
  31275. var depthSortedFacets = options.depthSortedFacets;
  31276. }
  31277. }
  31278. // facetPartitioning reinit if needed
  31279. var xSubRatio = 0;
  31280. var ySubRatio = 0;
  31281. var zSubRatio = 0;
  31282. var subSq = 0;
  31283. if (computeFacetPartitioning && options && options.bbSize) {
  31284. var ox = 0; // X partitioning index for facet position
  31285. var oy = 0; // Y partinioning index for facet position
  31286. var oz = 0; // Z partinioning index for facet position
  31287. var b1x = 0; // X partitioning index for facet v1 vertex
  31288. var b1y = 0; // Y partitioning index for facet v1 vertex
  31289. var b1z = 0; // z partitioning index for facet v1 vertex
  31290. var b2x = 0; // X partitioning index for facet v2 vertex
  31291. var b2y = 0; // Y partitioning index for facet v2 vertex
  31292. var b2z = 0; // Z partitioning index for facet v2 vertex
  31293. var b3x = 0; // X partitioning index for facet v3 vertex
  31294. var b3y = 0; // Y partitioning index for facet v3 vertex
  31295. var b3z = 0; // Z partitioning index for facet v3 vertex
  31296. var block_idx_o = 0; // facet barycenter block index
  31297. var block_idx_v1 = 0; // v1 vertex block index
  31298. var block_idx_v2 = 0; // v2 vertex block index
  31299. var block_idx_v3 = 0; // v3 vertex block index
  31300. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  31301. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  31302. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  31303. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  31304. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  31305. subSq = options.subDiv.max * options.subDiv.max;
  31306. options.facetPartitioning.length = 0;
  31307. }
  31308. // reset the normals
  31309. for (index = 0; index < positions.length; index++) {
  31310. normals[index] = 0.0;
  31311. }
  31312. // Loop : 1 indice triplet = 1 facet
  31313. var nbFaces = (indices.length / 3) | 0;
  31314. for (index = 0; index < nbFaces; index++) {
  31315. // get the indexes of the coordinates of each vertex of the facet
  31316. v1x = indices[index * 3] * 3;
  31317. v1y = v1x + 1;
  31318. v1z = v1x + 2;
  31319. v2x = indices[index * 3 + 1] * 3;
  31320. v2y = v2x + 1;
  31321. v2z = v2x + 2;
  31322. v3x = indices[index * 3 + 2] * 3;
  31323. v3y = v3x + 1;
  31324. v3z = v3x + 2;
  31325. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  31326. p1p2y = positions[v1y] - positions[v2y];
  31327. p1p2z = positions[v1z] - positions[v2z];
  31328. p3p2x = positions[v3x] - positions[v2x];
  31329. p3p2y = positions[v3y] - positions[v2y];
  31330. p3p2z = positions[v3z] - positions[v2z];
  31331. // compute the face normal with the cross product
  31332. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  31333. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  31334. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  31335. // normalize this normal and store it in the array facetData
  31336. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31337. length = (length === 0) ? 1.0 : length;
  31338. faceNormalx /= length;
  31339. faceNormaly /= length;
  31340. faceNormalz /= length;
  31341. if (computeFacetNormals && options) {
  31342. options.facetNormals[index].x = faceNormalx;
  31343. options.facetNormals[index].y = faceNormaly;
  31344. options.facetNormals[index].z = faceNormalz;
  31345. }
  31346. if (computeFacetPositions && options) {
  31347. // compute and the facet barycenter coordinates in the array facetPositions
  31348. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  31349. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  31350. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  31351. }
  31352. if (computeFacetPartitioning && options) {
  31353. // store the facet indexes in arrays in the main facetPartitioning array :
  31354. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  31355. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  31356. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  31357. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  31358. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31359. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31360. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31361. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31362. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31363. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31364. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  31365. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  31366. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  31367. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  31368. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  31369. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  31370. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  31371. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  31372. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  31373. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  31374. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  31375. // push each facet index in each block containing the vertex
  31376. options.facetPartitioning[block_idx_v1].push(index);
  31377. if (block_idx_v2 != block_idx_v1) {
  31378. options.facetPartitioning[block_idx_v2].push(index);
  31379. }
  31380. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  31381. options.facetPartitioning[block_idx_v3].push(index);
  31382. }
  31383. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  31384. options.facetPartitioning[block_idx_o].push(index);
  31385. }
  31386. }
  31387. if (computeDepthSort && options && options.facetPositions) {
  31388. var dsf = depthSortedFacets[index];
  31389. dsf.ind = index * 3;
  31390. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  31391. }
  31392. // compute the normals anyway
  31393. normals[v1x] += faceNormalx; // accumulate all the normals per face
  31394. normals[v1y] += faceNormaly;
  31395. normals[v1z] += faceNormalz;
  31396. normals[v2x] += faceNormalx;
  31397. normals[v2y] += faceNormaly;
  31398. normals[v2z] += faceNormalz;
  31399. normals[v3x] += faceNormalx;
  31400. normals[v3y] += faceNormaly;
  31401. normals[v3z] += faceNormalz;
  31402. }
  31403. // last normalization of each normal
  31404. for (index = 0; index < normals.length / 3; index++) {
  31405. faceNormalx = normals[index * 3];
  31406. faceNormaly = normals[index * 3 + 1];
  31407. faceNormalz = normals[index * 3 + 2];
  31408. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31409. length = (length === 0) ? 1.0 : length;
  31410. faceNormalx /= length;
  31411. faceNormaly /= length;
  31412. faceNormalz /= length;
  31413. normals[index * 3] = faceNormalx;
  31414. normals[index * 3 + 1] = faceNormaly;
  31415. normals[index * 3 + 2] = faceNormalz;
  31416. }
  31417. };
  31418. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  31419. var li = indices.length;
  31420. var ln = normals.length;
  31421. var i;
  31422. var n;
  31423. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31424. switch (sideOrientation) {
  31425. case BABYLON.Mesh.FRONTSIDE:
  31426. // nothing changed
  31427. break;
  31428. case BABYLON.Mesh.BACKSIDE:
  31429. var tmp;
  31430. // indices
  31431. for (i = 0; i < li; i += 3) {
  31432. tmp = indices[i];
  31433. indices[i] = indices[i + 2];
  31434. indices[i + 2] = tmp;
  31435. }
  31436. // normals
  31437. for (n = 0; n < ln; n++) {
  31438. normals[n] = -normals[n];
  31439. }
  31440. break;
  31441. case BABYLON.Mesh.DOUBLESIDE:
  31442. // positions
  31443. var lp = positions.length;
  31444. var l = lp / 3;
  31445. for (var p = 0; p < lp; p++) {
  31446. positions[lp + p] = positions[p];
  31447. }
  31448. // indices
  31449. for (i = 0; i < li; i += 3) {
  31450. indices[i + li] = indices[i + 2] + l;
  31451. indices[i + 1 + li] = indices[i + 1] + l;
  31452. indices[i + 2 + li] = indices[i] + l;
  31453. }
  31454. // normals
  31455. for (n = 0; n < ln; n++) {
  31456. normals[ln + n] = -normals[n];
  31457. }
  31458. // uvs
  31459. var lu = uvs.length;
  31460. var u = 0;
  31461. for (u = 0; u < lu; u++) {
  31462. uvs[u + lu] = uvs[u];
  31463. }
  31464. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31465. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31466. u = 0;
  31467. for (i = 0; i < lu / 2; i++) {
  31468. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31469. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31470. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31471. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31472. u += 2;
  31473. }
  31474. break;
  31475. }
  31476. };
  31477. /**
  31478. * Creates a new VertexData from the imported parameters.
  31479. */
  31480. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31481. var vertexData = new VertexData();
  31482. // positions
  31483. var positions = parsedVertexData.positions;
  31484. if (positions) {
  31485. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31486. }
  31487. // normals
  31488. var normals = parsedVertexData.normals;
  31489. if (normals) {
  31490. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31491. }
  31492. // tangents
  31493. var tangents = parsedVertexData.tangents;
  31494. if (tangents) {
  31495. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31496. }
  31497. // uvs
  31498. var uvs = parsedVertexData.uvs;
  31499. if (uvs) {
  31500. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31501. }
  31502. // uv2s
  31503. var uv2s = parsedVertexData.uv2s;
  31504. if (uv2s) {
  31505. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31506. }
  31507. // uv3s
  31508. var uv3s = parsedVertexData.uv3s;
  31509. if (uv3s) {
  31510. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31511. }
  31512. // uv4s
  31513. var uv4s = parsedVertexData.uv4s;
  31514. if (uv4s) {
  31515. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31516. }
  31517. // uv5s
  31518. var uv5s = parsedVertexData.uv5s;
  31519. if (uv5s) {
  31520. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31521. }
  31522. // uv6s
  31523. var uv6s = parsedVertexData.uv6s;
  31524. if (uv6s) {
  31525. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31526. }
  31527. // colors
  31528. var colors = parsedVertexData.colors;
  31529. if (colors) {
  31530. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31531. }
  31532. // matricesIndices
  31533. var matricesIndices = parsedVertexData.matricesIndices;
  31534. if (matricesIndices) {
  31535. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31536. }
  31537. // matricesWeights
  31538. var matricesWeights = parsedVertexData.matricesWeights;
  31539. if (matricesWeights) {
  31540. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31541. }
  31542. // indices
  31543. var indices = parsedVertexData.indices;
  31544. if (indices) {
  31545. vertexData.indices = indices;
  31546. }
  31547. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31548. };
  31549. return VertexData;
  31550. }());
  31551. BABYLON.VertexData = VertexData;
  31552. })(BABYLON || (BABYLON = {}));
  31553. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31554. var BABYLON;
  31555. (function (BABYLON) {
  31556. var Geometry = /** @class */ (function () {
  31557. function Geometry(id, scene, vertexData, updatable, mesh) {
  31558. if (updatable === void 0) { updatable = false; }
  31559. if (mesh === void 0) { mesh = null; }
  31560. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31561. this._totalVertices = 0;
  31562. this._isDisposed = false;
  31563. this._indexBufferIsUpdatable = false;
  31564. this.id = id;
  31565. this._engine = scene.getEngine();
  31566. this._meshes = [];
  31567. this._scene = scene;
  31568. //Init vertex buffer cache
  31569. this._vertexBuffers = {};
  31570. this._indices = [];
  31571. this._updatable = updatable;
  31572. // vertexData
  31573. if (vertexData) {
  31574. this.setAllVerticesData(vertexData, updatable);
  31575. }
  31576. else {
  31577. this._totalVertices = 0;
  31578. this._indices = [];
  31579. }
  31580. if (this._engine.getCaps().vertexArrayObject) {
  31581. this._vertexArrayObjects = {};
  31582. }
  31583. // applyToMesh
  31584. if (mesh) {
  31585. if (mesh.getClassName() === "LinesMesh") {
  31586. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31587. this.updateExtend();
  31588. }
  31589. this.applyToMesh(mesh);
  31590. mesh.computeWorldMatrix(true);
  31591. }
  31592. }
  31593. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31594. /**
  31595. * 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
  31596. * @returns The Bias Vector
  31597. */
  31598. get: function () {
  31599. return this._boundingBias;
  31600. },
  31601. set: function (value) {
  31602. if (this._boundingBias && this._boundingBias.equals(value)) {
  31603. return;
  31604. }
  31605. this._boundingBias = value.clone();
  31606. this.updateBoundingInfo(true, null);
  31607. },
  31608. enumerable: true,
  31609. configurable: true
  31610. });
  31611. Geometry.CreateGeometryForMesh = function (mesh) {
  31612. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31613. geometry.applyToMesh(mesh);
  31614. return geometry;
  31615. };
  31616. Object.defineProperty(Geometry.prototype, "extend", {
  31617. get: function () {
  31618. return this._extend;
  31619. },
  31620. enumerable: true,
  31621. configurable: true
  31622. });
  31623. Geometry.prototype.getScene = function () {
  31624. return this._scene;
  31625. };
  31626. Geometry.prototype.getEngine = function () {
  31627. return this._engine;
  31628. };
  31629. Geometry.prototype.isReady = function () {
  31630. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31631. };
  31632. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31633. get: function () {
  31634. for (var index = 0; index < this._meshes.length; index++) {
  31635. if (!this._meshes[index].doNotSerialize) {
  31636. return false;
  31637. }
  31638. }
  31639. return true;
  31640. },
  31641. enumerable: true,
  31642. configurable: true
  31643. });
  31644. Geometry.prototype._rebuild = function () {
  31645. if (this._vertexArrayObjects) {
  31646. this._vertexArrayObjects = {};
  31647. }
  31648. // Index buffer
  31649. if (this._meshes.length !== 0 && this._indices) {
  31650. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31651. }
  31652. // Vertex buffers
  31653. for (var key in this._vertexBuffers) {
  31654. var vertexBuffer = this._vertexBuffers[key];
  31655. vertexBuffer._rebuild();
  31656. }
  31657. };
  31658. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31659. vertexData.applyToGeometry(this, updatable);
  31660. this.notifyUpdate();
  31661. };
  31662. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31663. if (updatable === void 0) { updatable = false; }
  31664. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31665. this.setVerticesBuffer(buffer);
  31666. };
  31667. Geometry.prototype.removeVerticesData = function (kind) {
  31668. if (this._vertexBuffers[kind]) {
  31669. this._vertexBuffers[kind].dispose();
  31670. delete this._vertexBuffers[kind];
  31671. }
  31672. };
  31673. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31674. var kind = buffer.getKind();
  31675. if (this._vertexBuffers[kind]) {
  31676. this._vertexBuffers[kind].dispose();
  31677. }
  31678. this._vertexBuffers[kind] = buffer;
  31679. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31680. var data = buffer.getData();
  31681. var stride = buffer.getStrideSize();
  31682. this._totalVertices = data.length / stride;
  31683. this.updateExtend(data, stride);
  31684. this._resetPointsArrayCache();
  31685. var meshes = this._meshes;
  31686. var numOfMeshes = meshes.length;
  31687. for (var index = 0; index < numOfMeshes; index++) {
  31688. var mesh = meshes[index];
  31689. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31690. mesh._createGlobalSubMesh(false);
  31691. mesh.computeWorldMatrix(true);
  31692. }
  31693. }
  31694. this.notifyUpdate(kind);
  31695. if (this._vertexArrayObjects) {
  31696. this._disposeVertexArrayObjects();
  31697. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31698. }
  31699. };
  31700. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31701. var vertexBuffer = this.getVertexBuffer(kind);
  31702. if (!vertexBuffer) {
  31703. return;
  31704. }
  31705. vertexBuffer.updateDirectly(data, offset);
  31706. this.notifyUpdate(kind);
  31707. };
  31708. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31709. if (updateExtends === void 0) { updateExtends = false; }
  31710. var vertexBuffer = this.getVertexBuffer(kind);
  31711. if (!vertexBuffer) {
  31712. return;
  31713. }
  31714. vertexBuffer.update(data);
  31715. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31716. var stride = vertexBuffer.getStrideSize();
  31717. this._totalVertices = data.length / stride;
  31718. this.updateBoundingInfo(updateExtends, data);
  31719. }
  31720. this.notifyUpdate(kind);
  31721. };
  31722. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31723. if (updateExtends) {
  31724. this.updateExtend(data);
  31725. }
  31726. var meshes = this._meshes;
  31727. var numOfMeshes = meshes.length;
  31728. this._resetPointsArrayCache();
  31729. for (var index = 0; index < numOfMeshes; index++) {
  31730. var mesh = meshes[index];
  31731. if (updateExtends) {
  31732. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31733. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31734. var subMesh = mesh.subMeshes[subIndex];
  31735. subMesh.refreshBoundingInfo();
  31736. }
  31737. }
  31738. }
  31739. };
  31740. Geometry.prototype._bind = function (effect, indexToBind) {
  31741. if (!effect) {
  31742. return;
  31743. }
  31744. if (indexToBind === undefined) {
  31745. indexToBind = this._indexBuffer;
  31746. }
  31747. var vbs = this.getVertexBuffers();
  31748. if (!vbs) {
  31749. return;
  31750. }
  31751. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31752. this._engine.bindBuffers(vbs, indexToBind, effect);
  31753. return;
  31754. }
  31755. // Using VAO
  31756. if (!this._vertexArrayObjects[effect.key]) {
  31757. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31758. }
  31759. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31760. };
  31761. Geometry.prototype.getTotalVertices = function () {
  31762. if (!this.isReady()) {
  31763. return 0;
  31764. }
  31765. return this._totalVertices;
  31766. };
  31767. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31768. var vertexBuffer = this.getVertexBuffer(kind);
  31769. if (!vertexBuffer) {
  31770. return null;
  31771. }
  31772. var orig = vertexBuffer.getData();
  31773. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31774. return orig;
  31775. }
  31776. else {
  31777. var len = orig.length;
  31778. var copy = [];
  31779. for (var i = 0; i < len; i++) {
  31780. copy.push(orig[i]);
  31781. }
  31782. return copy;
  31783. }
  31784. };
  31785. /**
  31786. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31787. * Possible `kind` values :
  31788. * - BABYLON.VertexBuffer.PositionKind
  31789. * - BABYLON.VertexBuffer.UVKind
  31790. * - BABYLON.VertexBuffer.UV2Kind
  31791. * - BABYLON.VertexBuffer.UV3Kind
  31792. * - BABYLON.VertexBuffer.UV4Kind
  31793. * - BABYLON.VertexBuffer.UV5Kind
  31794. * - BABYLON.VertexBuffer.UV6Kind
  31795. * - BABYLON.VertexBuffer.ColorKind
  31796. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31797. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31798. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31799. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31800. */
  31801. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31802. var vb = this._vertexBuffers[kind];
  31803. if (!vb) {
  31804. return false;
  31805. }
  31806. return vb.isUpdatable();
  31807. };
  31808. Geometry.prototype.getVertexBuffer = function (kind) {
  31809. if (!this.isReady()) {
  31810. return null;
  31811. }
  31812. return this._vertexBuffers[kind];
  31813. };
  31814. Geometry.prototype.getVertexBuffers = function () {
  31815. if (!this.isReady()) {
  31816. return null;
  31817. }
  31818. return this._vertexBuffers;
  31819. };
  31820. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31821. if (!this._vertexBuffers) {
  31822. if (this._delayInfo) {
  31823. return this._delayInfo.indexOf(kind) !== -1;
  31824. }
  31825. return false;
  31826. }
  31827. return this._vertexBuffers[kind] !== undefined;
  31828. };
  31829. Geometry.prototype.getVerticesDataKinds = function () {
  31830. var result = [];
  31831. var kind;
  31832. if (!this._vertexBuffers && this._delayInfo) {
  31833. for (kind in this._delayInfo) {
  31834. result.push(kind);
  31835. }
  31836. }
  31837. else {
  31838. for (kind in this._vertexBuffers) {
  31839. result.push(kind);
  31840. }
  31841. }
  31842. return result;
  31843. };
  31844. Geometry.prototype.updateIndices = function (indices, offset) {
  31845. if (!this._indexBuffer) {
  31846. return;
  31847. }
  31848. if (!this._indexBufferIsUpdatable) {
  31849. this.setIndices(indices, null, true);
  31850. }
  31851. else {
  31852. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31853. }
  31854. };
  31855. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31856. if (totalVertices === void 0) { totalVertices = null; }
  31857. if (updatable === void 0) { updatable = false; }
  31858. if (this._indexBuffer) {
  31859. this._engine._releaseBuffer(this._indexBuffer);
  31860. }
  31861. this._disposeVertexArrayObjects();
  31862. this._indices = indices;
  31863. this._indexBufferIsUpdatable = updatable;
  31864. if (this._meshes.length !== 0 && this._indices) {
  31865. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31866. }
  31867. if (totalVertices != undefined) {
  31868. this._totalVertices = totalVertices;
  31869. }
  31870. var meshes = this._meshes;
  31871. var numOfMeshes = meshes.length;
  31872. for (var index = 0; index < numOfMeshes; index++) {
  31873. meshes[index]._createGlobalSubMesh(true);
  31874. }
  31875. this.notifyUpdate();
  31876. };
  31877. Geometry.prototype.getTotalIndices = function () {
  31878. if (!this.isReady()) {
  31879. return 0;
  31880. }
  31881. return this._indices.length;
  31882. };
  31883. Geometry.prototype.getIndices = function (copyWhenShared) {
  31884. if (!this.isReady()) {
  31885. return null;
  31886. }
  31887. var orig = this._indices;
  31888. if (!copyWhenShared || this._meshes.length === 1) {
  31889. return orig;
  31890. }
  31891. else {
  31892. var len = orig.length;
  31893. var copy = [];
  31894. for (var i = 0; i < len; i++) {
  31895. copy.push(orig[i]);
  31896. }
  31897. return copy;
  31898. }
  31899. };
  31900. Geometry.prototype.getIndexBuffer = function () {
  31901. if (!this.isReady()) {
  31902. return null;
  31903. }
  31904. return this._indexBuffer;
  31905. };
  31906. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31907. if (effect === void 0) { effect = null; }
  31908. if (!effect || !this._vertexArrayObjects) {
  31909. return;
  31910. }
  31911. if (this._vertexArrayObjects[effect.key]) {
  31912. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31913. delete this._vertexArrayObjects[effect.key];
  31914. }
  31915. };
  31916. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31917. var meshes = this._meshes;
  31918. var index = meshes.indexOf(mesh);
  31919. if (index === -1) {
  31920. return;
  31921. }
  31922. meshes.splice(index, 1);
  31923. mesh._geometry = null;
  31924. if (meshes.length === 0 && shouldDispose) {
  31925. this.dispose();
  31926. }
  31927. };
  31928. Geometry.prototype.applyToMesh = function (mesh) {
  31929. if (mesh._geometry === this) {
  31930. return;
  31931. }
  31932. var previousGeometry = mesh._geometry;
  31933. if (previousGeometry) {
  31934. previousGeometry.releaseForMesh(mesh);
  31935. }
  31936. var meshes = this._meshes;
  31937. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31938. mesh._geometry = this;
  31939. this._scene.pushGeometry(this);
  31940. meshes.push(mesh);
  31941. if (this.isReady()) {
  31942. this._applyToMesh(mesh);
  31943. }
  31944. else {
  31945. mesh._boundingInfo = this._boundingInfo;
  31946. }
  31947. };
  31948. Geometry.prototype.updateExtend = function (data, stride) {
  31949. if (data === void 0) { data = null; }
  31950. if (!data) {
  31951. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31952. }
  31953. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31954. };
  31955. Geometry.prototype._applyToMesh = function (mesh) {
  31956. var numOfMeshes = this._meshes.length;
  31957. // vertexBuffers
  31958. for (var kind in this._vertexBuffers) {
  31959. if (numOfMeshes === 1) {
  31960. this._vertexBuffers[kind].create();
  31961. }
  31962. var buffer = this._vertexBuffers[kind].getBuffer();
  31963. if (buffer)
  31964. buffer.references = numOfMeshes;
  31965. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31966. if (!this._extend) {
  31967. this.updateExtend(this._vertexBuffers[kind].getData());
  31968. }
  31969. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31970. mesh._createGlobalSubMesh(false);
  31971. //bounding info was just created again, world matrix should be applied again.
  31972. mesh._updateBoundingInfo();
  31973. }
  31974. }
  31975. // indexBuffer
  31976. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31977. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31978. }
  31979. if (this._indexBuffer) {
  31980. this._indexBuffer.references = numOfMeshes;
  31981. }
  31982. };
  31983. Geometry.prototype.notifyUpdate = function (kind) {
  31984. if (this.onGeometryUpdated) {
  31985. this.onGeometryUpdated(this, kind);
  31986. }
  31987. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31988. var mesh = _a[_i];
  31989. mesh._markSubMeshesAsAttributesDirty();
  31990. }
  31991. };
  31992. Geometry.prototype.load = function (scene, onLoaded) {
  31993. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31994. return;
  31995. }
  31996. if (this.isReady()) {
  31997. if (onLoaded) {
  31998. onLoaded();
  31999. }
  32000. return;
  32001. }
  32002. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32003. this._queueLoad(scene, onLoaded);
  32004. };
  32005. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  32006. var _this = this;
  32007. if (!this.delayLoadingFile) {
  32008. return;
  32009. }
  32010. scene._addPendingData(this);
  32011. scene._loadFile(this.delayLoadingFile, function (data) {
  32012. if (!_this._delayLoadingFunction) {
  32013. return;
  32014. }
  32015. _this._delayLoadingFunction(JSON.parse(data), _this);
  32016. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32017. _this._delayInfo = [];
  32018. scene._removePendingData(_this);
  32019. var meshes = _this._meshes;
  32020. var numOfMeshes = meshes.length;
  32021. for (var index = 0; index < numOfMeshes; index++) {
  32022. _this._applyToMesh(meshes[index]);
  32023. }
  32024. if (onLoaded) {
  32025. onLoaded();
  32026. }
  32027. }, undefined, true);
  32028. };
  32029. /**
  32030. * Invert the geometry to move from a right handed system to a left handed one.
  32031. */
  32032. Geometry.prototype.toLeftHanded = function () {
  32033. // Flip faces
  32034. var tIndices = this.getIndices(false);
  32035. if (tIndices != null && tIndices.length > 0) {
  32036. for (var i = 0; i < tIndices.length; i += 3) {
  32037. var tTemp = tIndices[i + 0];
  32038. tIndices[i + 0] = tIndices[i + 2];
  32039. tIndices[i + 2] = tTemp;
  32040. }
  32041. this.setIndices(tIndices);
  32042. }
  32043. // Negate position.z
  32044. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  32045. if (tPositions != null && tPositions.length > 0) {
  32046. for (var i = 0; i < tPositions.length; i += 3) {
  32047. tPositions[i + 2] = -tPositions[i + 2];
  32048. }
  32049. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  32050. }
  32051. // Negate normal.z
  32052. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  32053. if (tNormals != null && tNormals.length > 0) {
  32054. for (var i = 0; i < tNormals.length; i += 3) {
  32055. tNormals[i + 2] = -tNormals[i + 2];
  32056. }
  32057. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  32058. }
  32059. };
  32060. // Cache
  32061. Geometry.prototype._resetPointsArrayCache = function () {
  32062. this._positions = null;
  32063. };
  32064. Geometry.prototype._generatePointsArray = function () {
  32065. if (this._positions)
  32066. return true;
  32067. this._positions = [];
  32068. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32069. if (!data) {
  32070. return false;
  32071. }
  32072. for (var index = 0; index < data.length; index += 3) {
  32073. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  32074. }
  32075. return true;
  32076. };
  32077. Geometry.prototype.isDisposed = function () {
  32078. return this._isDisposed;
  32079. };
  32080. Geometry.prototype._disposeVertexArrayObjects = function () {
  32081. if (this._vertexArrayObjects) {
  32082. for (var kind in this._vertexArrayObjects) {
  32083. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  32084. }
  32085. this._vertexArrayObjects = {};
  32086. }
  32087. };
  32088. Geometry.prototype.dispose = function () {
  32089. var meshes = this._meshes;
  32090. var numOfMeshes = meshes.length;
  32091. var index;
  32092. for (index = 0; index < numOfMeshes; index++) {
  32093. this.releaseForMesh(meshes[index]);
  32094. }
  32095. this._meshes = [];
  32096. this._disposeVertexArrayObjects();
  32097. for (var kind in this._vertexBuffers) {
  32098. this._vertexBuffers[kind].dispose();
  32099. }
  32100. this._vertexBuffers = {};
  32101. this._totalVertices = 0;
  32102. if (this._indexBuffer) {
  32103. this._engine._releaseBuffer(this._indexBuffer);
  32104. }
  32105. this._indexBuffer = null;
  32106. this._indices = [];
  32107. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32108. this.delayLoadingFile = null;
  32109. this._delayLoadingFunction = null;
  32110. this._delayInfo = [];
  32111. this._boundingInfo = null;
  32112. this._scene.removeGeometry(this);
  32113. this._isDisposed = true;
  32114. };
  32115. Geometry.prototype.copy = function (id) {
  32116. var vertexData = new BABYLON.VertexData();
  32117. vertexData.indices = [];
  32118. var indices = this.getIndices();
  32119. if (indices) {
  32120. for (var index = 0; index < indices.length; index++) {
  32121. vertexData.indices.push(indices[index]);
  32122. }
  32123. }
  32124. var updatable = false;
  32125. var stopChecking = false;
  32126. var kind;
  32127. for (kind in this._vertexBuffers) {
  32128. // using slice() to make a copy of the array and not just reference it
  32129. var data = this.getVerticesData(kind);
  32130. if (data instanceof Float32Array) {
  32131. vertexData.set(new Float32Array(data), kind);
  32132. }
  32133. else {
  32134. vertexData.set(data.slice(0), kind);
  32135. }
  32136. if (!stopChecking) {
  32137. var vb = this.getVertexBuffer(kind);
  32138. if (vb) {
  32139. updatable = vb.isUpdatable();
  32140. stopChecking = !updatable;
  32141. }
  32142. }
  32143. }
  32144. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  32145. geometry.delayLoadState = this.delayLoadState;
  32146. geometry.delayLoadingFile = this.delayLoadingFile;
  32147. geometry._delayLoadingFunction = this._delayLoadingFunction;
  32148. for (kind in this._delayInfo) {
  32149. geometry._delayInfo = geometry._delayInfo || [];
  32150. geometry._delayInfo.push(kind);
  32151. }
  32152. // Bounding info
  32153. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  32154. return geometry;
  32155. };
  32156. Geometry.prototype.serialize = function () {
  32157. var serializationObject = {};
  32158. serializationObject.id = this.id;
  32159. serializationObject.updatable = this._updatable;
  32160. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32161. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32162. }
  32163. return serializationObject;
  32164. };
  32165. Geometry.prototype.toNumberArray = function (origin) {
  32166. if (Array.isArray(origin)) {
  32167. return origin;
  32168. }
  32169. else {
  32170. return Array.prototype.slice.call(origin);
  32171. }
  32172. };
  32173. Geometry.prototype.serializeVerticeData = function () {
  32174. var serializationObject = this.serialize();
  32175. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32176. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  32177. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  32178. serializationObject.positions._updatable = true;
  32179. }
  32180. }
  32181. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32182. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  32183. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  32184. serializationObject.normals._updatable = true;
  32185. }
  32186. }
  32187. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32188. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  32189. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  32190. serializationObject.uvs._updatable = true;
  32191. }
  32192. }
  32193. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32194. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  32195. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  32196. serializationObject.uv2s._updatable = true;
  32197. }
  32198. }
  32199. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32200. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  32201. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  32202. serializationObject.uv3s._updatable = true;
  32203. }
  32204. }
  32205. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32206. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  32207. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  32208. serializationObject.uv4s._updatable = true;
  32209. }
  32210. }
  32211. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32212. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  32213. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  32214. serializationObject.uv5s._updatable = true;
  32215. }
  32216. }
  32217. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32218. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  32219. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  32220. serializationObject.uv6s._updatable = true;
  32221. }
  32222. }
  32223. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32224. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  32225. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  32226. serializationObject.colors._updatable = true;
  32227. }
  32228. }
  32229. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32230. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  32231. serializationObject.matricesIndices._isExpanded = true;
  32232. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32233. serializationObject.matricesIndices._updatable = true;
  32234. }
  32235. }
  32236. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32237. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  32238. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32239. serializationObject.matricesWeights._updatable = true;
  32240. }
  32241. }
  32242. serializationObject.indices = this.toNumberArray(this.getIndices());
  32243. return serializationObject;
  32244. };
  32245. // Statics
  32246. Geometry.ExtractFromMesh = function (mesh, id) {
  32247. var geometry = mesh._geometry;
  32248. if (!geometry) {
  32249. return null;
  32250. }
  32251. return geometry.copy(id);
  32252. };
  32253. /**
  32254. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  32255. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  32256. * Be aware Math.random() could cause collisions, but:
  32257. * "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"
  32258. */
  32259. Geometry.RandomId = function () {
  32260. return BABYLON.Tools.RandomId();
  32261. };
  32262. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  32263. var scene = mesh.getScene();
  32264. // Geometry
  32265. var geometryId = parsedGeometry.geometryId;
  32266. if (geometryId) {
  32267. var geometry = scene.getGeometryByID(geometryId);
  32268. if (geometry) {
  32269. geometry.applyToMesh(mesh);
  32270. }
  32271. }
  32272. else if (parsedGeometry instanceof ArrayBuffer) {
  32273. var binaryInfo = mesh._binaryInfo;
  32274. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  32275. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  32276. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  32277. }
  32278. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  32279. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  32280. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  32281. }
  32282. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  32283. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  32284. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  32285. }
  32286. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  32287. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  32288. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  32289. }
  32290. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  32291. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  32292. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  32293. }
  32294. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  32295. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  32296. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  32297. }
  32298. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  32299. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  32300. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  32301. }
  32302. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  32303. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  32304. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  32305. }
  32306. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  32307. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  32308. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  32309. }
  32310. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  32311. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  32312. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  32313. }
  32314. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  32315. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  32316. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  32317. }
  32318. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  32319. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  32320. mesh.setIndices(indicesData, null);
  32321. }
  32322. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  32323. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  32324. mesh.subMeshes = [];
  32325. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  32326. var materialIndex = subMeshesData[(i * 5) + 0];
  32327. var verticesStart = subMeshesData[(i * 5) + 1];
  32328. var verticesCount = subMeshesData[(i * 5) + 2];
  32329. var indexStart = subMeshesData[(i * 5) + 3];
  32330. var indexCount = subMeshesData[(i * 5) + 4];
  32331. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  32332. }
  32333. }
  32334. }
  32335. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  32336. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  32337. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  32338. if (parsedGeometry.uvs) {
  32339. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  32340. }
  32341. if (parsedGeometry.uvs2) {
  32342. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  32343. }
  32344. if (parsedGeometry.uvs3) {
  32345. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  32346. }
  32347. if (parsedGeometry.uvs4) {
  32348. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  32349. }
  32350. if (parsedGeometry.uvs5) {
  32351. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  32352. }
  32353. if (parsedGeometry.uvs6) {
  32354. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  32355. }
  32356. if (parsedGeometry.colors) {
  32357. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  32358. }
  32359. if (parsedGeometry.matricesIndices) {
  32360. if (!parsedGeometry.matricesIndices._isExpanded) {
  32361. var floatIndices = [];
  32362. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  32363. var matricesIndex = parsedGeometry.matricesIndices[i];
  32364. floatIndices.push(matricesIndex & 0x000000FF);
  32365. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32366. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32367. floatIndices.push(matricesIndex >> 24);
  32368. }
  32369. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  32370. }
  32371. else {
  32372. delete parsedGeometry.matricesIndices._isExpanded;
  32373. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  32374. }
  32375. }
  32376. if (parsedGeometry.matricesIndicesExtra) {
  32377. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  32378. var floatIndices = [];
  32379. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  32380. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  32381. floatIndices.push(matricesIndex & 0x000000FF);
  32382. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  32383. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  32384. floatIndices.push(matricesIndex >> 24);
  32385. }
  32386. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  32387. }
  32388. else {
  32389. delete parsedGeometry.matricesIndices._isExpanded;
  32390. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  32391. }
  32392. }
  32393. if (parsedGeometry.matricesWeights) {
  32394. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  32395. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  32396. }
  32397. if (parsedGeometry.matricesWeightsExtra) {
  32398. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  32399. }
  32400. mesh.setIndices(parsedGeometry.indices, null);
  32401. }
  32402. // SubMeshes
  32403. if (parsedGeometry.subMeshes) {
  32404. mesh.subMeshes = [];
  32405. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  32406. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  32407. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  32408. }
  32409. }
  32410. // Flat shading
  32411. if (mesh._shouldGenerateFlatShading) {
  32412. mesh.convertToFlatShadedMesh();
  32413. delete mesh._shouldGenerateFlatShading;
  32414. }
  32415. // Update
  32416. mesh.computeWorldMatrix(true);
  32417. // Octree
  32418. var sceneOctree = scene.selectionOctree;
  32419. if (sceneOctree !== undefined && sceneOctree !== null) {
  32420. sceneOctree.addMesh(mesh);
  32421. }
  32422. };
  32423. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32424. var epsilon = 1e-3;
  32425. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32426. return;
  32427. }
  32428. var noInfluenceBoneIndex = 0.0;
  32429. if (parsedGeometry.skeletonId > -1) {
  32430. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32431. if (!skeleton) {
  32432. return;
  32433. }
  32434. noInfluenceBoneIndex = skeleton.bones.length;
  32435. }
  32436. else {
  32437. return;
  32438. }
  32439. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32440. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32441. var matricesWeights = parsedGeometry.matricesWeights;
  32442. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32443. var influencers = parsedGeometry.numBoneInfluencer;
  32444. var size = matricesWeights.length;
  32445. for (var i = 0; i < size; i += 4) {
  32446. var weight = 0.0;
  32447. var firstZeroWeight = -1;
  32448. for (var j = 0; j < 4; j++) {
  32449. var w = matricesWeights[i + j];
  32450. weight += w;
  32451. if (w < epsilon && firstZeroWeight < 0) {
  32452. firstZeroWeight = j;
  32453. }
  32454. }
  32455. if (matricesWeightsExtra) {
  32456. for (var j = 0; j < 4; j++) {
  32457. var w = matricesWeightsExtra[i + j];
  32458. weight += w;
  32459. if (w < epsilon && firstZeroWeight < 0) {
  32460. firstZeroWeight = j + 4;
  32461. }
  32462. }
  32463. }
  32464. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32465. firstZeroWeight = influencers - 1;
  32466. }
  32467. if (weight > epsilon) {
  32468. var mweight = 1.0 / weight;
  32469. for (var j = 0; j < 4; j++) {
  32470. matricesWeights[i + j] *= mweight;
  32471. }
  32472. if (matricesWeightsExtra) {
  32473. for (var j = 0; j < 4; j++) {
  32474. matricesWeightsExtra[i + j] *= mweight;
  32475. }
  32476. }
  32477. }
  32478. else {
  32479. if (firstZeroWeight >= 4) {
  32480. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32481. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32482. }
  32483. else {
  32484. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32485. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32486. }
  32487. }
  32488. }
  32489. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32490. if (parsedGeometry.matricesWeightsExtra) {
  32491. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32492. }
  32493. };
  32494. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32495. if (scene.getGeometryByID(parsedVertexData.id)) {
  32496. return null; // null since geometry could be something else than a box...
  32497. }
  32498. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32499. if (BABYLON.Tags) {
  32500. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32501. }
  32502. if (parsedVertexData.delayLoadingFile) {
  32503. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32504. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32505. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32506. geometry._delayInfo = [];
  32507. if (parsedVertexData.hasUVs) {
  32508. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32509. }
  32510. if (parsedVertexData.hasUVs2) {
  32511. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32512. }
  32513. if (parsedVertexData.hasUVs3) {
  32514. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32515. }
  32516. if (parsedVertexData.hasUVs4) {
  32517. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32518. }
  32519. if (parsedVertexData.hasUVs5) {
  32520. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32521. }
  32522. if (parsedVertexData.hasUVs6) {
  32523. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32524. }
  32525. if (parsedVertexData.hasColors) {
  32526. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32527. }
  32528. if (parsedVertexData.hasMatricesIndices) {
  32529. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32530. }
  32531. if (parsedVertexData.hasMatricesWeights) {
  32532. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32533. }
  32534. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32535. }
  32536. else {
  32537. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32538. }
  32539. scene.pushGeometry(geometry, true);
  32540. return geometry;
  32541. };
  32542. return Geometry;
  32543. }());
  32544. BABYLON.Geometry = Geometry;
  32545. /////// Primitives //////////////////////////////////////////////
  32546. //export module Geometry.Primitives {
  32547. /// Abstract class
  32548. var _PrimitiveGeometry = /** @class */ (function (_super) {
  32549. __extends(_PrimitiveGeometry, _super);
  32550. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  32551. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32552. if (mesh === void 0) { mesh = null; }
  32553. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32554. _this._canBeRegenerated = _canBeRegenerated;
  32555. _this._beingRegenerated = true;
  32556. _this.regenerate();
  32557. _this._beingRegenerated = false;
  32558. return _this;
  32559. }
  32560. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  32561. return this._canBeRegenerated;
  32562. };
  32563. _PrimitiveGeometry.prototype.regenerate = function () {
  32564. if (!this._canBeRegenerated) {
  32565. return;
  32566. }
  32567. this._beingRegenerated = true;
  32568. this.setAllVerticesData(this._regenerateVertexData(), false);
  32569. this._beingRegenerated = false;
  32570. };
  32571. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  32572. return _super.prototype.copy.call(this, id);
  32573. };
  32574. // overrides
  32575. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  32576. if (!this._beingRegenerated) {
  32577. return;
  32578. }
  32579. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32580. };
  32581. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  32582. if (!this._beingRegenerated) {
  32583. return;
  32584. }
  32585. _super.prototype.setVerticesData.call(this, kind, data, false);
  32586. };
  32587. // to override
  32588. // protected
  32589. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  32590. throw new Error("Abstract method");
  32591. };
  32592. _PrimitiveGeometry.prototype.copy = function (id) {
  32593. throw new Error("Must be overriden in sub-classes.");
  32594. };
  32595. _PrimitiveGeometry.prototype.serialize = function () {
  32596. var serializationObject = _super.prototype.serialize.call(this);
  32597. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32598. return serializationObject;
  32599. };
  32600. return _PrimitiveGeometry;
  32601. }(Geometry));
  32602. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  32603. var RibbonGeometry = /** @class */ (function (_super) {
  32604. __extends(RibbonGeometry, _super);
  32605. // Members
  32606. function RibbonGeometry(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32607. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32608. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32609. _this.pathArray = pathArray;
  32610. _this.closeArray = closeArray;
  32611. _this.closePath = closePath;
  32612. _this.offset = offset;
  32613. _this.side = side;
  32614. return _this;
  32615. }
  32616. RibbonGeometry.prototype._regenerateVertexData = function () {
  32617. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32618. };
  32619. RibbonGeometry.prototype.copy = function (id) {
  32620. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32621. };
  32622. return RibbonGeometry;
  32623. }(_PrimitiveGeometry));
  32624. BABYLON.RibbonGeometry = RibbonGeometry;
  32625. var BoxGeometry = /** @class */ (function (_super) {
  32626. __extends(BoxGeometry, _super);
  32627. // Members
  32628. function BoxGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32629. if (mesh === void 0) { mesh = null; }
  32630. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32631. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32632. _this.size = size;
  32633. _this.side = side;
  32634. return _this;
  32635. }
  32636. BoxGeometry.prototype._regenerateVertexData = function () {
  32637. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32638. };
  32639. BoxGeometry.prototype.copy = function (id) {
  32640. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32641. };
  32642. BoxGeometry.prototype.serialize = function () {
  32643. var serializationObject = _super.prototype.serialize.call(this);
  32644. serializationObject.size = this.size;
  32645. return serializationObject;
  32646. };
  32647. BoxGeometry.Parse = function (parsedBox, scene) {
  32648. if (scene.getGeometryByID(parsedBox.id)) {
  32649. return null; // null since geometry could be something else than a box...
  32650. }
  32651. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32652. if (BABYLON.Tags) {
  32653. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32654. }
  32655. scene.pushGeometry(box, true);
  32656. return box;
  32657. };
  32658. return BoxGeometry;
  32659. }(_PrimitiveGeometry));
  32660. BABYLON.BoxGeometry = BoxGeometry;
  32661. var SphereGeometry = /** @class */ (function (_super) {
  32662. __extends(SphereGeometry, _super);
  32663. function SphereGeometry(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32664. if (mesh === void 0) { mesh = null; }
  32665. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32666. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32667. _this.segments = segments;
  32668. _this.diameter = diameter;
  32669. _this.side = side;
  32670. return _this;
  32671. }
  32672. SphereGeometry.prototype._regenerateVertexData = function () {
  32673. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32674. };
  32675. SphereGeometry.prototype.copy = function (id) {
  32676. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32677. };
  32678. SphereGeometry.prototype.serialize = function () {
  32679. var serializationObject = _super.prototype.serialize.call(this);
  32680. serializationObject.segments = this.segments;
  32681. serializationObject.diameter = this.diameter;
  32682. return serializationObject;
  32683. };
  32684. SphereGeometry.Parse = function (parsedSphere, scene) {
  32685. if (scene.getGeometryByID(parsedSphere.id)) {
  32686. return null; // null since geometry could be something else than a sphere...
  32687. }
  32688. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32689. if (BABYLON.Tags) {
  32690. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32691. }
  32692. scene.pushGeometry(sphere, true);
  32693. return sphere;
  32694. };
  32695. return SphereGeometry;
  32696. }(_PrimitiveGeometry));
  32697. BABYLON.SphereGeometry = SphereGeometry;
  32698. var DiscGeometry = /** @class */ (function (_super) {
  32699. __extends(DiscGeometry, _super);
  32700. // Members
  32701. function DiscGeometry(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32702. if (mesh === void 0) { mesh = null; }
  32703. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32704. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32705. _this.radius = radius;
  32706. _this.tessellation = tessellation;
  32707. _this.side = side;
  32708. return _this;
  32709. }
  32710. DiscGeometry.prototype._regenerateVertexData = function () {
  32711. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32712. };
  32713. DiscGeometry.prototype.copy = function (id) {
  32714. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32715. };
  32716. return DiscGeometry;
  32717. }(_PrimitiveGeometry));
  32718. BABYLON.DiscGeometry = DiscGeometry;
  32719. var CylinderGeometry = /** @class */ (function (_super) {
  32720. __extends(CylinderGeometry, _super);
  32721. function CylinderGeometry(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32722. if (subdivisions === void 0) { subdivisions = 1; }
  32723. if (mesh === void 0) { mesh = null; }
  32724. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32725. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32726. _this.height = height;
  32727. _this.diameterTop = diameterTop;
  32728. _this.diameterBottom = diameterBottom;
  32729. _this.tessellation = tessellation;
  32730. _this.subdivisions = subdivisions;
  32731. _this.side = side;
  32732. return _this;
  32733. }
  32734. CylinderGeometry.prototype._regenerateVertexData = function () {
  32735. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32736. };
  32737. CylinderGeometry.prototype.copy = function (id) {
  32738. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32739. };
  32740. CylinderGeometry.prototype.serialize = function () {
  32741. var serializationObject = _super.prototype.serialize.call(this);
  32742. serializationObject.height = this.height;
  32743. serializationObject.diameterTop = this.diameterTop;
  32744. serializationObject.diameterBottom = this.diameterBottom;
  32745. serializationObject.tessellation = this.tessellation;
  32746. return serializationObject;
  32747. };
  32748. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  32749. if (scene.getGeometryByID(parsedCylinder.id)) {
  32750. return null; // null since geometry could be something else than a cylinder...
  32751. }
  32752. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32753. if (BABYLON.Tags) {
  32754. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32755. }
  32756. scene.pushGeometry(cylinder, true);
  32757. return cylinder;
  32758. };
  32759. return CylinderGeometry;
  32760. }(_PrimitiveGeometry));
  32761. BABYLON.CylinderGeometry = CylinderGeometry;
  32762. var TorusGeometry = /** @class */ (function (_super) {
  32763. __extends(TorusGeometry, _super);
  32764. function TorusGeometry(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32765. if (mesh === void 0) { mesh = null; }
  32766. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32767. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32768. _this.diameter = diameter;
  32769. _this.thickness = thickness;
  32770. _this.tessellation = tessellation;
  32771. _this.side = side;
  32772. return _this;
  32773. }
  32774. TorusGeometry.prototype._regenerateVertexData = function () {
  32775. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32776. };
  32777. TorusGeometry.prototype.copy = function (id) {
  32778. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32779. };
  32780. TorusGeometry.prototype.serialize = function () {
  32781. var serializationObject = _super.prototype.serialize.call(this);
  32782. serializationObject.diameter = this.diameter;
  32783. serializationObject.thickness = this.thickness;
  32784. serializationObject.tessellation = this.tessellation;
  32785. return serializationObject;
  32786. };
  32787. TorusGeometry.Parse = function (parsedTorus, scene) {
  32788. if (scene.getGeometryByID(parsedTorus.id)) {
  32789. return null; // null since geometry could be something else than a torus...
  32790. }
  32791. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32792. if (BABYLON.Tags) {
  32793. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32794. }
  32795. scene.pushGeometry(torus, true);
  32796. return torus;
  32797. };
  32798. return TorusGeometry;
  32799. }(_PrimitiveGeometry));
  32800. BABYLON.TorusGeometry = TorusGeometry;
  32801. var GroundGeometry = /** @class */ (function (_super) {
  32802. __extends(GroundGeometry, _super);
  32803. function GroundGeometry(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32804. if (mesh === void 0) { mesh = null; }
  32805. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32806. _this.width = width;
  32807. _this.height = height;
  32808. _this.subdivisions = subdivisions;
  32809. return _this;
  32810. }
  32811. GroundGeometry.prototype._regenerateVertexData = function () {
  32812. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32813. };
  32814. GroundGeometry.prototype.copy = function (id) {
  32815. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32816. };
  32817. GroundGeometry.prototype.serialize = function () {
  32818. var serializationObject = _super.prototype.serialize.call(this);
  32819. serializationObject.width = this.width;
  32820. serializationObject.height = this.height;
  32821. serializationObject.subdivisions = this.subdivisions;
  32822. return serializationObject;
  32823. };
  32824. GroundGeometry.Parse = function (parsedGround, scene) {
  32825. if (scene.getGeometryByID(parsedGround.id)) {
  32826. return null; // null since geometry could be something else than a ground...
  32827. }
  32828. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32829. if (BABYLON.Tags) {
  32830. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32831. }
  32832. scene.pushGeometry(ground, true);
  32833. return ground;
  32834. };
  32835. return GroundGeometry;
  32836. }(_PrimitiveGeometry));
  32837. BABYLON.GroundGeometry = GroundGeometry;
  32838. var TiledGroundGeometry = /** @class */ (function (_super) {
  32839. __extends(TiledGroundGeometry, _super);
  32840. function TiledGroundGeometry(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32841. if (mesh === void 0) { mesh = null; }
  32842. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32843. _this.xmin = xmin;
  32844. _this.zmin = zmin;
  32845. _this.xmax = xmax;
  32846. _this.zmax = zmax;
  32847. _this.subdivisions = subdivisions;
  32848. _this.precision = precision;
  32849. return _this;
  32850. }
  32851. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  32852. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32853. };
  32854. TiledGroundGeometry.prototype.copy = function (id) {
  32855. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32856. };
  32857. return TiledGroundGeometry;
  32858. }(_PrimitiveGeometry));
  32859. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  32860. var PlaneGeometry = /** @class */ (function (_super) {
  32861. __extends(PlaneGeometry, _super);
  32862. function PlaneGeometry(id, scene, size, canBeRegenerated, mesh, side) {
  32863. if (mesh === void 0) { mesh = null; }
  32864. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32865. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32866. _this.size = size;
  32867. _this.side = side;
  32868. return _this;
  32869. }
  32870. PlaneGeometry.prototype._regenerateVertexData = function () {
  32871. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32872. };
  32873. PlaneGeometry.prototype.copy = function (id) {
  32874. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32875. };
  32876. PlaneGeometry.prototype.serialize = function () {
  32877. var serializationObject = _super.prototype.serialize.call(this);
  32878. serializationObject.size = this.size;
  32879. return serializationObject;
  32880. };
  32881. PlaneGeometry.Parse = function (parsedPlane, scene) {
  32882. if (scene.getGeometryByID(parsedPlane.id)) {
  32883. return null; // null since geometry could be something else than a ground...
  32884. }
  32885. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32886. if (BABYLON.Tags) {
  32887. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32888. }
  32889. scene.pushGeometry(plane, true);
  32890. return plane;
  32891. };
  32892. return PlaneGeometry;
  32893. }(_PrimitiveGeometry));
  32894. BABYLON.PlaneGeometry = PlaneGeometry;
  32895. var TorusKnotGeometry = /** @class */ (function (_super) {
  32896. __extends(TorusKnotGeometry, _super);
  32897. function TorusKnotGeometry(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32898. if (mesh === void 0) { mesh = null; }
  32899. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32900. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32901. _this.radius = radius;
  32902. _this.tube = tube;
  32903. _this.radialSegments = radialSegments;
  32904. _this.tubularSegments = tubularSegments;
  32905. _this.p = p;
  32906. _this.q = q;
  32907. _this.side = side;
  32908. return _this;
  32909. }
  32910. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  32911. 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 });
  32912. };
  32913. TorusKnotGeometry.prototype.copy = function (id) {
  32914. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32915. };
  32916. TorusKnotGeometry.prototype.serialize = function () {
  32917. var serializationObject = _super.prototype.serialize.call(this);
  32918. serializationObject.radius = this.radius;
  32919. serializationObject.tube = this.tube;
  32920. serializationObject.radialSegments = this.radialSegments;
  32921. serializationObject.tubularSegments = this.tubularSegments;
  32922. serializationObject.p = this.p;
  32923. serializationObject.q = this.q;
  32924. return serializationObject;
  32925. };
  32926. ;
  32927. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  32928. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32929. return null; // null since geometry could be something else than a ground...
  32930. }
  32931. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32932. if (BABYLON.Tags) {
  32933. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32934. }
  32935. scene.pushGeometry(torusKnot, true);
  32936. return torusKnot;
  32937. };
  32938. return TorusKnotGeometry;
  32939. }(_PrimitiveGeometry));
  32940. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  32941. //}
  32942. })(BABYLON || (BABYLON = {}));
  32943. //# sourceMappingURL=babylon.geometry.js.map
  32944. var BABYLON;
  32945. (function (BABYLON) {
  32946. var PostProcessManager = /** @class */ (function () {
  32947. function PostProcessManager(scene) {
  32948. this._vertexBuffers = {};
  32949. this._scene = scene;
  32950. }
  32951. PostProcessManager.prototype._prepareBuffers = function () {
  32952. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32953. return;
  32954. }
  32955. // VBO
  32956. var vertices = [];
  32957. vertices.push(1, 1);
  32958. vertices.push(-1, 1);
  32959. vertices.push(-1, -1);
  32960. vertices.push(1, -1);
  32961. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32962. this._buildIndexBuffer();
  32963. };
  32964. PostProcessManager.prototype._buildIndexBuffer = function () {
  32965. // Indices
  32966. var indices = [];
  32967. indices.push(0);
  32968. indices.push(1);
  32969. indices.push(2);
  32970. indices.push(0);
  32971. indices.push(2);
  32972. indices.push(3);
  32973. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32974. };
  32975. PostProcessManager.prototype._rebuild = function () {
  32976. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32977. if (!vb) {
  32978. return;
  32979. }
  32980. vb._rebuild();
  32981. this._buildIndexBuffer();
  32982. };
  32983. // Methods
  32984. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32985. if (sourceTexture === void 0) { sourceTexture = null; }
  32986. if (postProcesses === void 0) { postProcesses = null; }
  32987. var camera = this._scene.activeCamera;
  32988. if (!camera) {
  32989. return false;
  32990. }
  32991. var postProcesses = postProcesses || camera._postProcesses;
  32992. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32993. return false;
  32994. }
  32995. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32996. return true;
  32997. };
  32998. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32999. if (targetTexture === void 0) { targetTexture = null; }
  33000. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33001. var engine = this._scene.getEngine();
  33002. for (var index = 0; index < postProcesses.length; index++) {
  33003. if (index < postProcesses.length - 1) {
  33004. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  33005. }
  33006. else {
  33007. if (targetTexture) {
  33008. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  33009. }
  33010. else {
  33011. engine.restoreDefaultFramebuffer();
  33012. }
  33013. }
  33014. var pp = postProcesses[index];
  33015. var effect = pp.apply();
  33016. if (effect) {
  33017. pp.onBeforeRenderObservable.notifyObservers(effect);
  33018. // VBOs
  33019. this._prepareBuffers();
  33020. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33021. // Draw order
  33022. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33023. pp.onAfterRenderObservable.notifyObservers(effect);
  33024. }
  33025. }
  33026. // Restore depth buffer
  33027. engine.setDepthBuffer(true);
  33028. engine.setDepthWrite(true);
  33029. };
  33030. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  33031. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  33032. var camera = this._scene.activeCamera;
  33033. if (!camera) {
  33034. return;
  33035. }
  33036. postProcesses = postProcesses || camera._postProcesses;
  33037. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  33038. return;
  33039. }
  33040. var engine = this._scene.getEngine();
  33041. for (var index = 0, len = postProcesses.length; index < len; index++) {
  33042. if (index < len - 1) {
  33043. postProcesses[index + 1].activate(camera, targetTexture);
  33044. }
  33045. else {
  33046. if (targetTexture) {
  33047. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  33048. }
  33049. else {
  33050. engine.restoreDefaultFramebuffer();
  33051. }
  33052. }
  33053. if (doNotPresent) {
  33054. break;
  33055. }
  33056. var pp = postProcesses[index];
  33057. var effect = pp.apply();
  33058. if (effect) {
  33059. pp.onBeforeRenderObservable.notifyObservers(effect);
  33060. // VBOs
  33061. this._prepareBuffers();
  33062. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  33063. // Draw order
  33064. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  33065. pp.onAfterRenderObservable.notifyObservers(effect);
  33066. }
  33067. }
  33068. // Restore states
  33069. engine.setDepthBuffer(true);
  33070. engine.setDepthWrite(true);
  33071. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  33072. };
  33073. PostProcessManager.prototype.dispose = function () {
  33074. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33075. if (buffer) {
  33076. buffer.dispose();
  33077. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33078. }
  33079. if (this._indexBuffer) {
  33080. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33081. this._indexBuffer = null;
  33082. }
  33083. };
  33084. return PostProcessManager;
  33085. }());
  33086. BABYLON.PostProcessManager = PostProcessManager;
  33087. })(BABYLON || (BABYLON = {}));
  33088. //# sourceMappingURL=babylon.postProcessManager.js.map
  33089. var BABYLON;
  33090. (function (BABYLON) {
  33091. /**
  33092. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  33093. */
  33094. var PerformanceMonitor = /** @class */ (function () {
  33095. /**
  33096. * constructor
  33097. * @param frameSampleSize The number of samples required to saturate the sliding window
  33098. */
  33099. function PerformanceMonitor(frameSampleSize) {
  33100. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  33101. this._enabled = true;
  33102. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  33103. }
  33104. /**
  33105. * Samples current frame
  33106. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  33107. */
  33108. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  33109. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  33110. if (!this._enabled)
  33111. return;
  33112. if (this._lastFrameTimeMs != null) {
  33113. var dt = timeMs - this._lastFrameTimeMs;
  33114. this._rollingFrameTime.add(dt);
  33115. }
  33116. this._lastFrameTimeMs = timeMs;
  33117. };
  33118. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  33119. /**
  33120. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33121. * @return Average frame time in milliseconds
  33122. */
  33123. get: function () {
  33124. return this._rollingFrameTime.average;
  33125. },
  33126. enumerable: true,
  33127. configurable: true
  33128. });
  33129. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  33130. /**
  33131. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  33132. * @return Frame time variance in milliseconds squared
  33133. */
  33134. get: function () {
  33135. return this._rollingFrameTime.variance;
  33136. },
  33137. enumerable: true,
  33138. configurable: true
  33139. });
  33140. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  33141. /**
  33142. * Returns the frame time of the most recent frame
  33143. * @return Frame time in milliseconds
  33144. */
  33145. get: function () {
  33146. return this._rollingFrameTime.history(0);
  33147. },
  33148. enumerable: true,
  33149. configurable: true
  33150. });
  33151. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  33152. /**
  33153. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  33154. * @return Framerate in frames per second
  33155. */
  33156. get: function () {
  33157. return 1000.0 / this._rollingFrameTime.average;
  33158. },
  33159. enumerable: true,
  33160. configurable: true
  33161. });
  33162. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  33163. /**
  33164. * Returns the average framerate in frames per second using the most recent frame time
  33165. * @return Framerate in frames per second
  33166. */
  33167. get: function () {
  33168. var history = this._rollingFrameTime.history(0);
  33169. if (history === 0) {
  33170. return 0;
  33171. }
  33172. return 1000.0 / history;
  33173. },
  33174. enumerable: true,
  33175. configurable: true
  33176. });
  33177. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  33178. /**
  33179. * Returns true if enough samples have been taken to completely fill the sliding window
  33180. * @return true if saturated
  33181. */
  33182. get: function () {
  33183. return this._rollingFrameTime.isSaturated();
  33184. },
  33185. enumerable: true,
  33186. configurable: true
  33187. });
  33188. /**
  33189. * Enables contributions to the sliding window sample set
  33190. */
  33191. PerformanceMonitor.prototype.enable = function () {
  33192. this._enabled = true;
  33193. };
  33194. /**
  33195. * Disables contributions to the sliding window sample set
  33196. * Samples will not be interpolated over the disabled period
  33197. */
  33198. PerformanceMonitor.prototype.disable = function () {
  33199. this._enabled = false;
  33200. //clear last sample to avoid interpolating over the disabled period when next enabled
  33201. this._lastFrameTimeMs = null;
  33202. };
  33203. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  33204. /**
  33205. * Returns true if sampling is enabled
  33206. * @return true if enabled
  33207. */
  33208. get: function () {
  33209. return this._enabled;
  33210. },
  33211. enumerable: true,
  33212. configurable: true
  33213. });
  33214. /**
  33215. * Resets performance monitor
  33216. */
  33217. PerformanceMonitor.prototype.reset = function () {
  33218. //clear last sample to avoid interpolating over the disabled period when next enabled
  33219. this._lastFrameTimeMs = null;
  33220. //wipe record
  33221. this._rollingFrameTime.reset();
  33222. };
  33223. return PerformanceMonitor;
  33224. }());
  33225. BABYLON.PerformanceMonitor = PerformanceMonitor;
  33226. /**
  33227. * RollingAverage
  33228. *
  33229. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  33230. */
  33231. var RollingAverage = /** @class */ (function () {
  33232. /**
  33233. * constructor
  33234. * @param length The number of samples required to saturate the sliding window
  33235. */
  33236. function RollingAverage(length) {
  33237. this._samples = new Array(length);
  33238. this.reset();
  33239. }
  33240. /**
  33241. * Adds a sample to the sample set
  33242. * @param v The sample value
  33243. */
  33244. RollingAverage.prototype.add = function (v) {
  33245. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  33246. var delta;
  33247. //we need to check if we've already wrapped round
  33248. if (this.isSaturated()) {
  33249. //remove bottom of stack from mean
  33250. var bottomValue = this._samples[this._pos];
  33251. delta = bottomValue - this.average;
  33252. this.average -= delta / (this._sampleCount - 1);
  33253. this._m2 -= delta * (bottomValue - this.average);
  33254. }
  33255. else {
  33256. this._sampleCount++;
  33257. }
  33258. //add new value to mean
  33259. delta = v - this.average;
  33260. this.average += delta / (this._sampleCount);
  33261. this._m2 += delta * (v - this.average);
  33262. //set the new variance
  33263. this.variance = this._m2 / (this._sampleCount - 1);
  33264. this._samples[this._pos] = v;
  33265. this._pos++;
  33266. this._pos %= this._samples.length; //positive wrap around
  33267. };
  33268. /**
  33269. * Returns previously added values or null if outside of history or outside the sliding window domain
  33270. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  33271. * @return Value previously recorded with add() or null if outside of range
  33272. */
  33273. RollingAverage.prototype.history = function (i) {
  33274. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  33275. return 0;
  33276. }
  33277. var i0 = this._wrapPosition(this._pos - 1.0);
  33278. return this._samples[this._wrapPosition(i0 - i)];
  33279. };
  33280. /**
  33281. * Returns true if enough samples have been taken to completely fill the sliding window
  33282. * @return true if sample-set saturated
  33283. */
  33284. RollingAverage.prototype.isSaturated = function () {
  33285. return this._sampleCount >= this._samples.length;
  33286. };
  33287. /**
  33288. * Resets the rolling average (equivalent to 0 samples taken so far)
  33289. */
  33290. RollingAverage.prototype.reset = function () {
  33291. this.average = 0;
  33292. this.variance = 0;
  33293. this._sampleCount = 0;
  33294. this._pos = 0;
  33295. this._m2 = 0;
  33296. };
  33297. /**
  33298. * Wraps a value around the sample range boundaries
  33299. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  33300. * @return Wrapped position in sample range
  33301. */
  33302. RollingAverage.prototype._wrapPosition = function (i) {
  33303. var max = this._samples.length;
  33304. return ((i % max) + max) % max;
  33305. };
  33306. return RollingAverage;
  33307. }());
  33308. BABYLON.RollingAverage = RollingAverage;
  33309. })(BABYLON || (BABYLON = {}));
  33310. //# sourceMappingURL=babylon.performanceMonitor.js.map
  33311. var BABYLON;
  33312. (function (BABYLON) {
  33313. /**
  33314. * This groups together the common properties used for image processing either in direct forward pass
  33315. * or through post processing effect depending on the use of the image processing pipeline in your scene
  33316. * or not.
  33317. */
  33318. var ImageProcessingConfiguration = /** @class */ (function () {
  33319. function ImageProcessingConfiguration() {
  33320. /**
  33321. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  33322. */
  33323. this.colorCurves = new BABYLON.ColorCurves();
  33324. this._colorCurvesEnabled = false;
  33325. this._colorGradingEnabled = false;
  33326. this._colorGradingWithGreenDepth = true;
  33327. this._colorGradingBGR = true;
  33328. this._exposure = 1.0;
  33329. this._toneMappingEnabled = false;
  33330. this._contrast = 1.0;
  33331. /**
  33332. * Vignette stretch size.
  33333. */
  33334. this.vignetteStretch = 0;
  33335. /**
  33336. * Vignette centre X Offset.
  33337. */
  33338. this.vignetteCentreX = 0;
  33339. /**
  33340. * Vignette centre Y Offset.
  33341. */
  33342. this.vignetteCentreY = 0;
  33343. /**
  33344. * Vignette weight or intensity of the vignette effect.
  33345. */
  33346. this.vignetteWeight = 1.5;
  33347. /**
  33348. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  33349. * if vignetteEnabled is set to true.
  33350. */
  33351. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  33352. /**
  33353. * Camera field of view used by the Vignette effect.
  33354. */
  33355. this.vignetteCameraFov = 0.5;
  33356. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  33357. this._vignetteEnabled = false;
  33358. this._applyByPostProcess = false;
  33359. this._isEnabled = true;
  33360. /**
  33361. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  33362. * @type {BABYLON.Observable}
  33363. */
  33364. this.onUpdateParameters = new BABYLON.Observable();
  33365. }
  33366. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  33367. /**
  33368. * Gets wether the color curves effect is enabled.
  33369. */
  33370. get: function () {
  33371. return this._colorCurvesEnabled;
  33372. },
  33373. /**
  33374. * Sets wether the color curves effect is enabled.
  33375. */
  33376. set: function (value) {
  33377. if (this._colorCurvesEnabled === value) {
  33378. return;
  33379. }
  33380. this._colorCurvesEnabled = value;
  33381. this._updateParameters();
  33382. },
  33383. enumerable: true,
  33384. configurable: true
  33385. });
  33386. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  33387. /**
  33388. * Gets wether the color grading effect is enabled.
  33389. */
  33390. get: function () {
  33391. return this._colorGradingEnabled;
  33392. },
  33393. /**
  33394. * Sets wether the color grading effect is enabled.
  33395. */
  33396. set: function (value) {
  33397. if (this._colorGradingEnabled === value) {
  33398. return;
  33399. }
  33400. this._colorGradingEnabled = value;
  33401. this._updateParameters();
  33402. },
  33403. enumerable: true,
  33404. configurable: true
  33405. });
  33406. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  33407. /**
  33408. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  33409. */
  33410. get: function () {
  33411. return this._colorGradingWithGreenDepth;
  33412. },
  33413. /**
  33414. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  33415. */
  33416. set: function (value) {
  33417. if (this._colorGradingWithGreenDepth === value) {
  33418. return;
  33419. }
  33420. this._colorGradingWithGreenDepth = value;
  33421. this._updateParameters();
  33422. },
  33423. enumerable: true,
  33424. configurable: true
  33425. });
  33426. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33427. /**
  33428. * Gets wether the color grading texture contains BGR values.
  33429. */
  33430. get: function () {
  33431. return this._colorGradingBGR;
  33432. },
  33433. /**
  33434. * Sets wether the color grading texture contains BGR values.
  33435. */
  33436. set: function (value) {
  33437. if (this._colorGradingBGR === value) {
  33438. return;
  33439. }
  33440. this._colorGradingBGR = value;
  33441. this._updateParameters();
  33442. },
  33443. enumerable: true,
  33444. configurable: true
  33445. });
  33446. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33447. /**
  33448. * Gets the Exposure used in the effect.
  33449. */
  33450. get: function () {
  33451. return this._exposure;
  33452. },
  33453. /**
  33454. * Sets the Exposure used in the effect.
  33455. */
  33456. set: function (value) {
  33457. if (this._exposure === value) {
  33458. return;
  33459. }
  33460. this._exposure = value;
  33461. this._updateParameters();
  33462. },
  33463. enumerable: true,
  33464. configurable: true
  33465. });
  33466. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33467. /**
  33468. * Gets wether the tone mapping effect is enabled.
  33469. */
  33470. get: function () {
  33471. return this._toneMappingEnabled;
  33472. },
  33473. /**
  33474. * Sets wether the tone mapping effect is enabled.
  33475. */
  33476. set: function (value) {
  33477. if (this._toneMappingEnabled === value) {
  33478. return;
  33479. }
  33480. this._toneMappingEnabled = value;
  33481. this._updateParameters();
  33482. },
  33483. enumerable: true,
  33484. configurable: true
  33485. });
  33486. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33487. /**
  33488. * Gets the contrast used in the effect.
  33489. */
  33490. get: function () {
  33491. return this._contrast;
  33492. },
  33493. /**
  33494. * Sets the contrast used in the effect.
  33495. */
  33496. set: function (value) {
  33497. if (this._contrast === value) {
  33498. return;
  33499. }
  33500. this._contrast = value;
  33501. this._updateParameters();
  33502. },
  33503. enumerable: true,
  33504. configurable: true
  33505. });
  33506. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33507. /**
  33508. * Gets the vignette blend mode allowing different kind of effect.
  33509. */
  33510. get: function () {
  33511. return this._vignetteBlendMode;
  33512. },
  33513. /**
  33514. * Sets the vignette blend mode allowing different kind of effect.
  33515. */
  33516. set: function (value) {
  33517. if (this._vignetteBlendMode === value) {
  33518. return;
  33519. }
  33520. this._vignetteBlendMode = value;
  33521. this._updateParameters();
  33522. },
  33523. enumerable: true,
  33524. configurable: true
  33525. });
  33526. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33527. /**
  33528. * Gets wether the vignette effect is enabled.
  33529. */
  33530. get: function () {
  33531. return this._vignetteEnabled;
  33532. },
  33533. /**
  33534. * Sets wether the vignette effect is enabled.
  33535. */
  33536. set: function (value) {
  33537. if (this._vignetteEnabled === value) {
  33538. return;
  33539. }
  33540. this._vignetteEnabled = value;
  33541. this._updateParameters();
  33542. },
  33543. enumerable: true,
  33544. configurable: true
  33545. });
  33546. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33547. /**
  33548. * Gets wether the image processing is applied through a post process or not.
  33549. */
  33550. get: function () {
  33551. return this._applyByPostProcess;
  33552. },
  33553. /**
  33554. * Sets wether the image processing is applied through a post process or not.
  33555. */
  33556. set: function (value) {
  33557. if (this._applyByPostProcess === value) {
  33558. return;
  33559. }
  33560. this._applyByPostProcess = value;
  33561. this._updateParameters();
  33562. },
  33563. enumerable: true,
  33564. configurable: true
  33565. });
  33566. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33567. /**
  33568. * Gets wether the image processing is enabled or not.
  33569. */
  33570. get: function () {
  33571. return this._isEnabled;
  33572. },
  33573. /**
  33574. * Sets wether the image processing is enabled or not.
  33575. */
  33576. set: function (value) {
  33577. if (this._isEnabled === value) {
  33578. return;
  33579. }
  33580. this._isEnabled = value;
  33581. this._updateParameters();
  33582. },
  33583. enumerable: true,
  33584. configurable: true
  33585. });
  33586. /**
  33587. * Method called each time the image processing information changes requires to recompile the effect.
  33588. */
  33589. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33590. this.onUpdateParameters.notifyObservers(this);
  33591. };
  33592. ImageProcessingConfiguration.prototype.getClassName = function () {
  33593. return "ImageProcessingConfiguration";
  33594. };
  33595. /**
  33596. * Prepare the list of uniforms associated with the Image Processing effects.
  33597. * @param uniformsList The list of uniforms used in the effect
  33598. * @param defines the list of defines currently in use
  33599. */
  33600. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33601. if (defines.EXPOSURE) {
  33602. uniforms.push("exposureLinear");
  33603. }
  33604. if (defines.CONTRAST) {
  33605. uniforms.push("contrast");
  33606. }
  33607. if (defines.COLORGRADING) {
  33608. uniforms.push("colorTransformSettings");
  33609. }
  33610. if (defines.VIGNETTE) {
  33611. uniforms.push("vInverseScreenSize");
  33612. uniforms.push("vignetteSettings1");
  33613. uniforms.push("vignetteSettings2");
  33614. }
  33615. if (defines.COLORCURVES) {
  33616. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33617. }
  33618. };
  33619. /**
  33620. * Prepare the list of samplers associated with the Image Processing effects.
  33621. * @param uniformsList The list of uniforms used in the effect
  33622. * @param defines the list of defines currently in use
  33623. */
  33624. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33625. if (defines.COLORGRADING) {
  33626. samplersList.push("txColorTransform");
  33627. }
  33628. };
  33629. /**
  33630. * Prepare the list of defines associated to the shader.
  33631. * @param defines the list of defines to complete
  33632. */
  33633. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33634. if (forPostProcess === void 0) { forPostProcess = false; }
  33635. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33636. defines.VIGNETTE = false;
  33637. defines.TONEMAPPING = false;
  33638. defines.CONTRAST = false;
  33639. defines.EXPOSURE = false;
  33640. defines.COLORCURVES = false;
  33641. defines.COLORGRADING = false;
  33642. defines.COLORGRADING3D = false;
  33643. defines.IMAGEPROCESSING = false;
  33644. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33645. return;
  33646. }
  33647. defines.VIGNETTE = this.vignetteEnabled;
  33648. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33649. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33650. defines.TONEMAPPING = this.toneMappingEnabled;
  33651. defines.CONTRAST = (this.contrast !== 1.0);
  33652. defines.EXPOSURE = (this.exposure !== 1.0);
  33653. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33654. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33655. if (defines.COLORGRADING) {
  33656. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33657. }
  33658. else {
  33659. defines.COLORGRADING3D = false;
  33660. }
  33661. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33662. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33663. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33664. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33665. };
  33666. /**
  33667. * Returns true if all the image processing information are ready.
  33668. */
  33669. ImageProcessingConfiguration.prototype.isReady = function () {
  33670. // Color Grading texure can not be none blocking.
  33671. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33672. };
  33673. /**
  33674. * Binds the image processing to the shader.
  33675. * @param effect The effect to bind to
  33676. */
  33677. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33678. if (aspectRatio === void 0) { aspectRatio = 1; }
  33679. // Color Curves
  33680. if (this._colorCurvesEnabled && this.colorCurves) {
  33681. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33682. }
  33683. // Vignette
  33684. if (this._vignetteEnabled) {
  33685. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33686. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33687. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33688. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33689. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33690. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33691. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33692. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33693. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33694. var vignettePower = -2.0 * this.vignetteWeight;
  33695. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33696. }
  33697. // Exposure
  33698. effect.setFloat("exposureLinear", this.exposure);
  33699. // Contrast
  33700. effect.setFloat("contrast", this.contrast);
  33701. // Color transform settings
  33702. if (this.colorGradingTexture) {
  33703. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33704. var textureSize = this.colorGradingTexture.getSize().height;
  33705. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33706. 0.5 / textureSize, // textureOffset
  33707. textureSize, // textureSize
  33708. this.colorGradingTexture.level // weight
  33709. );
  33710. }
  33711. };
  33712. /**
  33713. * Clones the current image processing instance.
  33714. * @return The cloned image processing
  33715. */
  33716. ImageProcessingConfiguration.prototype.clone = function () {
  33717. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33718. };
  33719. /**
  33720. * Serializes the current image processing instance to a json representation.
  33721. * @return a JSON representation
  33722. */
  33723. ImageProcessingConfiguration.prototype.serialize = function () {
  33724. return BABYLON.SerializationHelper.Serialize(this);
  33725. };
  33726. /**
  33727. * Parses the image processing from a json representation.
  33728. * @param source the JSON source to parse
  33729. * @return The parsed image processing
  33730. */
  33731. ImageProcessingConfiguration.Parse = function (source) {
  33732. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33733. };
  33734. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33735. /**
  33736. * Used to apply the vignette as a mix with the pixel color.
  33737. */
  33738. get: function () {
  33739. return this._VIGNETTEMODE_MULTIPLY;
  33740. },
  33741. enumerable: true,
  33742. configurable: true
  33743. });
  33744. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33745. /**
  33746. * Used to apply the vignette as a replacement of the pixel color.
  33747. */
  33748. get: function () {
  33749. return this._VIGNETTEMODE_OPAQUE;
  33750. },
  33751. enumerable: true,
  33752. configurable: true
  33753. });
  33754. // Static constants associated to the image processing.
  33755. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33756. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33757. __decorate([
  33758. BABYLON.serializeAsColorCurves()
  33759. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33760. __decorate([
  33761. BABYLON.serialize()
  33762. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33763. __decorate([
  33764. BABYLON.serializeAsTexture()
  33765. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33766. __decorate([
  33767. BABYLON.serialize()
  33768. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33769. __decorate([
  33770. BABYLON.serialize()
  33771. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33772. __decorate([
  33773. BABYLON.serialize()
  33774. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33775. __decorate([
  33776. BABYLON.serialize()
  33777. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33778. __decorate([
  33779. BABYLON.serialize()
  33780. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33781. __decorate([
  33782. BABYLON.serialize()
  33783. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33784. __decorate([
  33785. BABYLON.serialize()
  33786. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33787. __decorate([
  33788. BABYLON.serialize()
  33789. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33790. __decorate([
  33791. BABYLON.serialize()
  33792. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33793. __decorate([
  33794. BABYLON.serialize()
  33795. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33796. __decorate([
  33797. BABYLON.serializeAsColor4()
  33798. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33799. __decorate([
  33800. BABYLON.serialize()
  33801. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33802. __decorate([
  33803. BABYLON.serialize()
  33804. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33805. __decorate([
  33806. BABYLON.serialize()
  33807. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33808. __decorate([
  33809. BABYLON.serialize()
  33810. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33811. __decorate([
  33812. BABYLON.serialize()
  33813. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33814. return ImageProcessingConfiguration;
  33815. }());
  33816. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33817. })(BABYLON || (BABYLON = {}));
  33818. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33819. var BABYLON;
  33820. (function (BABYLON) {
  33821. /**
  33822. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33823. * It can help converting any input color in a desired output one. This can then be used to create effects
  33824. * from sepia, black and white to sixties or futuristic rendering...
  33825. *
  33826. * The only supported format is currently 3dl.
  33827. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33828. */
  33829. var ColorGradingTexture = /** @class */ (function (_super) {
  33830. __extends(ColorGradingTexture, _super);
  33831. /**
  33832. * Instantiates a ColorGradingTexture from the following parameters.
  33833. *
  33834. * @param url The location of the color gradind data (currently only supporting 3dl)
  33835. * @param scene The scene the texture will be used in
  33836. */
  33837. function ColorGradingTexture(url, scene) {
  33838. var _this = _super.call(this, scene) || this;
  33839. if (!url) {
  33840. return _this;
  33841. }
  33842. _this._engine = scene.getEngine();
  33843. _this._textureMatrix = BABYLON.Matrix.Identity();
  33844. _this.name = url;
  33845. _this.url = url;
  33846. _this.hasAlpha = false;
  33847. _this.isCube = false;
  33848. _this.is3D = _this._engine.webGLVersion > 1;
  33849. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33850. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33851. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33852. _this.anisotropicFilteringLevel = 1;
  33853. _this._texture = _this._getFromCache(url, true);
  33854. if (!_this._texture) {
  33855. if (!scene.useDelayedTextureLoading) {
  33856. _this.loadTexture();
  33857. }
  33858. else {
  33859. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33860. }
  33861. }
  33862. return _this;
  33863. }
  33864. /**
  33865. * Returns the texture matrix used in most of the material.
  33866. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33867. */
  33868. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33869. return this._textureMatrix;
  33870. };
  33871. /**
  33872. * Occurs when the file being loaded is a .3dl LUT file.
  33873. */
  33874. ColorGradingTexture.prototype.load3dlTexture = function () {
  33875. var engine = this._engine;
  33876. var texture;
  33877. if (engine.webGLVersion === 1) {
  33878. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33879. }
  33880. else {
  33881. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33882. }
  33883. this._texture = texture;
  33884. var callback = function (text) {
  33885. if (typeof text !== "string") {
  33886. return;
  33887. }
  33888. var data = null;
  33889. var tempData = null;
  33890. var line;
  33891. var lines = text.split('\n');
  33892. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33893. var maxColor = 0;
  33894. for (var i = 0; i < lines.length; i++) {
  33895. line = lines[i];
  33896. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33897. continue;
  33898. if (line.indexOf('#') === 0)
  33899. continue;
  33900. var words = line.split(" ");
  33901. if (size === 0) {
  33902. // Number of space + one
  33903. size = words.length;
  33904. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33905. tempData = new Float32Array(size * size * size * 4);
  33906. continue;
  33907. }
  33908. if (size != 0) {
  33909. var r = Math.max(parseInt(words[0]), 0);
  33910. var g = Math.max(parseInt(words[1]), 0);
  33911. var b = Math.max(parseInt(words[2]), 0);
  33912. maxColor = Math.max(r, maxColor);
  33913. maxColor = Math.max(g, maxColor);
  33914. maxColor = Math.max(b, maxColor);
  33915. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33916. if (tempData) {
  33917. tempData[pixelStorageIndex + 0] = r;
  33918. tempData[pixelStorageIndex + 1] = g;
  33919. tempData[pixelStorageIndex + 2] = b;
  33920. }
  33921. pixelIndexSlice++;
  33922. if (pixelIndexSlice % size == 0) {
  33923. pixelIndexH++;
  33924. pixelIndexSlice = 0;
  33925. if (pixelIndexH % size == 0) {
  33926. pixelIndexW++;
  33927. pixelIndexH = 0;
  33928. }
  33929. }
  33930. }
  33931. }
  33932. if (tempData && data) {
  33933. for (var i = 0; i < tempData.length; i++) {
  33934. if (i > 0 && (i + 1) % 4 === 0) {
  33935. data[i] = 255;
  33936. }
  33937. else {
  33938. var value = tempData[i];
  33939. data[i] = (value / maxColor * 255);
  33940. }
  33941. }
  33942. }
  33943. if (texture.is3D) {
  33944. texture.updateSize(size, size, size);
  33945. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33946. }
  33947. else {
  33948. texture.updateSize(size * size, size);
  33949. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33950. }
  33951. };
  33952. var scene = this.getScene();
  33953. if (scene) {
  33954. scene._loadFile(this.url, callback);
  33955. }
  33956. else {
  33957. this._engine._loadFile(this.url, callback);
  33958. }
  33959. return this._texture;
  33960. };
  33961. /**
  33962. * Starts the loading process of the texture.
  33963. */
  33964. ColorGradingTexture.prototype.loadTexture = function () {
  33965. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33966. this.load3dlTexture();
  33967. }
  33968. };
  33969. /**
  33970. * Clones the color gradind texture.
  33971. */
  33972. ColorGradingTexture.prototype.clone = function () {
  33973. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33974. // Base texture
  33975. newTexture.level = this.level;
  33976. return newTexture;
  33977. };
  33978. /**
  33979. * Called during delayed load for textures.
  33980. */
  33981. ColorGradingTexture.prototype.delayLoad = function () {
  33982. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33983. return;
  33984. }
  33985. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33986. this._texture = this._getFromCache(this.url, true);
  33987. if (!this._texture) {
  33988. this.loadTexture();
  33989. }
  33990. };
  33991. /**
  33992. * Parses a color grading texture serialized by Babylon.
  33993. * @param parsedTexture The texture information being parsedTexture
  33994. * @param scene The scene to load the texture in
  33995. * @param rootUrl The root url of the data assets to load
  33996. * @return A color gradind texture
  33997. */
  33998. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33999. var texture = null;
  34000. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  34001. texture = new ColorGradingTexture(parsedTexture.name, scene);
  34002. texture.name = parsedTexture.name;
  34003. texture.level = parsedTexture.level;
  34004. }
  34005. return texture;
  34006. };
  34007. /**
  34008. * Serializes the LUT texture to json format.
  34009. */
  34010. ColorGradingTexture.prototype.serialize = function () {
  34011. if (!this.name) {
  34012. return null;
  34013. }
  34014. var serializationObject = {};
  34015. serializationObject.name = this.name;
  34016. serializationObject.level = this.level;
  34017. serializationObject.customType = "BABYLON.ColorGradingTexture";
  34018. return serializationObject;
  34019. };
  34020. /**
  34021. * Empty line regex stored for GC.
  34022. */
  34023. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  34024. return ColorGradingTexture;
  34025. }(BABYLON.BaseTexture));
  34026. BABYLON.ColorGradingTexture = ColorGradingTexture;
  34027. })(BABYLON || (BABYLON = {}));
  34028. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  34029. var BABYLON;
  34030. (function (BABYLON) {
  34031. /**
  34032. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34033. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34034. * 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;
  34035. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34036. */
  34037. var ColorCurves = /** @class */ (function () {
  34038. function ColorCurves() {
  34039. this._dirty = true;
  34040. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  34041. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  34042. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34043. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  34044. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  34045. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  34046. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  34047. this._globalHue = 30;
  34048. this._globalDensity = 0;
  34049. this._globalSaturation = 0;
  34050. this._globalExposure = 0;
  34051. this._highlightsHue = 30;
  34052. this._highlightsDensity = 0;
  34053. this._highlightsSaturation = 0;
  34054. this._highlightsExposure = 0;
  34055. this._midtonesHue = 30;
  34056. this._midtonesDensity = 0;
  34057. this._midtonesSaturation = 0;
  34058. this._midtonesExposure = 0;
  34059. this._shadowsHue = 30;
  34060. this._shadowsDensity = 0;
  34061. this._shadowsSaturation = 0;
  34062. this._shadowsExposure = 0;
  34063. }
  34064. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  34065. /**
  34066. * Gets the global Hue value.
  34067. * 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).
  34068. */
  34069. get: function () {
  34070. return this._globalHue;
  34071. },
  34072. /**
  34073. * Sets the global Hue value.
  34074. * 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).
  34075. */
  34076. set: function (value) {
  34077. this._globalHue = value;
  34078. this._dirty = true;
  34079. },
  34080. enumerable: true,
  34081. configurable: true
  34082. });
  34083. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  34084. /**
  34085. * Gets the global Density value.
  34086. * 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.
  34087. * Values less than zero provide a filter of opposite hue.
  34088. */
  34089. get: function () {
  34090. return this._globalDensity;
  34091. },
  34092. /**
  34093. * Sets the global Density value.
  34094. * 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.
  34095. * Values less than zero provide a filter of opposite hue.
  34096. */
  34097. set: function (value) {
  34098. this._globalDensity = value;
  34099. this._dirty = true;
  34100. },
  34101. enumerable: true,
  34102. configurable: true
  34103. });
  34104. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  34105. /**
  34106. * Gets the global Saturation value.
  34107. * 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.
  34108. */
  34109. get: function () {
  34110. return this._globalSaturation;
  34111. },
  34112. /**
  34113. * Sets the global Saturation value.
  34114. * 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.
  34115. */
  34116. set: function (value) {
  34117. this._globalSaturation = value;
  34118. this._dirty = true;
  34119. },
  34120. enumerable: true,
  34121. configurable: true
  34122. });
  34123. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  34124. /**
  34125. * Gets the highlights Hue value.
  34126. * 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).
  34127. */
  34128. get: function () {
  34129. return this._highlightsHue;
  34130. },
  34131. /**
  34132. * Sets the highlights Hue value.
  34133. * 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).
  34134. */
  34135. set: function (value) {
  34136. this._highlightsHue = value;
  34137. this._dirty = true;
  34138. },
  34139. enumerable: true,
  34140. configurable: true
  34141. });
  34142. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  34143. /**
  34144. * Gets the highlights Density value.
  34145. * 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.
  34146. * Values less than zero provide a filter of opposite hue.
  34147. */
  34148. get: function () {
  34149. return this._highlightsDensity;
  34150. },
  34151. /**
  34152. * Sets the highlights Density value.
  34153. * 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.
  34154. * Values less than zero provide a filter of opposite hue.
  34155. */
  34156. set: function (value) {
  34157. this._highlightsDensity = value;
  34158. this._dirty = true;
  34159. },
  34160. enumerable: true,
  34161. configurable: true
  34162. });
  34163. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  34164. /**
  34165. * Gets the highlights Saturation value.
  34166. * 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.
  34167. */
  34168. get: function () {
  34169. return this._highlightsSaturation;
  34170. },
  34171. /**
  34172. * Sets the highlights Saturation value.
  34173. * 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.
  34174. */
  34175. set: function (value) {
  34176. this._highlightsSaturation = value;
  34177. this._dirty = true;
  34178. },
  34179. enumerable: true,
  34180. configurable: true
  34181. });
  34182. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  34183. /**
  34184. * Gets the highlights Exposure value.
  34185. * 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.
  34186. */
  34187. get: function () {
  34188. return this._highlightsExposure;
  34189. },
  34190. /**
  34191. * Sets the highlights Exposure value.
  34192. * 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.
  34193. */
  34194. set: function (value) {
  34195. this._highlightsExposure = value;
  34196. this._dirty = true;
  34197. },
  34198. enumerable: true,
  34199. configurable: true
  34200. });
  34201. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  34202. /**
  34203. * Gets the midtones Hue value.
  34204. * 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).
  34205. */
  34206. get: function () {
  34207. return this._midtonesHue;
  34208. },
  34209. /**
  34210. * Sets the midtones Hue value.
  34211. * 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).
  34212. */
  34213. set: function (value) {
  34214. this._midtonesHue = value;
  34215. this._dirty = true;
  34216. },
  34217. enumerable: true,
  34218. configurable: true
  34219. });
  34220. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  34221. /**
  34222. * Gets the midtones Density value.
  34223. * 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.
  34224. * Values less than zero provide a filter of opposite hue.
  34225. */
  34226. get: function () {
  34227. return this._midtonesDensity;
  34228. },
  34229. /**
  34230. * Sets the midtones Density value.
  34231. * 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.
  34232. * Values less than zero provide a filter of opposite hue.
  34233. */
  34234. set: function (value) {
  34235. this._midtonesDensity = value;
  34236. this._dirty = true;
  34237. },
  34238. enumerable: true,
  34239. configurable: true
  34240. });
  34241. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  34242. /**
  34243. * Gets the midtones Saturation value.
  34244. * 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.
  34245. */
  34246. get: function () {
  34247. return this._midtonesSaturation;
  34248. },
  34249. /**
  34250. * Sets the midtones Saturation value.
  34251. * 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.
  34252. */
  34253. set: function (value) {
  34254. this._midtonesSaturation = value;
  34255. this._dirty = true;
  34256. },
  34257. enumerable: true,
  34258. configurable: true
  34259. });
  34260. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  34261. /**
  34262. * Gets the midtones Exposure value.
  34263. * 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.
  34264. */
  34265. get: function () {
  34266. return this._midtonesExposure;
  34267. },
  34268. /**
  34269. * Sets the midtones Exposure value.
  34270. * 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.
  34271. */
  34272. set: function (value) {
  34273. this._midtonesExposure = value;
  34274. this._dirty = true;
  34275. },
  34276. enumerable: true,
  34277. configurable: true
  34278. });
  34279. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  34280. /**
  34281. * Gets the shadows Hue value.
  34282. * 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).
  34283. */
  34284. get: function () {
  34285. return this._shadowsHue;
  34286. },
  34287. /**
  34288. * Sets the shadows Hue value.
  34289. * 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).
  34290. */
  34291. set: function (value) {
  34292. this._shadowsHue = value;
  34293. this._dirty = true;
  34294. },
  34295. enumerable: true,
  34296. configurable: true
  34297. });
  34298. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  34299. /**
  34300. * Gets the shadows Density value.
  34301. * 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.
  34302. * Values less than zero provide a filter of opposite hue.
  34303. */
  34304. get: function () {
  34305. return this._shadowsDensity;
  34306. },
  34307. /**
  34308. * Sets the shadows Density value.
  34309. * 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.
  34310. * Values less than zero provide a filter of opposite hue.
  34311. */
  34312. set: function (value) {
  34313. this._shadowsDensity = value;
  34314. this._dirty = true;
  34315. },
  34316. enumerable: true,
  34317. configurable: true
  34318. });
  34319. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  34320. /**
  34321. * Gets the shadows Saturation value.
  34322. * 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.
  34323. */
  34324. get: function () {
  34325. return this._shadowsSaturation;
  34326. },
  34327. /**
  34328. * Sets the shadows Saturation value.
  34329. * 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.
  34330. */
  34331. set: function (value) {
  34332. this._shadowsSaturation = value;
  34333. this._dirty = true;
  34334. },
  34335. enumerable: true,
  34336. configurable: true
  34337. });
  34338. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  34339. /**
  34340. * Gets the shadows Exposure value.
  34341. * 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.
  34342. */
  34343. get: function () {
  34344. return this._shadowsExposure;
  34345. },
  34346. /**
  34347. * Sets the shadows Exposure value.
  34348. * 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.
  34349. */
  34350. set: function (value) {
  34351. this._shadowsExposure = value;
  34352. this._dirty = true;
  34353. },
  34354. enumerable: true,
  34355. configurable: true
  34356. });
  34357. ColorCurves.prototype.getClassName = function () {
  34358. return "ColorCurves";
  34359. };
  34360. /**
  34361. * Binds the color curves to the shader.
  34362. * @param colorCurves The color curve to bind
  34363. * @param effect The effect to bind to
  34364. */
  34365. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  34366. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  34367. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  34368. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  34369. if (colorCurves._dirty) {
  34370. colorCurves._dirty = false;
  34371. // Fill in global info.
  34372. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  34373. // Compute highlights info.
  34374. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  34375. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  34376. // Compute midtones info.
  34377. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  34378. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  34379. // Compute shadows info.
  34380. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  34381. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  34382. // Compute deltas (neutral is midtones).
  34383. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  34384. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  34385. }
  34386. if (effect) {
  34387. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  34388. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  34389. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  34390. }
  34391. };
  34392. /**
  34393. * Prepare the list of uniforms associated with the ColorCurves effects.
  34394. * @param uniformsList The list of uniforms used in the effect
  34395. */
  34396. ColorCurves.PrepareUniforms = function (uniformsList) {
  34397. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  34398. };
  34399. /**
  34400. * Returns color grading data based on a hue, density, saturation and exposure value.
  34401. * @param filterHue The hue of the color filter.
  34402. * @param filterDensity The density of the color filter.
  34403. * @param saturation The saturation.
  34404. * @param exposure The exposure.
  34405. * @param result The result data container.
  34406. */
  34407. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  34408. if (hue == null) {
  34409. return;
  34410. }
  34411. hue = ColorCurves.clamp(hue, 0, 360);
  34412. density = ColorCurves.clamp(density, -100, 100);
  34413. saturation = ColorCurves.clamp(saturation, -100, 100);
  34414. exposure = ColorCurves.clamp(exposure, -100, 100);
  34415. // Remap the slider/config filter density with non-linear mapping and also scale by half
  34416. // so that the maximum filter density is only 50% control. This provides fine control
  34417. // for small values and reasonable range.
  34418. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34419. density *= 0.5;
  34420. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34421. if (density < 0) {
  34422. density *= -1;
  34423. hue = (hue + 180) % 360;
  34424. }
  34425. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34426. result.scaleToRef(2, result);
  34427. result.a = 1 + 0.01 * saturation;
  34428. };
  34429. /**
  34430. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34431. * @param value The input slider value in range [-100,100].
  34432. * @returns Adjusted value.
  34433. */
  34434. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34435. value /= 100;
  34436. var x = Math.abs(value);
  34437. x = Math.pow(x, 2);
  34438. if (value < 0) {
  34439. x *= -1;
  34440. }
  34441. x *= 100;
  34442. return x;
  34443. };
  34444. /**
  34445. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34446. * @param hue The hue (H) input.
  34447. * @param saturation The saturation (S) input.
  34448. * @param brightness The brightness (B) input.
  34449. * @result An RGBA color represented as Vector4.
  34450. */
  34451. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34452. var h = ColorCurves.clamp(hue, 0, 360);
  34453. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34454. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34455. if (s === 0) {
  34456. result.r = v;
  34457. result.g = v;
  34458. result.b = v;
  34459. }
  34460. else {
  34461. // sector 0 to 5
  34462. h /= 60;
  34463. var i = Math.floor(h);
  34464. // fractional part of h
  34465. var f = h - i;
  34466. var p = v * (1 - s);
  34467. var q = v * (1 - s * f);
  34468. var t = v * (1 - s * (1 - f));
  34469. switch (i) {
  34470. case 0:
  34471. result.r = v;
  34472. result.g = t;
  34473. result.b = p;
  34474. break;
  34475. case 1:
  34476. result.r = q;
  34477. result.g = v;
  34478. result.b = p;
  34479. break;
  34480. case 2:
  34481. result.r = p;
  34482. result.g = v;
  34483. result.b = t;
  34484. break;
  34485. case 3:
  34486. result.r = p;
  34487. result.g = q;
  34488. result.b = v;
  34489. break;
  34490. case 4:
  34491. result.r = t;
  34492. result.g = p;
  34493. result.b = v;
  34494. break;
  34495. default:// case 5:
  34496. result.r = v;
  34497. result.g = p;
  34498. result.b = q;
  34499. break;
  34500. }
  34501. }
  34502. result.a = 1;
  34503. };
  34504. /**
  34505. * Returns a value clamped between min and max
  34506. * @param value The value to clamp
  34507. * @param min The minimum of value
  34508. * @param max The maximum of value
  34509. * @returns The clamped value.
  34510. */
  34511. ColorCurves.clamp = function (value, min, max) {
  34512. return Math.min(Math.max(value, min), max);
  34513. };
  34514. /**
  34515. * Clones the current color curve instance.
  34516. * @return The cloned curves
  34517. */
  34518. ColorCurves.prototype.clone = function () {
  34519. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34520. };
  34521. /**
  34522. * Serializes the current color curve instance to a json representation.
  34523. * @return a JSON representation
  34524. */
  34525. ColorCurves.prototype.serialize = function () {
  34526. return BABYLON.SerializationHelper.Serialize(this);
  34527. };
  34528. /**
  34529. * Parses the color curve from a json representation.
  34530. * @param source the JSON source to parse
  34531. * @return The parsed curves
  34532. */
  34533. ColorCurves.Parse = function (source) {
  34534. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34535. };
  34536. __decorate([
  34537. BABYLON.serialize()
  34538. ], ColorCurves.prototype, "_globalHue", void 0);
  34539. __decorate([
  34540. BABYLON.serialize()
  34541. ], ColorCurves.prototype, "_globalDensity", void 0);
  34542. __decorate([
  34543. BABYLON.serialize()
  34544. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34545. __decorate([
  34546. BABYLON.serialize()
  34547. ], ColorCurves.prototype, "_globalExposure", void 0);
  34548. __decorate([
  34549. BABYLON.serialize()
  34550. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34551. __decorate([
  34552. BABYLON.serialize()
  34553. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34554. __decorate([
  34555. BABYLON.serialize()
  34556. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34557. __decorate([
  34558. BABYLON.serialize()
  34559. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34560. __decorate([
  34561. BABYLON.serialize()
  34562. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34563. __decorate([
  34564. BABYLON.serialize()
  34565. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34566. __decorate([
  34567. BABYLON.serialize()
  34568. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34569. __decorate([
  34570. BABYLON.serialize()
  34571. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34572. return ColorCurves;
  34573. }());
  34574. BABYLON.ColorCurves = ColorCurves;
  34575. })(BABYLON || (BABYLON = {}));
  34576. //# sourceMappingURL=babylon.colorCurves.js.map
  34577. //# sourceMappingURL=babylon.behavior.js.map
  34578. var BABYLON;
  34579. (function (BABYLON) {
  34580. var MaterialHelper = /** @class */ (function () {
  34581. function MaterialHelper() {
  34582. }
  34583. MaterialHelper.BindEyePosition = function (effect, scene) {
  34584. if (scene._forcedViewPosition) {
  34585. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34586. return;
  34587. }
  34588. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34589. };
  34590. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34591. defines._needUVs = true;
  34592. defines[key] = true;
  34593. if (texture.getTextureMatrix().isIdentity(true)) {
  34594. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34595. if (texture.coordinatesIndex === 0) {
  34596. defines["MAINUV1"] = true;
  34597. }
  34598. else {
  34599. defines["MAINUV2"] = true;
  34600. }
  34601. }
  34602. else {
  34603. defines[key + "DIRECTUV"] = 0;
  34604. }
  34605. };
  34606. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34607. var matrix = texture.getTextureMatrix();
  34608. if (!matrix.isIdentity(true)) {
  34609. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34610. }
  34611. };
  34612. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34613. if (defines._areMiscDirty) {
  34614. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34615. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34616. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34617. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34618. }
  34619. };
  34620. /**
  34621. * Helper used to prepare the list of defines for shader compilation
  34622. * @param scene defines the current scene
  34623. * @param engine defines the current engine
  34624. * @param defines specifies the list of active defines
  34625. * @param useInstances defines if instances have to be turned on
  34626. * @param alphaTest defines if alpha testing has to be turned on
  34627. */
  34628. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, alphaTest) {
  34629. var changed = false;
  34630. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34631. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34632. changed = true;
  34633. }
  34634. if (defines["ALPHATEST"] !== alphaTest) {
  34635. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34636. changed = true;
  34637. }
  34638. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34639. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34640. changed = true;
  34641. }
  34642. if (defines["INSTANCES"] !== useInstances) {
  34643. defines["INSTANCES"] = useInstances;
  34644. changed = true;
  34645. }
  34646. if (changed) {
  34647. defines.markAsUnprocessed();
  34648. }
  34649. };
  34650. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34651. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34652. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34653. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34654. return false;
  34655. }
  34656. defines._normals = defines._needNormals;
  34657. defines._uvs = defines._needUVs;
  34658. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34659. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34660. defines["TANGENT"] = true;
  34661. }
  34662. if (defines._needUVs) {
  34663. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34664. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34665. }
  34666. else {
  34667. defines["UV1"] = false;
  34668. defines["UV2"] = false;
  34669. }
  34670. if (useVertexColor) {
  34671. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34672. defines["VERTEXCOLOR"] = hasVertexColors;
  34673. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34674. }
  34675. if (useBones) {
  34676. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34677. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34678. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34679. }
  34680. else {
  34681. defines["NUM_BONE_INFLUENCERS"] = 0;
  34682. defines["BonesPerMesh"] = 0;
  34683. }
  34684. }
  34685. if (useMorphTargets) {
  34686. var manager = mesh.morphTargetManager;
  34687. if (manager) {
  34688. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34689. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34690. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34691. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34692. }
  34693. else {
  34694. defines["MORPHTARGETS_TANGENT"] = false;
  34695. defines["MORPHTARGETS_NORMAL"] = false;
  34696. defines["MORPHTARGETS"] = false;
  34697. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34698. }
  34699. }
  34700. return true;
  34701. };
  34702. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34703. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34704. if (disableLighting === void 0) { disableLighting = false; }
  34705. if (!defines._areLightsDirty) {
  34706. return defines._needNormals;
  34707. }
  34708. var lightIndex = 0;
  34709. var needNormals = false;
  34710. var needRebuild = false;
  34711. var lightmapMode = false;
  34712. var shadowEnabled = false;
  34713. var specularEnabled = false;
  34714. if (scene.lightsEnabled && !disableLighting) {
  34715. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34716. var light = _a[_i];
  34717. needNormals = true;
  34718. if (defines["LIGHT" + lightIndex] === undefined) {
  34719. needRebuild = true;
  34720. }
  34721. defines["LIGHT" + lightIndex] = true;
  34722. defines["SPOTLIGHT" + lightIndex] = false;
  34723. defines["HEMILIGHT" + lightIndex] = false;
  34724. defines["POINTLIGHT" + lightIndex] = false;
  34725. defines["DIRLIGHT" + lightIndex] = false;
  34726. var type;
  34727. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34728. type = "SPOTLIGHT" + lightIndex;
  34729. }
  34730. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34731. type = "HEMILIGHT" + lightIndex;
  34732. }
  34733. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34734. type = "POINTLIGHT" + lightIndex;
  34735. }
  34736. else {
  34737. type = "DIRLIGHT" + lightIndex;
  34738. }
  34739. defines[type] = true;
  34740. // Specular
  34741. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34742. specularEnabled = true;
  34743. }
  34744. // Shadows
  34745. defines["SHADOW" + lightIndex] = false;
  34746. defines["SHADOWPCF" + lightIndex] = false;
  34747. defines["SHADOWESM" + lightIndex] = false;
  34748. defines["SHADOWCUBE" + lightIndex] = false;
  34749. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34750. var shadowGenerator = light.getShadowGenerator();
  34751. if (shadowGenerator) {
  34752. shadowEnabled = true;
  34753. shadowGenerator.prepareDefines(defines, lightIndex);
  34754. }
  34755. }
  34756. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34757. lightmapMode = true;
  34758. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34759. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34760. }
  34761. else {
  34762. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34763. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34764. }
  34765. lightIndex++;
  34766. if (lightIndex === maxSimultaneousLights)
  34767. break;
  34768. }
  34769. }
  34770. defines["SPECULARTERM"] = specularEnabled;
  34771. defines["SHADOWS"] = shadowEnabled;
  34772. // Resetting all other lights if any
  34773. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34774. if (defines["LIGHT" + index] !== undefined) {
  34775. defines["LIGHT" + index] = false;
  34776. defines["HEMILIGHT" + lightIndex] = false;
  34777. defines["POINTLIGHT" + lightIndex] = false;
  34778. defines["DIRLIGHT" + lightIndex] = false;
  34779. defines["SPOTLIGHT" + lightIndex] = false;
  34780. defines["SHADOW" + lightIndex] = false;
  34781. }
  34782. }
  34783. var caps = scene.getEngine().getCaps();
  34784. if (defines["SHADOWFLOAT"] === undefined) {
  34785. needRebuild = true;
  34786. }
  34787. defines["SHADOWFLOAT"] = shadowEnabled &&
  34788. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34789. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34790. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34791. if (needRebuild) {
  34792. defines.rebuild();
  34793. }
  34794. return needNormals;
  34795. };
  34796. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34797. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34798. var uniformsList;
  34799. var uniformBuffersList = null;
  34800. if (uniformsListOrOptions.uniformsNames) {
  34801. var options = uniformsListOrOptions;
  34802. uniformsList = options.uniformsNames;
  34803. uniformBuffersList = options.uniformBuffersNames;
  34804. samplersList = options.samplers;
  34805. defines = options.defines;
  34806. maxSimultaneousLights = options.maxSimultaneousLights;
  34807. }
  34808. else {
  34809. uniformsList = uniformsListOrOptions;
  34810. if (!samplersList) {
  34811. samplersList = [];
  34812. }
  34813. }
  34814. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34815. if (!defines["LIGHT" + lightIndex]) {
  34816. break;
  34817. }
  34818. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34819. if (uniformBuffersList) {
  34820. uniformBuffersList.push("Light" + lightIndex);
  34821. }
  34822. samplersList.push("shadowSampler" + lightIndex);
  34823. }
  34824. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34825. uniformsList.push("morphTargetInfluences");
  34826. }
  34827. };
  34828. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34829. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34830. if (rank === void 0) { rank = 0; }
  34831. var lightFallbackRank = 0;
  34832. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34833. if (!defines["LIGHT" + lightIndex]) {
  34834. break;
  34835. }
  34836. if (lightIndex > 0) {
  34837. lightFallbackRank = rank + lightIndex;
  34838. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34839. }
  34840. if (!defines["SHADOWS"]) {
  34841. if (defines["SHADOW" + lightIndex]) {
  34842. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34843. }
  34844. if (defines["SHADOWPCF" + lightIndex]) {
  34845. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34846. }
  34847. if (defines["SHADOWESM" + lightIndex]) {
  34848. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34849. }
  34850. }
  34851. }
  34852. return lightFallbackRank++;
  34853. };
  34854. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34855. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34856. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34857. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34858. var manager = mesh.morphTargetManager;
  34859. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34860. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34861. for (var index = 0; index < influencers; index++) {
  34862. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34863. if (normal) {
  34864. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34865. }
  34866. if (tangent) {
  34867. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34868. }
  34869. if (attribs.length > maxAttributesCount) {
  34870. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34871. }
  34872. }
  34873. }
  34874. };
  34875. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34876. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34877. fallbacks.addCPUSkinningFallback(0, mesh);
  34878. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34879. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34880. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34881. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34882. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34883. }
  34884. }
  34885. };
  34886. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34887. if (defines["INSTANCES"]) {
  34888. attribs.push("world0");
  34889. attribs.push("world1");
  34890. attribs.push("world2");
  34891. attribs.push("world3");
  34892. }
  34893. };
  34894. // Bindings
  34895. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34896. if (light.shadowEnabled && mesh.receiveShadows) {
  34897. var shadowGenerator = light.getShadowGenerator();
  34898. if (shadowGenerator) {
  34899. shadowGenerator.bindShadowLight(lightIndex, effect);
  34900. }
  34901. }
  34902. };
  34903. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34904. light.transferToEffect(effect, lightIndex + "");
  34905. };
  34906. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34907. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34908. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34909. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  34910. for (var i = 0; i < len; i++) {
  34911. var light = mesh._lightSources[i];
  34912. var iAsString = i.toString();
  34913. var scaledIntensity = light.getScaledIntensity();
  34914. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34915. MaterialHelper.BindLightProperties(light, effect, i);
  34916. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34917. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34918. if (defines["SPECULARTERM"]) {
  34919. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34920. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34921. }
  34922. // Shadows
  34923. if (scene.shadowsEnabled) {
  34924. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34925. }
  34926. light._uniformBuffer.update();
  34927. }
  34928. };
  34929. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34930. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34931. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34932. effect.setColor3("vFogColor", scene.fogColor);
  34933. }
  34934. };
  34935. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34936. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34937. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34938. if (matrices && effect) {
  34939. effect.setMatrices("mBones", matrices);
  34940. }
  34941. }
  34942. };
  34943. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34944. var manager = abstractMesh.morphTargetManager;
  34945. if (!abstractMesh || !manager) {
  34946. return;
  34947. }
  34948. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34949. };
  34950. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34951. if (defines["LOGARITHMICDEPTH"]) {
  34952. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34953. }
  34954. };
  34955. MaterialHelper.BindClipPlane = function (effect, scene) {
  34956. if (scene.clipPlane) {
  34957. var clipPlane = scene.clipPlane;
  34958. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34959. }
  34960. };
  34961. return MaterialHelper;
  34962. }());
  34963. BABYLON.MaterialHelper = MaterialHelper;
  34964. })(BABYLON || (BABYLON = {}));
  34965. //# sourceMappingURL=babylon.materialHelper.js.map
  34966. var BABYLON;
  34967. (function (BABYLON) {
  34968. var PushMaterial = /** @class */ (function (_super) {
  34969. __extends(PushMaterial, _super);
  34970. function PushMaterial(name, scene) {
  34971. var _this = _super.call(this, name, scene) || this;
  34972. _this.storeEffectOnSubMeshes = true;
  34973. return _this;
  34974. }
  34975. PushMaterial.prototype.getEffect = function () {
  34976. return this._activeEffect;
  34977. };
  34978. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34979. if (!mesh) {
  34980. return false;
  34981. }
  34982. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34983. return true;
  34984. }
  34985. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34986. };
  34987. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34988. this._activeEffect.setMatrix("world", world);
  34989. };
  34990. PushMaterial.prototype.bind = function (world, mesh) {
  34991. if (!mesh) {
  34992. return;
  34993. }
  34994. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34995. };
  34996. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34997. if (effect === void 0) { effect = null; }
  34998. _super.prototype._afterBind.call(this, mesh);
  34999. this.getScene()._cachedEffect = effect;
  35000. };
  35001. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  35002. if (visibility === void 0) { visibility = 1; }
  35003. return scene.isCachedMaterialInvalid(this, effect, visibility);
  35004. };
  35005. return PushMaterial;
  35006. }(BABYLON.Material));
  35007. BABYLON.PushMaterial = PushMaterial;
  35008. })(BABYLON || (BABYLON = {}));
  35009. //# sourceMappingURL=babylon.pushMaterial.js.map
  35010. var BABYLON;
  35011. (function (BABYLON) {
  35012. var StandardMaterialDefines = /** @class */ (function (_super) {
  35013. __extends(StandardMaterialDefines, _super);
  35014. function StandardMaterialDefines() {
  35015. var _this = _super.call(this) || this;
  35016. _this.MAINUV1 = false;
  35017. _this.MAINUV2 = false;
  35018. _this.DIFFUSE = false;
  35019. _this.DIFFUSEDIRECTUV = 0;
  35020. _this.AMBIENT = false;
  35021. _this.AMBIENTDIRECTUV = 0;
  35022. _this.OPACITY = false;
  35023. _this.OPACITYDIRECTUV = 0;
  35024. _this.OPACITYRGB = false;
  35025. _this.REFLECTION = false;
  35026. _this.EMISSIVE = false;
  35027. _this.EMISSIVEDIRECTUV = 0;
  35028. _this.SPECULAR = false;
  35029. _this.SPECULARDIRECTUV = 0;
  35030. _this.BUMP = false;
  35031. _this.BUMPDIRECTUV = 0;
  35032. _this.PARALLAX = false;
  35033. _this.PARALLAXOCCLUSION = false;
  35034. _this.SPECULAROVERALPHA = false;
  35035. _this.CLIPPLANE = false;
  35036. _this.ALPHATEST = false;
  35037. _this.DEPTHPREPASS = false;
  35038. _this.ALPHAFROMDIFFUSE = false;
  35039. _this.POINTSIZE = false;
  35040. _this.FOG = false;
  35041. _this.SPECULARTERM = false;
  35042. _this.DIFFUSEFRESNEL = false;
  35043. _this.OPACITYFRESNEL = false;
  35044. _this.REFLECTIONFRESNEL = false;
  35045. _this.REFRACTIONFRESNEL = false;
  35046. _this.EMISSIVEFRESNEL = false;
  35047. _this.FRESNEL = false;
  35048. _this.NORMAL = false;
  35049. _this.UV1 = false;
  35050. _this.UV2 = false;
  35051. _this.VERTEXCOLOR = false;
  35052. _this.VERTEXALPHA = false;
  35053. _this.NUM_BONE_INFLUENCERS = 0;
  35054. _this.BonesPerMesh = 0;
  35055. _this.INSTANCES = false;
  35056. _this.GLOSSINESS = false;
  35057. _this.ROUGHNESS = false;
  35058. _this.EMISSIVEASILLUMINATION = false;
  35059. _this.LINKEMISSIVEWITHDIFFUSE = false;
  35060. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  35061. _this.LIGHTMAP = false;
  35062. _this.LIGHTMAPDIRECTUV = 0;
  35063. _this.USELIGHTMAPASSHADOWMAP = false;
  35064. _this.REFLECTIONMAP_3D = false;
  35065. _this.REFLECTIONMAP_SPHERICAL = false;
  35066. _this.REFLECTIONMAP_PLANAR = false;
  35067. _this.REFLECTIONMAP_CUBIC = false;
  35068. _this.REFLECTIONMAP_PROJECTION = false;
  35069. _this.REFLECTIONMAP_SKYBOX = false;
  35070. _this.REFLECTIONMAP_EXPLICIT = false;
  35071. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  35072. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  35073. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  35074. _this.INVERTCUBICMAP = false;
  35075. _this.LOGARITHMICDEPTH = false;
  35076. _this.REFRACTION = false;
  35077. _this.REFRACTIONMAP_3D = false;
  35078. _this.REFLECTIONOVERALPHA = false;
  35079. _this.TWOSIDEDLIGHTING = false;
  35080. _this.SHADOWFLOAT = false;
  35081. _this.MORPHTARGETS = false;
  35082. _this.MORPHTARGETS_NORMAL = false;
  35083. _this.MORPHTARGETS_TANGENT = false;
  35084. _this.NUM_MORPH_INFLUENCERS = 0;
  35085. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  35086. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  35087. _this.IMAGEPROCESSING = false;
  35088. _this.VIGNETTE = false;
  35089. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  35090. _this.VIGNETTEBLENDMODEOPAQUE = false;
  35091. _this.TONEMAPPING = false;
  35092. _this.CONTRAST = false;
  35093. _this.COLORCURVES = false;
  35094. _this.COLORGRADING = false;
  35095. _this.COLORGRADING3D = false;
  35096. _this.SAMPLER3DGREENDEPTH = false;
  35097. _this.SAMPLER3DBGRMAP = false;
  35098. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  35099. _this.EXPOSURE = false;
  35100. _this.rebuild();
  35101. return _this;
  35102. }
  35103. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  35104. var modes = [
  35105. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  35106. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  35107. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  35108. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  35109. ];
  35110. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  35111. var mode = modes_1[_i];
  35112. this[mode] = (mode === modeToEnable);
  35113. }
  35114. };
  35115. return StandardMaterialDefines;
  35116. }(BABYLON.MaterialDefines));
  35117. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  35118. var StandardMaterial = /** @class */ (function (_super) {
  35119. __extends(StandardMaterial, _super);
  35120. function StandardMaterial(name, scene) {
  35121. var _this = _super.call(this, name, scene) || this;
  35122. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  35123. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  35124. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  35125. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  35126. _this.specularPower = 64;
  35127. _this._useAlphaFromDiffuseTexture = false;
  35128. _this._useEmissiveAsIllumination = false;
  35129. _this._linkEmissiveWithDiffuse = false;
  35130. _this._useSpecularOverAlpha = false;
  35131. _this._useReflectionOverAlpha = false;
  35132. _this._disableLighting = false;
  35133. _this._useParallax = false;
  35134. _this._useParallaxOcclusion = false;
  35135. _this.parallaxScaleBias = 0.05;
  35136. _this._roughness = 0;
  35137. _this.indexOfRefraction = 0.98;
  35138. _this.invertRefractionY = true;
  35139. _this._useLightmapAsShadowmap = false;
  35140. _this._useReflectionFresnelFromSpecular = false;
  35141. _this._useGlossinessFromSpecularMapAlpha = false;
  35142. _this._maxSimultaneousLights = 4;
  35143. /**
  35144. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  35145. */
  35146. _this._invertNormalMapX = false;
  35147. /**
  35148. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  35149. */
  35150. _this._invertNormalMapY = false;
  35151. /**
  35152. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  35153. */
  35154. _this._twoSidedLighting = false;
  35155. _this._renderTargets = new BABYLON.SmartArray(16);
  35156. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  35157. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  35158. // Setup the default processing configuration to the scene.
  35159. _this._attachImageProcessingConfiguration(null);
  35160. _this.getRenderTargetTextures = function () {
  35161. _this._renderTargets.reset();
  35162. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  35163. _this._renderTargets.push(_this._reflectionTexture);
  35164. }
  35165. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  35166. _this._renderTargets.push(_this._refractionTexture);
  35167. }
  35168. return _this._renderTargets;
  35169. };
  35170. return _this;
  35171. }
  35172. ;
  35173. ;
  35174. ;
  35175. ;
  35176. ;
  35177. ;
  35178. ;
  35179. ;
  35180. ;
  35181. ;
  35182. ;
  35183. ;
  35184. ;
  35185. ;
  35186. ;
  35187. ;
  35188. ;
  35189. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  35190. /**
  35191. * Gets the image processing configuration used either in this material.
  35192. */
  35193. get: function () {
  35194. return this._imageProcessingConfiguration;
  35195. },
  35196. /**
  35197. * Sets the Default image processing configuration used either in the this material.
  35198. *
  35199. * If sets to null, the scene one is in use.
  35200. */
  35201. set: function (value) {
  35202. this._attachImageProcessingConfiguration(value);
  35203. // Ensure the effect will be rebuilt.
  35204. this._markAllSubMeshesAsTexturesDirty();
  35205. },
  35206. enumerable: true,
  35207. configurable: true
  35208. });
  35209. /**
  35210. * Attaches a new image processing configuration to the Standard Material.
  35211. * @param configuration
  35212. */
  35213. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  35214. var _this = this;
  35215. if (configuration === this._imageProcessingConfiguration) {
  35216. return;
  35217. }
  35218. // Detaches observer.
  35219. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35220. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35221. }
  35222. // Pick the scene configuration if needed.
  35223. if (!configuration) {
  35224. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  35225. }
  35226. else {
  35227. this._imageProcessingConfiguration = configuration;
  35228. }
  35229. // Attaches observer.
  35230. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  35231. _this._markAllSubMeshesAsImageProcessingDirty();
  35232. });
  35233. };
  35234. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  35235. /**
  35236. * Gets wether the color curves effect is enabled.
  35237. */
  35238. get: function () {
  35239. return this.imageProcessingConfiguration.colorCurvesEnabled;
  35240. },
  35241. /**
  35242. * Sets wether the color curves effect is enabled.
  35243. */
  35244. set: function (value) {
  35245. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  35246. },
  35247. enumerable: true,
  35248. configurable: true
  35249. });
  35250. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  35251. /**
  35252. * Gets wether the color grading effect is enabled.
  35253. */
  35254. get: function () {
  35255. return this.imageProcessingConfiguration.colorGradingEnabled;
  35256. },
  35257. /**
  35258. * Gets wether the color grading effect is enabled.
  35259. */
  35260. set: function (value) {
  35261. this.imageProcessingConfiguration.colorGradingEnabled = value;
  35262. },
  35263. enumerable: true,
  35264. configurable: true
  35265. });
  35266. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  35267. /**
  35268. * Gets wether tonemapping is enabled or not.
  35269. */
  35270. get: function () {
  35271. return this._imageProcessingConfiguration.toneMappingEnabled;
  35272. },
  35273. /**
  35274. * Sets wether tonemapping is enabled or not
  35275. */
  35276. set: function (value) {
  35277. this._imageProcessingConfiguration.toneMappingEnabled = value;
  35278. },
  35279. enumerable: true,
  35280. configurable: true
  35281. });
  35282. ;
  35283. ;
  35284. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  35285. /**
  35286. * The camera exposure used on this material.
  35287. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35288. * This corresponds to a photographic exposure.
  35289. */
  35290. get: function () {
  35291. return this._imageProcessingConfiguration.exposure;
  35292. },
  35293. /**
  35294. * The camera exposure used on this material.
  35295. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  35296. * This corresponds to a photographic exposure.
  35297. */
  35298. set: function (value) {
  35299. this._imageProcessingConfiguration.exposure = value;
  35300. },
  35301. enumerable: true,
  35302. configurable: true
  35303. });
  35304. ;
  35305. ;
  35306. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  35307. /**
  35308. * Gets The camera contrast used on this material.
  35309. */
  35310. get: function () {
  35311. return this._imageProcessingConfiguration.contrast;
  35312. },
  35313. /**
  35314. * Sets The camera contrast used on this material.
  35315. */
  35316. set: function (value) {
  35317. this._imageProcessingConfiguration.contrast = value;
  35318. },
  35319. enumerable: true,
  35320. configurable: true
  35321. });
  35322. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  35323. /**
  35324. * Gets the Color Grading 2D Lookup Texture.
  35325. */
  35326. get: function () {
  35327. return this._imageProcessingConfiguration.colorGradingTexture;
  35328. },
  35329. /**
  35330. * Sets the Color Grading 2D Lookup Texture.
  35331. */
  35332. set: function (value) {
  35333. this._imageProcessingConfiguration.colorGradingTexture = value;
  35334. },
  35335. enumerable: true,
  35336. configurable: true
  35337. });
  35338. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  35339. /**
  35340. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35341. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35342. * 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;
  35343. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35344. */
  35345. get: function () {
  35346. return this._imageProcessingConfiguration.colorCurves;
  35347. },
  35348. /**
  35349. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  35350. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  35351. * 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;
  35352. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  35353. */
  35354. set: function (value) {
  35355. this._imageProcessingConfiguration.colorCurves = value;
  35356. },
  35357. enumerable: true,
  35358. configurable: true
  35359. });
  35360. StandardMaterial.prototype.getClassName = function () {
  35361. return "StandardMaterial";
  35362. };
  35363. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  35364. get: function () {
  35365. return this._useLogarithmicDepth;
  35366. },
  35367. set: function (value) {
  35368. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  35369. this._markAllSubMeshesAsMiscDirty();
  35370. },
  35371. enumerable: true,
  35372. configurable: true
  35373. });
  35374. StandardMaterial.prototype.needAlphaBlending = function () {
  35375. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  35376. };
  35377. StandardMaterial.prototype.needAlphaTesting = function () {
  35378. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  35379. };
  35380. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  35381. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  35382. };
  35383. StandardMaterial.prototype.getAlphaTestTexture = function () {
  35384. return this._diffuseTexture;
  35385. };
  35386. /**
  35387. * Child classes can use it to update shaders
  35388. */
  35389. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35390. if (useInstances === void 0) { useInstances = false; }
  35391. if (subMesh.effect && this.isFrozen) {
  35392. if (this._wasPreviouslyReady && subMesh.effect) {
  35393. return true;
  35394. }
  35395. }
  35396. if (!subMesh._materialDefines) {
  35397. subMesh._materialDefines = new StandardMaterialDefines();
  35398. }
  35399. var scene = this.getScene();
  35400. var defines = subMesh._materialDefines;
  35401. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  35402. if (defines._renderId === scene.getRenderId()) {
  35403. return true;
  35404. }
  35405. }
  35406. var engine = scene.getEngine();
  35407. // Lights
  35408. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  35409. // Textures
  35410. if (defines._areTexturesDirty) {
  35411. defines._needUVs = false;
  35412. defines.MAINUV1 = false;
  35413. defines.MAINUV2 = false;
  35414. if (scene.texturesEnabled) {
  35415. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35416. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  35417. return false;
  35418. }
  35419. else {
  35420. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  35421. }
  35422. }
  35423. else {
  35424. defines.DIFFUSE = false;
  35425. }
  35426. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35427. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35428. return false;
  35429. }
  35430. else {
  35431. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35432. }
  35433. }
  35434. else {
  35435. defines.AMBIENT = false;
  35436. }
  35437. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35438. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35439. return false;
  35440. }
  35441. else {
  35442. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35443. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35444. }
  35445. }
  35446. else {
  35447. defines.OPACITY = false;
  35448. }
  35449. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35450. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35451. return false;
  35452. }
  35453. else {
  35454. defines._needNormals = true;
  35455. defines.REFLECTION = true;
  35456. defines.ROUGHNESS = (this._roughness > 0);
  35457. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35458. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35459. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35460. switch (this._reflectionTexture.coordinatesMode) {
  35461. case BABYLON.Texture.CUBIC_MODE:
  35462. case BABYLON.Texture.INVCUBIC_MODE:
  35463. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35464. break;
  35465. case BABYLON.Texture.EXPLICIT_MODE:
  35466. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35467. break;
  35468. case BABYLON.Texture.PLANAR_MODE:
  35469. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35470. break;
  35471. case BABYLON.Texture.PROJECTION_MODE:
  35472. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35473. break;
  35474. case BABYLON.Texture.SKYBOX_MODE:
  35475. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35476. break;
  35477. case BABYLON.Texture.SPHERICAL_MODE:
  35478. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35479. break;
  35480. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35481. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35482. break;
  35483. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35484. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35485. break;
  35486. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35487. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35488. break;
  35489. }
  35490. }
  35491. }
  35492. else {
  35493. defines.REFLECTION = false;
  35494. }
  35495. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35496. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35497. return false;
  35498. }
  35499. else {
  35500. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35501. }
  35502. }
  35503. else {
  35504. defines.EMISSIVE = false;
  35505. }
  35506. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35507. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35508. return false;
  35509. }
  35510. else {
  35511. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35512. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35513. }
  35514. }
  35515. else {
  35516. defines.LIGHTMAP = false;
  35517. }
  35518. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35519. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35520. return false;
  35521. }
  35522. else {
  35523. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35524. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35525. }
  35526. }
  35527. else {
  35528. defines.SPECULAR = false;
  35529. }
  35530. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35531. // Bump texure can not be not blocking.
  35532. if (!this._bumpTexture.isReady()) {
  35533. return false;
  35534. }
  35535. else {
  35536. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35537. defines.PARALLAX = this._useParallax;
  35538. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35539. }
  35540. }
  35541. else {
  35542. defines.BUMP = false;
  35543. }
  35544. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35545. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35546. return false;
  35547. }
  35548. else {
  35549. defines._needUVs = true;
  35550. defines.REFRACTION = true;
  35551. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35552. }
  35553. }
  35554. else {
  35555. defines.REFRACTION = false;
  35556. }
  35557. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35558. }
  35559. else {
  35560. defines.DIFFUSE = false;
  35561. defines.AMBIENT = false;
  35562. defines.OPACITY = false;
  35563. defines.REFLECTION = false;
  35564. defines.EMISSIVE = false;
  35565. defines.LIGHTMAP = false;
  35566. defines.BUMP = false;
  35567. defines.REFRACTION = false;
  35568. }
  35569. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35570. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35571. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35572. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35573. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35574. }
  35575. if (defines._areImageProcessingDirty) {
  35576. if (!this._imageProcessingConfiguration.isReady()) {
  35577. return false;
  35578. }
  35579. this._imageProcessingConfiguration.prepareDefines(defines);
  35580. }
  35581. if (defines._areFresnelDirty) {
  35582. if (StandardMaterial.FresnelEnabled) {
  35583. // Fresnel
  35584. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35585. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35586. this._reflectionFresnelParameters) {
  35587. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35588. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35589. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35590. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35591. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35592. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35593. defines._needNormals = true;
  35594. defines.FRESNEL = true;
  35595. }
  35596. }
  35597. else {
  35598. defines.FRESNEL = false;
  35599. }
  35600. }
  35601. // Misc.
  35602. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35603. // Attribs
  35604. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35605. // Values that need to be evaluated on every frame
  35606. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  35607. // Get correct effect
  35608. if (defines.isDirty) {
  35609. defines.markAsProcessed();
  35610. scene.resetCachedMaterial();
  35611. // Fallbacks
  35612. var fallbacks = new BABYLON.EffectFallbacks();
  35613. if (defines.REFLECTION) {
  35614. fallbacks.addFallback(0, "REFLECTION");
  35615. }
  35616. if (defines.SPECULAR) {
  35617. fallbacks.addFallback(0, "SPECULAR");
  35618. }
  35619. if (defines.BUMP) {
  35620. fallbacks.addFallback(0, "BUMP");
  35621. }
  35622. if (defines.PARALLAX) {
  35623. fallbacks.addFallback(1, "PARALLAX");
  35624. }
  35625. if (defines.PARALLAXOCCLUSION) {
  35626. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35627. }
  35628. if (defines.SPECULAROVERALPHA) {
  35629. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35630. }
  35631. if (defines.FOG) {
  35632. fallbacks.addFallback(1, "FOG");
  35633. }
  35634. if (defines.POINTSIZE) {
  35635. fallbacks.addFallback(0, "POINTSIZE");
  35636. }
  35637. if (defines.LOGARITHMICDEPTH) {
  35638. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35639. }
  35640. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35641. if (defines.SPECULARTERM) {
  35642. fallbacks.addFallback(0, "SPECULARTERM");
  35643. }
  35644. if (defines.DIFFUSEFRESNEL) {
  35645. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35646. }
  35647. if (defines.OPACITYFRESNEL) {
  35648. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35649. }
  35650. if (defines.REFLECTIONFRESNEL) {
  35651. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35652. }
  35653. if (defines.EMISSIVEFRESNEL) {
  35654. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35655. }
  35656. if (defines.FRESNEL) {
  35657. fallbacks.addFallback(4, "FRESNEL");
  35658. }
  35659. //Attributes
  35660. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35661. if (defines.NORMAL) {
  35662. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35663. }
  35664. if (defines.UV1) {
  35665. attribs.push(BABYLON.VertexBuffer.UVKind);
  35666. }
  35667. if (defines.UV2) {
  35668. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35669. }
  35670. if (defines.VERTEXCOLOR) {
  35671. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35672. }
  35673. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35674. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35675. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35676. var shaderName = "default";
  35677. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35678. "vFogInfos", "vFogColor", "pointSize",
  35679. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35680. "mBones",
  35681. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35682. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35683. "logarithmicDepthConstant", "vTangentSpaceParams"
  35684. ];
  35685. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35686. var uniformBuffers = ["Material", "Scene"];
  35687. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35688. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35689. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35690. uniformsNames: uniforms,
  35691. uniformBuffersNames: uniformBuffers,
  35692. samplers: samplers,
  35693. defines: defines,
  35694. maxSimultaneousLights: this._maxSimultaneousLights
  35695. });
  35696. if (this.customShaderNameResolve) {
  35697. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35698. }
  35699. var join = defines.toString();
  35700. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35701. attributes: attribs,
  35702. uniformsNames: uniforms,
  35703. uniformBuffersNames: uniformBuffers,
  35704. samplers: samplers,
  35705. defines: join,
  35706. fallbacks: fallbacks,
  35707. onCompiled: this.onCompiled,
  35708. onError: this.onError,
  35709. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35710. }, engine), defines);
  35711. this.buildUniformLayout();
  35712. }
  35713. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35714. return false;
  35715. }
  35716. defines._renderId = scene.getRenderId();
  35717. this._wasPreviouslyReady = true;
  35718. return true;
  35719. };
  35720. StandardMaterial.prototype.buildUniformLayout = function () {
  35721. // Order is important !
  35722. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35723. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35724. this._uniformBuffer.addUniform("opacityParts", 4);
  35725. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35726. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35727. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35728. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35729. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35730. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35731. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35732. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35733. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35734. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35735. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35736. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35737. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35738. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35739. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35740. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35741. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35742. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35743. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35744. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35745. this._uniformBuffer.addUniform("specularMatrix", 16);
  35746. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35747. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35748. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35749. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35750. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35751. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35752. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35753. this._uniformBuffer.addUniform("pointSize", 1);
  35754. this._uniformBuffer.create();
  35755. };
  35756. StandardMaterial.prototype.unbind = function () {
  35757. if (this._activeEffect) {
  35758. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35759. this._activeEffect.setTexture("reflection2DSampler", null);
  35760. }
  35761. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35762. this._activeEffect.setTexture("refraction2DSampler", null);
  35763. }
  35764. }
  35765. _super.prototype.unbind.call(this);
  35766. };
  35767. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35768. var scene = this.getScene();
  35769. var defines = subMesh._materialDefines;
  35770. if (!defines) {
  35771. return;
  35772. }
  35773. var effect = subMesh.effect;
  35774. if (!effect) {
  35775. return;
  35776. }
  35777. this._activeEffect = effect;
  35778. // Matrices
  35779. this.bindOnlyWorldMatrix(world);
  35780. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35781. // Bones
  35782. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35783. if (mustRebind) {
  35784. this._uniformBuffer.bindToEffect(effect, "Material");
  35785. this.bindViewProjection(effect);
  35786. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35787. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35788. // Fresnel
  35789. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35790. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35791. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35792. }
  35793. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35794. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35795. }
  35796. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35797. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35798. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35799. }
  35800. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35801. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35802. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35803. }
  35804. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35805. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35806. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35807. }
  35808. }
  35809. // Textures
  35810. if (scene.texturesEnabled) {
  35811. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35812. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35813. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35814. }
  35815. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35816. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35817. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35818. }
  35819. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35820. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35821. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35822. }
  35823. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35824. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35825. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35826. }
  35827. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35828. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35829. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35830. }
  35831. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35832. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35833. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35834. }
  35835. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35836. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35837. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35838. }
  35839. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35840. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35841. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35842. if (scene._mirroredCameraPosition) {
  35843. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35844. }
  35845. else {
  35846. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35847. }
  35848. }
  35849. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35850. var depth = 1.0;
  35851. if (!this._refractionTexture.isCube) {
  35852. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35853. if (this._refractionTexture.depth) {
  35854. depth = this._refractionTexture.depth;
  35855. }
  35856. }
  35857. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35858. }
  35859. }
  35860. // Point size
  35861. if (this.pointsCloud) {
  35862. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35863. }
  35864. if (defines.SPECULARTERM) {
  35865. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35866. }
  35867. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35868. // Diffuse
  35869. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35870. }
  35871. // Textures
  35872. if (scene.texturesEnabled) {
  35873. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35874. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35875. }
  35876. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35877. effect.setTexture("ambientSampler", this._ambientTexture);
  35878. }
  35879. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35880. effect.setTexture("opacitySampler", this._opacityTexture);
  35881. }
  35882. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35883. if (this._reflectionTexture.isCube) {
  35884. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35885. }
  35886. else {
  35887. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35888. }
  35889. }
  35890. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35891. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35892. }
  35893. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35894. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35895. }
  35896. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35897. effect.setTexture("specularSampler", this._specularTexture);
  35898. }
  35899. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35900. effect.setTexture("bumpSampler", this._bumpTexture);
  35901. }
  35902. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35903. var depth = 1.0;
  35904. if (this._refractionTexture.isCube) {
  35905. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35906. }
  35907. else {
  35908. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35909. }
  35910. }
  35911. }
  35912. // Clip plane
  35913. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35914. // Colors
  35915. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35916. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35917. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35918. }
  35919. if (mustRebind || !this.isFrozen) {
  35920. // Lights
  35921. if (scene.lightsEnabled && !this._disableLighting) {
  35922. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35923. }
  35924. // View
  35925. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35926. this.bindView(effect);
  35927. }
  35928. // Fog
  35929. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35930. // Morph targets
  35931. if (defines.NUM_MORPH_INFLUENCERS) {
  35932. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35933. }
  35934. // Log. depth
  35935. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35936. // image processing
  35937. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35938. this._imageProcessingConfiguration.bind(this._activeEffect);
  35939. }
  35940. }
  35941. this._uniformBuffer.update();
  35942. this._afterBind(mesh, this._activeEffect);
  35943. };
  35944. StandardMaterial.prototype.getAnimatables = function () {
  35945. var results = [];
  35946. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35947. results.push(this._diffuseTexture);
  35948. }
  35949. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35950. results.push(this._ambientTexture);
  35951. }
  35952. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35953. results.push(this._opacityTexture);
  35954. }
  35955. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35956. results.push(this._reflectionTexture);
  35957. }
  35958. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35959. results.push(this._emissiveTexture);
  35960. }
  35961. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35962. results.push(this._specularTexture);
  35963. }
  35964. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35965. results.push(this._bumpTexture);
  35966. }
  35967. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35968. results.push(this._lightmapTexture);
  35969. }
  35970. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35971. results.push(this._refractionTexture);
  35972. }
  35973. return results;
  35974. };
  35975. StandardMaterial.prototype.getActiveTextures = function () {
  35976. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35977. if (this._diffuseTexture) {
  35978. activeTextures.push(this._diffuseTexture);
  35979. }
  35980. if (this._ambientTexture) {
  35981. activeTextures.push(this._ambientTexture);
  35982. }
  35983. if (this._opacityTexture) {
  35984. activeTextures.push(this._opacityTexture);
  35985. }
  35986. if (this._reflectionTexture) {
  35987. activeTextures.push(this._reflectionTexture);
  35988. }
  35989. if (this._emissiveTexture) {
  35990. activeTextures.push(this._emissiveTexture);
  35991. }
  35992. if (this._specularTexture) {
  35993. activeTextures.push(this._specularTexture);
  35994. }
  35995. if (this._bumpTexture) {
  35996. activeTextures.push(this._bumpTexture);
  35997. }
  35998. if (this._lightmapTexture) {
  35999. activeTextures.push(this._lightmapTexture);
  36000. }
  36001. if (this._refractionTexture) {
  36002. activeTextures.push(this._refractionTexture);
  36003. }
  36004. return activeTextures;
  36005. };
  36006. StandardMaterial.prototype.hasTexture = function (texture) {
  36007. if (_super.prototype.hasTexture.call(this, texture)) {
  36008. return true;
  36009. }
  36010. if (this._diffuseTexture === texture) {
  36011. return true;
  36012. }
  36013. if (this._ambientTexture === texture) {
  36014. return true;
  36015. }
  36016. if (this._opacityTexture === texture) {
  36017. return true;
  36018. }
  36019. if (this._reflectionTexture === texture) {
  36020. return true;
  36021. }
  36022. if (this._emissiveTexture === texture) {
  36023. return true;
  36024. }
  36025. if (this._specularTexture === texture) {
  36026. return true;
  36027. }
  36028. if (this._bumpTexture === texture) {
  36029. return true;
  36030. }
  36031. if (this._lightmapTexture === texture) {
  36032. return true;
  36033. }
  36034. if (this._refractionTexture === texture) {
  36035. return true;
  36036. }
  36037. return false;
  36038. };
  36039. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36040. if (forceDisposeTextures) {
  36041. if (this._diffuseTexture) {
  36042. this._diffuseTexture.dispose();
  36043. }
  36044. if (this._ambientTexture) {
  36045. this._ambientTexture.dispose();
  36046. }
  36047. if (this._opacityTexture) {
  36048. this._opacityTexture.dispose();
  36049. }
  36050. if (this._reflectionTexture) {
  36051. this._reflectionTexture.dispose();
  36052. }
  36053. if (this._emissiveTexture) {
  36054. this._emissiveTexture.dispose();
  36055. }
  36056. if (this._specularTexture) {
  36057. this._specularTexture.dispose();
  36058. }
  36059. if (this._bumpTexture) {
  36060. this._bumpTexture.dispose();
  36061. }
  36062. if (this._lightmapTexture) {
  36063. this._lightmapTexture.dispose();
  36064. }
  36065. if (this._refractionTexture) {
  36066. this._refractionTexture.dispose();
  36067. }
  36068. }
  36069. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36070. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36071. }
  36072. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  36073. };
  36074. StandardMaterial.prototype.clone = function (name) {
  36075. var _this = this;
  36076. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  36077. result.name = name;
  36078. result.id = name;
  36079. return result;
  36080. };
  36081. StandardMaterial.prototype.serialize = function () {
  36082. return BABYLON.SerializationHelper.Serialize(this);
  36083. };
  36084. // Statics
  36085. StandardMaterial.Parse = function (source, scene, rootUrl) {
  36086. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  36087. };
  36088. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  36089. get: function () {
  36090. return StandardMaterial._DiffuseTextureEnabled;
  36091. },
  36092. set: function (value) {
  36093. if (StandardMaterial._DiffuseTextureEnabled === value) {
  36094. return;
  36095. }
  36096. StandardMaterial._DiffuseTextureEnabled = value;
  36097. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36098. },
  36099. enumerable: true,
  36100. configurable: true
  36101. });
  36102. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  36103. get: function () {
  36104. return StandardMaterial._AmbientTextureEnabled;
  36105. },
  36106. set: function (value) {
  36107. if (StandardMaterial._AmbientTextureEnabled === value) {
  36108. return;
  36109. }
  36110. StandardMaterial._AmbientTextureEnabled = value;
  36111. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36112. },
  36113. enumerable: true,
  36114. configurable: true
  36115. });
  36116. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  36117. get: function () {
  36118. return StandardMaterial._OpacityTextureEnabled;
  36119. },
  36120. set: function (value) {
  36121. if (StandardMaterial._OpacityTextureEnabled === value) {
  36122. return;
  36123. }
  36124. StandardMaterial._OpacityTextureEnabled = value;
  36125. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36126. },
  36127. enumerable: true,
  36128. configurable: true
  36129. });
  36130. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  36131. get: function () {
  36132. return StandardMaterial._ReflectionTextureEnabled;
  36133. },
  36134. set: function (value) {
  36135. if (StandardMaterial._ReflectionTextureEnabled === value) {
  36136. return;
  36137. }
  36138. StandardMaterial._ReflectionTextureEnabled = value;
  36139. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36140. },
  36141. enumerable: true,
  36142. configurable: true
  36143. });
  36144. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  36145. get: function () {
  36146. return StandardMaterial._EmissiveTextureEnabled;
  36147. },
  36148. set: function (value) {
  36149. if (StandardMaterial._EmissiveTextureEnabled === value) {
  36150. return;
  36151. }
  36152. StandardMaterial._EmissiveTextureEnabled = value;
  36153. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36154. },
  36155. enumerable: true,
  36156. configurable: true
  36157. });
  36158. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  36159. get: function () {
  36160. return StandardMaterial._SpecularTextureEnabled;
  36161. },
  36162. set: function (value) {
  36163. if (StandardMaterial._SpecularTextureEnabled === value) {
  36164. return;
  36165. }
  36166. StandardMaterial._SpecularTextureEnabled = value;
  36167. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36168. },
  36169. enumerable: true,
  36170. configurable: true
  36171. });
  36172. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  36173. get: function () {
  36174. return StandardMaterial._BumpTextureEnabled;
  36175. },
  36176. set: function (value) {
  36177. if (StandardMaterial._BumpTextureEnabled === value) {
  36178. return;
  36179. }
  36180. StandardMaterial._BumpTextureEnabled = value;
  36181. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36182. },
  36183. enumerable: true,
  36184. configurable: true
  36185. });
  36186. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  36187. get: function () {
  36188. return StandardMaterial._LightmapTextureEnabled;
  36189. },
  36190. set: function (value) {
  36191. if (StandardMaterial._LightmapTextureEnabled === value) {
  36192. return;
  36193. }
  36194. StandardMaterial._LightmapTextureEnabled = value;
  36195. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36196. },
  36197. enumerable: true,
  36198. configurable: true
  36199. });
  36200. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  36201. get: function () {
  36202. return StandardMaterial._RefractionTextureEnabled;
  36203. },
  36204. set: function (value) {
  36205. if (StandardMaterial._RefractionTextureEnabled === value) {
  36206. return;
  36207. }
  36208. StandardMaterial._RefractionTextureEnabled = value;
  36209. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36210. },
  36211. enumerable: true,
  36212. configurable: true
  36213. });
  36214. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  36215. get: function () {
  36216. return StandardMaterial._ColorGradingTextureEnabled;
  36217. },
  36218. set: function (value) {
  36219. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  36220. return;
  36221. }
  36222. StandardMaterial._ColorGradingTextureEnabled = value;
  36223. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  36224. },
  36225. enumerable: true,
  36226. configurable: true
  36227. });
  36228. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  36229. get: function () {
  36230. return StandardMaterial._FresnelEnabled;
  36231. },
  36232. set: function (value) {
  36233. if (StandardMaterial._FresnelEnabled === value) {
  36234. return;
  36235. }
  36236. StandardMaterial._FresnelEnabled = value;
  36237. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  36238. },
  36239. enumerable: true,
  36240. configurable: true
  36241. });
  36242. // Flags used to enable or disable a type of texture for all Standard Materials
  36243. StandardMaterial._DiffuseTextureEnabled = true;
  36244. StandardMaterial._AmbientTextureEnabled = true;
  36245. StandardMaterial._OpacityTextureEnabled = true;
  36246. StandardMaterial._ReflectionTextureEnabled = true;
  36247. StandardMaterial._EmissiveTextureEnabled = true;
  36248. StandardMaterial._SpecularTextureEnabled = true;
  36249. StandardMaterial._BumpTextureEnabled = true;
  36250. StandardMaterial._LightmapTextureEnabled = true;
  36251. StandardMaterial._RefractionTextureEnabled = true;
  36252. StandardMaterial._ColorGradingTextureEnabled = true;
  36253. StandardMaterial._FresnelEnabled = true;
  36254. __decorate([
  36255. BABYLON.serializeAsTexture("diffuseTexture")
  36256. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  36257. __decorate([
  36258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36259. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  36260. __decorate([
  36261. BABYLON.serializeAsTexture("ambientTexture")
  36262. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  36263. __decorate([
  36264. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36265. ], StandardMaterial.prototype, "ambientTexture", void 0);
  36266. __decorate([
  36267. BABYLON.serializeAsTexture("opacityTexture")
  36268. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  36269. __decorate([
  36270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36271. ], StandardMaterial.prototype, "opacityTexture", void 0);
  36272. __decorate([
  36273. BABYLON.serializeAsTexture("reflectionTexture")
  36274. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  36275. __decorate([
  36276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36277. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  36278. __decorate([
  36279. BABYLON.serializeAsTexture("emissiveTexture")
  36280. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  36281. __decorate([
  36282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36283. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  36284. __decorate([
  36285. BABYLON.serializeAsTexture("specularTexture")
  36286. ], StandardMaterial.prototype, "_specularTexture", void 0);
  36287. __decorate([
  36288. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36289. ], StandardMaterial.prototype, "specularTexture", void 0);
  36290. __decorate([
  36291. BABYLON.serializeAsTexture("bumpTexture")
  36292. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  36293. __decorate([
  36294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36295. ], StandardMaterial.prototype, "bumpTexture", void 0);
  36296. __decorate([
  36297. BABYLON.serializeAsTexture("lightmapTexture")
  36298. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  36299. __decorate([
  36300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36301. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  36302. __decorate([
  36303. BABYLON.serializeAsTexture("refractionTexture")
  36304. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  36305. __decorate([
  36306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36307. ], StandardMaterial.prototype, "refractionTexture", void 0);
  36308. __decorate([
  36309. BABYLON.serializeAsColor3("ambient")
  36310. ], StandardMaterial.prototype, "ambientColor", void 0);
  36311. __decorate([
  36312. BABYLON.serializeAsColor3("diffuse")
  36313. ], StandardMaterial.prototype, "diffuseColor", void 0);
  36314. __decorate([
  36315. BABYLON.serializeAsColor3("specular")
  36316. ], StandardMaterial.prototype, "specularColor", void 0);
  36317. __decorate([
  36318. BABYLON.serializeAsColor3("emissive")
  36319. ], StandardMaterial.prototype, "emissiveColor", void 0);
  36320. __decorate([
  36321. BABYLON.serialize()
  36322. ], StandardMaterial.prototype, "specularPower", void 0);
  36323. __decorate([
  36324. BABYLON.serialize("useAlphaFromDiffuseTexture")
  36325. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  36326. __decorate([
  36327. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36328. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  36329. __decorate([
  36330. BABYLON.serialize("useEmissiveAsIllumination")
  36331. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  36332. __decorate([
  36333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36334. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  36335. __decorate([
  36336. BABYLON.serialize("linkEmissiveWithDiffuse")
  36337. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  36338. __decorate([
  36339. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36340. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  36341. __decorate([
  36342. BABYLON.serialize("useSpecularOverAlpha")
  36343. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  36344. __decorate([
  36345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36346. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  36347. __decorate([
  36348. BABYLON.serialize("useReflectionOverAlpha")
  36349. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  36350. __decorate([
  36351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36352. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  36353. __decorate([
  36354. BABYLON.serialize("disableLighting")
  36355. ], StandardMaterial.prototype, "_disableLighting", void 0);
  36356. __decorate([
  36357. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36358. ], StandardMaterial.prototype, "disableLighting", void 0);
  36359. __decorate([
  36360. BABYLON.serialize("useParallax")
  36361. ], StandardMaterial.prototype, "_useParallax", void 0);
  36362. __decorate([
  36363. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36364. ], StandardMaterial.prototype, "useParallax", void 0);
  36365. __decorate([
  36366. BABYLON.serialize("useParallaxOcclusion")
  36367. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  36368. __decorate([
  36369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36370. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  36371. __decorate([
  36372. BABYLON.serialize()
  36373. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  36374. __decorate([
  36375. BABYLON.serialize("roughness")
  36376. ], StandardMaterial.prototype, "_roughness", void 0);
  36377. __decorate([
  36378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36379. ], StandardMaterial.prototype, "roughness", void 0);
  36380. __decorate([
  36381. BABYLON.serialize()
  36382. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  36383. __decorate([
  36384. BABYLON.serialize()
  36385. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  36386. __decorate([
  36387. BABYLON.serialize("useLightmapAsShadowmap")
  36388. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  36389. __decorate([
  36390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36391. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  36392. __decorate([
  36393. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  36394. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  36395. __decorate([
  36396. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36397. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  36398. __decorate([
  36399. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  36400. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  36401. __decorate([
  36402. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36403. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  36404. __decorate([
  36405. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  36406. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  36407. __decorate([
  36408. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36409. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  36410. __decorate([
  36411. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  36412. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  36413. __decorate([
  36414. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36415. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  36416. __decorate([
  36417. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  36418. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  36419. __decorate([
  36420. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36421. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  36422. __decorate([
  36423. BABYLON.serialize("useReflectionFresnelFromSpecular")
  36424. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  36425. __decorate([
  36426. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36427. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36428. __decorate([
  36429. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36430. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36431. __decorate([
  36432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36433. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36434. __decorate([
  36435. BABYLON.serialize("maxSimultaneousLights")
  36436. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36437. __decorate([
  36438. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36439. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36440. __decorate([
  36441. BABYLON.serialize("invertNormalMapX")
  36442. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36443. __decorate([
  36444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36445. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36446. __decorate([
  36447. BABYLON.serialize("invertNormalMapY")
  36448. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36449. __decorate([
  36450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36451. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36452. __decorate([
  36453. BABYLON.serialize("twoSidedLighting")
  36454. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36455. __decorate([
  36456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36457. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36458. __decorate([
  36459. BABYLON.serialize()
  36460. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36461. return StandardMaterial;
  36462. }(BABYLON.PushMaterial));
  36463. BABYLON.StandardMaterial = StandardMaterial;
  36464. })(BABYLON || (BABYLON = {}));
  36465. //# sourceMappingURL=babylon.standardMaterial.js.map
  36466. var BABYLON;
  36467. (function (BABYLON) {
  36468. var PBRMaterialDefines = /** @class */ (function (_super) {
  36469. __extends(PBRMaterialDefines, _super);
  36470. function PBRMaterialDefines() {
  36471. var _this = _super.call(this) || this;
  36472. _this.PBR = true;
  36473. _this.MAINUV1 = false;
  36474. _this.MAINUV2 = false;
  36475. _this.UV1 = false;
  36476. _this.UV2 = false;
  36477. _this.ALBEDO = false;
  36478. _this.ALBEDODIRECTUV = 0;
  36479. _this.VERTEXCOLOR = false;
  36480. _this.AMBIENT = false;
  36481. _this.AMBIENTDIRECTUV = 0;
  36482. _this.AMBIENTINGRAYSCALE = false;
  36483. _this.OPACITY = false;
  36484. _this.VERTEXALPHA = false;
  36485. _this.OPACITYDIRECTUV = 0;
  36486. _this.OPACITYRGB = false;
  36487. _this.ALPHATEST = false;
  36488. _this.DEPTHPREPASS = false;
  36489. _this.ALPHABLEND = false;
  36490. _this.ALPHAFROMALBEDO = false;
  36491. _this.ALPHATESTVALUE = 0.5;
  36492. _this.SPECULAROVERALPHA = false;
  36493. _this.RADIANCEOVERALPHA = false;
  36494. _this.ALPHAFRESNEL = false;
  36495. _this.LINEARALPHAFRESNEL = false;
  36496. _this.PREMULTIPLYALPHA = false;
  36497. _this.EMISSIVE = false;
  36498. _this.EMISSIVEDIRECTUV = 0;
  36499. _this.REFLECTIVITY = false;
  36500. _this.REFLECTIVITYDIRECTUV = 0;
  36501. _this.SPECULARTERM = false;
  36502. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36503. _this.MICROSURFACEAUTOMATIC = false;
  36504. _this.LODBASEDMICROSFURACE = false;
  36505. _this.MICROSURFACEMAP = false;
  36506. _this.MICROSURFACEMAPDIRECTUV = 0;
  36507. _this.METALLICWORKFLOW = false;
  36508. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36509. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36510. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36511. _this.AOSTOREINMETALMAPRED = false;
  36512. _this.ENVIRONMENTBRDF = false;
  36513. _this.NORMAL = false;
  36514. _this.TANGENT = false;
  36515. _this.BUMP = false;
  36516. _this.BUMPDIRECTUV = 0;
  36517. _this.PARALLAX = false;
  36518. _this.PARALLAXOCCLUSION = false;
  36519. _this.NORMALXYSCALE = true;
  36520. _this.LIGHTMAP = false;
  36521. _this.LIGHTMAPDIRECTUV = 0;
  36522. _this.USELIGHTMAPASSHADOWMAP = false;
  36523. _this.REFLECTION = false;
  36524. _this.REFLECTIONMAP_3D = false;
  36525. _this.REFLECTIONMAP_SPHERICAL = false;
  36526. _this.REFLECTIONMAP_PLANAR = false;
  36527. _this.REFLECTIONMAP_CUBIC = false;
  36528. _this.REFLECTIONMAP_PROJECTION = false;
  36529. _this.REFLECTIONMAP_SKYBOX = false;
  36530. _this.REFLECTIONMAP_EXPLICIT = false;
  36531. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36532. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36533. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36534. _this.INVERTCUBICMAP = false;
  36535. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36536. _this.USESPHERICALINVERTEX = false;
  36537. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36538. _this.LODINREFLECTIONALPHA = false;
  36539. _this.GAMMAREFLECTION = false;
  36540. _this.RADIANCEOCCLUSION = false;
  36541. _this.HORIZONOCCLUSION = false;
  36542. _this.REFRACTION = false;
  36543. _this.REFRACTIONMAP_3D = false;
  36544. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36545. _this.LODINREFRACTIONALPHA = false;
  36546. _this.GAMMAREFRACTION = false;
  36547. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36548. _this.INSTANCES = false;
  36549. _this.NUM_BONE_INFLUENCERS = 0;
  36550. _this.BonesPerMesh = 0;
  36551. _this.NONUNIFORMSCALING = false;
  36552. _this.MORPHTARGETS = false;
  36553. _this.MORPHTARGETS_NORMAL = false;
  36554. _this.MORPHTARGETS_TANGENT = false;
  36555. _this.NUM_MORPH_INFLUENCERS = 0;
  36556. _this.IMAGEPROCESSING = false;
  36557. _this.VIGNETTE = false;
  36558. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36559. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36560. _this.TONEMAPPING = false;
  36561. _this.CONTRAST = false;
  36562. _this.COLORCURVES = false;
  36563. _this.COLORGRADING = false;
  36564. _this.COLORGRADING3D = false;
  36565. _this.SAMPLER3DGREENDEPTH = false;
  36566. _this.SAMPLER3DBGRMAP = false;
  36567. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36568. _this.EXPOSURE = false;
  36569. _this.USEPHYSICALLIGHTFALLOFF = false;
  36570. _this.TWOSIDEDLIGHTING = false;
  36571. _this.SHADOWFLOAT = false;
  36572. _this.CLIPPLANE = false;
  36573. _this.POINTSIZE = false;
  36574. _this.FOG = false;
  36575. _this.LOGARITHMICDEPTH = false;
  36576. _this.FORCENORMALFORWARD = false;
  36577. _this.rebuild();
  36578. return _this;
  36579. }
  36580. PBRMaterialDefines.prototype.reset = function () {
  36581. _super.prototype.reset.call(this);
  36582. this.ALPHATESTVALUE = 0.5;
  36583. this.PBR = true;
  36584. };
  36585. return PBRMaterialDefines;
  36586. }(BABYLON.MaterialDefines));
  36587. /**
  36588. * The Physically based material base class of BJS.
  36589. *
  36590. * This offers the main features of a standard PBR material.
  36591. * For more information, please refer to the documentation :
  36592. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36593. */
  36594. var PBRBaseMaterial = /** @class */ (function (_super) {
  36595. __extends(PBRBaseMaterial, _super);
  36596. /**
  36597. * Instantiates a new PBRMaterial instance.
  36598. *
  36599. * @param name The material name
  36600. * @param scene The scene the material will be use in.
  36601. */
  36602. function PBRBaseMaterial(name, scene) {
  36603. var _this = _super.call(this, name, scene) || this;
  36604. /**
  36605. * Intensity of the direct lights e.g. the four lights available in your scene.
  36606. * This impacts both the direct diffuse and specular highlights.
  36607. */
  36608. _this._directIntensity = 1.0;
  36609. /**
  36610. * Intensity of the emissive part of the material.
  36611. * This helps controlling the emissive effect without modifying the emissive color.
  36612. */
  36613. _this._emissiveIntensity = 1.0;
  36614. /**
  36615. * Intensity of the environment e.g. how much the environment will light the object
  36616. * either through harmonics for rough material or through the refelction for shiny ones.
  36617. */
  36618. _this._environmentIntensity = 1.0;
  36619. /**
  36620. * This is a special control allowing the reduction of the specular highlights coming from the
  36621. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36622. */
  36623. _this._specularIntensity = 1.0;
  36624. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36625. /**
  36626. * Debug Control allowing disabling the bump map on this material.
  36627. */
  36628. _this._disableBumpMap = false;
  36629. /**
  36630. * AKA Occlusion Texture Intensity in other nomenclature.
  36631. */
  36632. _this._ambientTextureStrength = 1.0;
  36633. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36634. /**
  36635. * AKA Diffuse Color in other nomenclature.
  36636. */
  36637. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36638. /**
  36639. * AKA Specular Color in other nomenclature.
  36640. */
  36641. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36642. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36643. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36644. /**
  36645. * AKA Glossiness in other nomenclature.
  36646. */
  36647. _this._microSurface = 0.9;
  36648. /**
  36649. * source material index of refraction (IOR)' / 'destination material IOR.
  36650. */
  36651. _this._indexOfRefraction = 0.66;
  36652. /**
  36653. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36654. */
  36655. _this._invertRefractionY = false;
  36656. /**
  36657. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36658. * Materials half opaque for instance using refraction could benefit from this control.
  36659. */
  36660. _this._linkRefractionWithTransparency = false;
  36661. _this._useLightmapAsShadowmap = false;
  36662. /**
  36663. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36664. * makes the reflect vector face the model (under horizon).
  36665. */
  36666. _this._useHorizonOcclusion = true;
  36667. /**
  36668. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36669. * too much the area relying on ambient texture to define their ambient occlusion.
  36670. */
  36671. _this._useRadianceOcclusion = true;
  36672. /**
  36673. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36674. */
  36675. _this._useAlphaFromAlbedoTexture = false;
  36676. /**
  36677. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36678. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36679. */
  36680. _this._useSpecularOverAlpha = true;
  36681. /**
  36682. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36683. */
  36684. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36685. /**
  36686. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36687. */
  36688. _this._useRoughnessFromMetallicTextureAlpha = true;
  36689. /**
  36690. * Specifies if the metallic texture contains the roughness information in its green channel.
  36691. */
  36692. _this._useRoughnessFromMetallicTextureGreen = false;
  36693. /**
  36694. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36695. */
  36696. _this._useMetallnessFromMetallicTextureBlue = false;
  36697. /**
  36698. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36699. */
  36700. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36701. /**
  36702. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36703. */
  36704. _this._useAmbientInGrayScale = false;
  36705. /**
  36706. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36707. * The material will try to infer what glossiness each pixel should be.
  36708. */
  36709. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36710. /**
  36711. * BJS is using an harcoded light falloff based on a manually sets up range.
  36712. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36713. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36714. */
  36715. _this._usePhysicalLightFalloff = true;
  36716. /**
  36717. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36718. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36719. */
  36720. _this._useRadianceOverAlpha = true;
  36721. /**
  36722. * Allows using the bump map in parallax mode.
  36723. */
  36724. _this._useParallax = false;
  36725. /**
  36726. * Allows using the bump map in parallax occlusion mode.
  36727. */
  36728. _this._useParallaxOcclusion = false;
  36729. /**
  36730. * Controls the scale bias of the parallax mode.
  36731. */
  36732. _this._parallaxScaleBias = 0.05;
  36733. /**
  36734. * If sets to true, disables all the lights affecting the material.
  36735. */
  36736. _this._disableLighting = false;
  36737. /**
  36738. * Number of Simultaneous lights allowed on the material.
  36739. */
  36740. _this._maxSimultaneousLights = 4;
  36741. /**
  36742. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36743. */
  36744. _this._invertNormalMapX = false;
  36745. /**
  36746. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36747. */
  36748. _this._invertNormalMapY = false;
  36749. /**
  36750. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36751. */
  36752. _this._twoSidedLighting = false;
  36753. /**
  36754. * Defines the alpha limits in alpha test mode.
  36755. */
  36756. _this._alphaCutOff = 0.4;
  36757. /**
  36758. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36759. */
  36760. _this._forceAlphaTest = false;
  36761. /**
  36762. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36763. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36764. */
  36765. _this._useAlphaFresnel = false;
  36766. /**
  36767. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36768. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36769. */
  36770. _this._useLinearAlphaFresnel = false;
  36771. /**
  36772. * The transparency mode of the material.
  36773. */
  36774. _this._transparencyMode = null;
  36775. /**
  36776. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36777. * from cos thetav and roughness:
  36778. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36779. */
  36780. _this._environmentBRDFTexture = null;
  36781. /**
  36782. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36783. */
  36784. _this._forceIrradianceInFragment = false;
  36785. /**
  36786. * Force normal to face away from face.
  36787. */
  36788. _this._forceNormalForward = false;
  36789. /**
  36790. * Force metallic workflow.
  36791. */
  36792. _this._forceMetallicWorkflow = false;
  36793. _this._renderTargets = new BABYLON.SmartArray(16);
  36794. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36795. // Setup the default processing configuration to the scene.
  36796. _this._attachImageProcessingConfiguration(null);
  36797. _this.getRenderTargetTextures = function () {
  36798. _this._renderTargets.reset();
  36799. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36800. _this._renderTargets.push(_this._reflectionTexture);
  36801. }
  36802. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36803. _this._renderTargets.push(_this._refractionTexture);
  36804. }
  36805. return _this._renderTargets;
  36806. };
  36807. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36808. return _this;
  36809. }
  36810. /**
  36811. * Attaches a new image processing configuration to the PBR Material.
  36812. * @param configuration
  36813. */
  36814. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36815. var _this = this;
  36816. if (configuration === this._imageProcessingConfiguration) {
  36817. return;
  36818. }
  36819. // Detaches observer.
  36820. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36821. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36822. }
  36823. // Pick the scene configuration if needed.
  36824. if (!configuration) {
  36825. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36826. }
  36827. else {
  36828. this._imageProcessingConfiguration = configuration;
  36829. }
  36830. // Attaches observer.
  36831. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36832. _this._markAllSubMeshesAsImageProcessingDirty();
  36833. });
  36834. };
  36835. PBRBaseMaterial.prototype.getClassName = function () {
  36836. return "PBRBaseMaterial";
  36837. };
  36838. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36839. get: function () {
  36840. return this._useLogarithmicDepth;
  36841. },
  36842. set: function (value) {
  36843. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36844. },
  36845. enumerable: true,
  36846. configurable: true
  36847. });
  36848. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36849. /**
  36850. * Gets the current transparency mode.
  36851. */
  36852. get: function () {
  36853. return this._transparencyMode;
  36854. },
  36855. /**
  36856. * Sets the transparency mode of the material.
  36857. */
  36858. set: function (value) {
  36859. if (this._transparencyMode === value) {
  36860. return;
  36861. }
  36862. this._transparencyMode = value;
  36863. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36864. this._markAllSubMeshesAsTexturesDirty();
  36865. },
  36866. enumerable: true,
  36867. configurable: true
  36868. });
  36869. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36870. /**
  36871. * Returns true if alpha blending should be disabled.
  36872. */
  36873. get: function () {
  36874. return (this._linkRefractionWithTransparency ||
  36875. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36876. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36877. },
  36878. enumerable: true,
  36879. configurable: true
  36880. });
  36881. /**
  36882. * Specifies whether or not this material should be rendered in alpha blend mode.
  36883. */
  36884. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36885. if (this._disableAlphaBlending) {
  36886. return false;
  36887. }
  36888. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36889. };
  36890. /**
  36891. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36892. */
  36893. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36894. if (this._disableAlphaBlending) {
  36895. return false;
  36896. }
  36897. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36898. };
  36899. /**
  36900. * Specifies whether or not this material should be rendered in alpha test mode.
  36901. */
  36902. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36903. if (this._forceAlphaTest) {
  36904. return true;
  36905. }
  36906. if (this._linkRefractionWithTransparency) {
  36907. return false;
  36908. }
  36909. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36910. };
  36911. /**
  36912. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36913. */
  36914. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36915. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36916. };
  36917. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36918. return this._albedoTexture;
  36919. };
  36920. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36921. var _this = this;
  36922. if (subMesh.effect && this.isFrozen) {
  36923. if (this._wasPreviouslyReady) {
  36924. return true;
  36925. }
  36926. }
  36927. if (!subMesh._materialDefines) {
  36928. subMesh._materialDefines = new PBRMaterialDefines();
  36929. }
  36930. var scene = this.getScene();
  36931. var defines = subMesh._materialDefines;
  36932. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36933. if (defines._renderId === scene.getRenderId()) {
  36934. return true;
  36935. }
  36936. }
  36937. var engine = scene.getEngine();
  36938. // Lights
  36939. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36940. defines._needNormals = true;
  36941. // Textures
  36942. if (defines._areTexturesDirty) {
  36943. defines._needUVs = false;
  36944. if (scene.texturesEnabled) {
  36945. if (scene.getEngine().getCaps().textureLOD) {
  36946. defines.LODBASEDMICROSFURACE = true;
  36947. }
  36948. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36949. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36950. return false;
  36951. }
  36952. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36953. }
  36954. else {
  36955. defines.ALBEDO = false;
  36956. }
  36957. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36958. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36959. return false;
  36960. }
  36961. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36962. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36963. }
  36964. else {
  36965. defines.AMBIENT = false;
  36966. }
  36967. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36968. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36969. return false;
  36970. }
  36971. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36972. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36973. }
  36974. else {
  36975. defines.OPACITY = false;
  36976. }
  36977. var reflectionTexture = this._getReflectionTexture();
  36978. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36979. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36980. return false;
  36981. }
  36982. defines.REFLECTION = true;
  36983. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36984. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36985. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36986. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36987. defines.INVERTCUBICMAP = true;
  36988. }
  36989. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36990. switch (reflectionTexture.coordinatesMode) {
  36991. case BABYLON.Texture.CUBIC_MODE:
  36992. case BABYLON.Texture.INVCUBIC_MODE:
  36993. defines.REFLECTIONMAP_CUBIC = true;
  36994. break;
  36995. case BABYLON.Texture.EXPLICIT_MODE:
  36996. defines.REFLECTIONMAP_EXPLICIT = true;
  36997. break;
  36998. case BABYLON.Texture.PLANAR_MODE:
  36999. defines.REFLECTIONMAP_PLANAR = true;
  37000. break;
  37001. case BABYLON.Texture.PROJECTION_MODE:
  37002. defines.REFLECTIONMAP_PROJECTION = true;
  37003. break;
  37004. case BABYLON.Texture.SKYBOX_MODE:
  37005. defines.REFLECTIONMAP_SKYBOX = true;
  37006. break;
  37007. case BABYLON.Texture.SPHERICAL_MODE:
  37008. defines.REFLECTIONMAP_SPHERICAL = true;
  37009. break;
  37010. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  37011. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  37012. break;
  37013. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  37014. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  37015. break;
  37016. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  37017. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  37018. break;
  37019. }
  37020. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  37021. if (reflectionTexture.sphericalPolynomial) {
  37022. defines.USESPHERICALFROMREFLECTIONMAP = true;
  37023. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  37024. defines.USESPHERICALINVERTEX = false;
  37025. }
  37026. else {
  37027. defines.USESPHERICALINVERTEX = true;
  37028. }
  37029. }
  37030. }
  37031. }
  37032. else {
  37033. defines.REFLECTION = false;
  37034. defines.REFLECTIONMAP_3D = false;
  37035. defines.REFLECTIONMAP_SPHERICAL = false;
  37036. defines.REFLECTIONMAP_PLANAR = false;
  37037. defines.REFLECTIONMAP_CUBIC = false;
  37038. defines.REFLECTIONMAP_PROJECTION = false;
  37039. defines.REFLECTIONMAP_SKYBOX = false;
  37040. defines.REFLECTIONMAP_EXPLICIT = false;
  37041. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  37042. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  37043. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  37044. defines.INVERTCUBICMAP = false;
  37045. defines.USESPHERICALFROMREFLECTIONMAP = false;
  37046. defines.USESPHERICALINVERTEX = false;
  37047. defines.REFLECTIONMAP_OPPOSITEZ = false;
  37048. defines.LODINREFLECTIONALPHA = false;
  37049. defines.GAMMAREFLECTION = false;
  37050. }
  37051. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37052. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  37053. return false;
  37054. }
  37055. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  37056. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  37057. }
  37058. else {
  37059. defines.LIGHTMAP = false;
  37060. }
  37061. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37062. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  37063. return false;
  37064. }
  37065. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  37066. }
  37067. else {
  37068. defines.EMISSIVE = false;
  37069. }
  37070. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37071. if (this._metallicTexture) {
  37072. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  37073. return false;
  37074. }
  37075. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  37076. defines.METALLICWORKFLOW = true;
  37077. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  37078. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  37079. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  37080. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  37081. }
  37082. else if (this._reflectivityTexture) {
  37083. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  37084. return false;
  37085. }
  37086. defines.METALLICWORKFLOW = false;
  37087. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  37088. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  37089. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  37090. }
  37091. else {
  37092. defines.METALLICWORKFLOW = false;
  37093. defines.REFLECTIVITY = false;
  37094. }
  37095. if (this._microSurfaceTexture) {
  37096. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  37097. return false;
  37098. }
  37099. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  37100. }
  37101. else {
  37102. defines.MICROSURFACEMAP = false;
  37103. }
  37104. }
  37105. else {
  37106. defines.REFLECTIVITY = false;
  37107. defines.MICROSURFACEMAP = false;
  37108. }
  37109. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37110. // Bump texure can not be none blocking.
  37111. if (!this._bumpTexture.isReady()) {
  37112. return false;
  37113. }
  37114. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  37115. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37116. defines.PARALLAX = true;
  37117. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  37118. }
  37119. else {
  37120. defines.PARALLAX = false;
  37121. }
  37122. }
  37123. else {
  37124. defines.BUMP = false;
  37125. }
  37126. var refractionTexture = this._getRefractionTexture();
  37127. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37128. if (!refractionTexture.isReadyOrNotBlocking()) {
  37129. return false;
  37130. }
  37131. defines.REFRACTION = true;
  37132. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  37133. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  37134. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  37135. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  37136. if (this._linkRefractionWithTransparency) {
  37137. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  37138. }
  37139. }
  37140. else {
  37141. defines.REFRACTION = false;
  37142. }
  37143. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37144. // This is blocking.
  37145. if (!this._environmentBRDFTexture.isReady()) {
  37146. return false;
  37147. }
  37148. defines.ENVIRONMENTBRDF = true;
  37149. }
  37150. else {
  37151. defines.ENVIRONMENTBRDF = false;
  37152. }
  37153. if (this._shouldUseAlphaFromAlbedoTexture()) {
  37154. defines.ALPHAFROMALBEDO = true;
  37155. }
  37156. else {
  37157. defines.ALPHAFROMALBEDO = false;
  37158. }
  37159. }
  37160. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  37161. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  37162. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  37163. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  37164. defines.METALLICWORKFLOW = true;
  37165. }
  37166. else {
  37167. defines.METALLICWORKFLOW = false;
  37168. }
  37169. if (!this.backFaceCulling && this._twoSidedLighting) {
  37170. defines.TWOSIDEDLIGHTING = true;
  37171. }
  37172. else {
  37173. defines.TWOSIDEDLIGHTING = false;
  37174. }
  37175. defines.ALPHATESTVALUE = this._alphaCutOff;
  37176. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  37177. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  37178. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  37179. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  37180. }
  37181. if (defines._areImageProcessingDirty) {
  37182. if (!this._imageProcessingConfiguration.isReady()) {
  37183. return false;
  37184. }
  37185. this._imageProcessingConfiguration.prepareDefines(defines);
  37186. }
  37187. defines.FORCENORMALFORWARD = this._forceNormalForward;
  37188. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  37189. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  37190. // Misc.
  37191. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  37192. // Values that need to be evaluated on every frame
  37193. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest);
  37194. // Attribs
  37195. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  37196. var bufferMesh = null;
  37197. if (mesh instanceof BABYLON.InstancedMesh) {
  37198. bufferMesh = mesh.sourceMesh;
  37199. }
  37200. else if (mesh instanceof BABYLON.Mesh) {
  37201. bufferMesh = mesh;
  37202. }
  37203. if (bufferMesh) {
  37204. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37205. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  37206. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  37207. var normals = normalVertexBuffer.getData();
  37208. var vertexBufferOffset = normalVertexBuffer.getOffset();
  37209. var strideSize = normalVertexBuffer.getStrideSize();
  37210. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  37211. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  37212. defines.NORMAL = false;
  37213. }
  37214. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37215. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  37216. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  37217. var tangents = tangentVertexBuffer.getData();
  37218. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  37219. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  37220. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  37221. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  37222. defines.TANGENT = false;
  37223. }
  37224. }
  37225. }
  37226. else {
  37227. if (!scene.getEngine().getCaps().standardDerivatives) {
  37228. bufferMesh.createNormals(true);
  37229. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  37230. }
  37231. }
  37232. }
  37233. }
  37234. // Get correct effect
  37235. if (defines.isDirty) {
  37236. defines.markAsProcessed();
  37237. scene.resetCachedMaterial();
  37238. // Fallbacks
  37239. var fallbacks = new BABYLON.EffectFallbacks();
  37240. var fallbackRank = 0;
  37241. if (defines.USESPHERICALINVERTEX) {
  37242. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  37243. }
  37244. if (defines.FOG) {
  37245. fallbacks.addFallback(fallbackRank, "FOG");
  37246. }
  37247. if (defines.POINTSIZE) {
  37248. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  37249. }
  37250. if (defines.LOGARITHMICDEPTH) {
  37251. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  37252. }
  37253. if (defines.PARALLAX) {
  37254. fallbacks.addFallback(fallbackRank, "PARALLAX");
  37255. }
  37256. if (defines.PARALLAXOCCLUSION) {
  37257. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  37258. }
  37259. if (defines.ENVIRONMENTBRDF) {
  37260. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  37261. }
  37262. if (defines.TANGENT) {
  37263. fallbacks.addFallback(fallbackRank++, "TANGENT");
  37264. }
  37265. if (defines.BUMP) {
  37266. fallbacks.addFallback(fallbackRank++, "BUMP");
  37267. }
  37268. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  37269. if (defines.SPECULARTERM) {
  37270. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  37271. }
  37272. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  37273. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  37274. }
  37275. if (defines.LIGHTMAP) {
  37276. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  37277. }
  37278. if (defines.NORMAL) {
  37279. fallbacks.addFallback(fallbackRank++, "NORMAL");
  37280. }
  37281. if (defines.AMBIENT) {
  37282. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  37283. }
  37284. if (defines.EMISSIVE) {
  37285. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  37286. }
  37287. if (defines.VERTEXCOLOR) {
  37288. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  37289. }
  37290. if (defines.NUM_BONE_INFLUENCERS > 0) {
  37291. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  37292. }
  37293. if (defines.MORPHTARGETS) {
  37294. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  37295. }
  37296. //Attributes
  37297. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37298. if (defines.NORMAL) {
  37299. attribs.push(BABYLON.VertexBuffer.NormalKind);
  37300. }
  37301. if (defines.TANGENT) {
  37302. attribs.push(BABYLON.VertexBuffer.TangentKind);
  37303. }
  37304. if (defines.UV1) {
  37305. attribs.push(BABYLON.VertexBuffer.UVKind);
  37306. }
  37307. if (defines.UV2) {
  37308. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37309. }
  37310. if (defines.VERTEXCOLOR) {
  37311. attribs.push(BABYLON.VertexBuffer.ColorKind);
  37312. }
  37313. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  37314. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  37315. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  37316. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  37317. "vFogInfos", "vFogColor", "pointSize",
  37318. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  37319. "mBones",
  37320. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  37321. "vLightingIntensity",
  37322. "logarithmicDepthConstant",
  37323. "vSphericalX", "vSphericalY", "vSphericalZ",
  37324. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  37325. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  37326. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  37327. "vTangentSpaceParams"
  37328. ];
  37329. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  37330. "bumpSampler", "lightmapSampler", "opacitySampler",
  37331. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  37332. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  37333. "microSurfaceSampler", "environmentBrdfSampler"];
  37334. var uniformBuffers = ["Material", "Scene"];
  37335. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  37336. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  37337. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  37338. uniformsNames: uniforms,
  37339. uniformBuffersNames: uniformBuffers,
  37340. samplers: samplers,
  37341. defines: defines,
  37342. maxSimultaneousLights: this._maxSimultaneousLights
  37343. });
  37344. var onCompiled = function (effect) {
  37345. if (_this.onCompiled) {
  37346. _this.onCompiled(effect);
  37347. }
  37348. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  37349. };
  37350. var join = defines.toString();
  37351. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  37352. attributes: attribs,
  37353. uniformsNames: uniforms,
  37354. uniformBuffersNames: uniformBuffers,
  37355. samplers: samplers,
  37356. defines: join,
  37357. fallbacks: fallbacks,
  37358. onCompiled: onCompiled,
  37359. onError: this.onError,
  37360. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  37361. }, engine), defines);
  37362. this.buildUniformLayout();
  37363. }
  37364. if (!subMesh.effect || !subMesh.effect.isReady()) {
  37365. return false;
  37366. }
  37367. defines._renderId = scene.getRenderId();
  37368. this._wasPreviouslyReady = true;
  37369. return true;
  37370. };
  37371. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  37372. // Order is important !
  37373. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  37374. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  37375. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  37376. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  37377. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  37378. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  37379. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  37380. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  37381. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  37382. this._uniformBuffer.addUniform("vBumpInfos", 3);
  37383. this._uniformBuffer.addUniform("albedoMatrix", 16);
  37384. this._uniformBuffer.addUniform("ambientMatrix", 16);
  37385. this._uniformBuffer.addUniform("opacityMatrix", 16);
  37386. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  37387. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  37388. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  37389. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  37390. this._uniformBuffer.addUniform("bumpMatrix", 16);
  37391. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  37392. this._uniformBuffer.addUniform("refractionMatrix", 16);
  37393. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  37394. this._uniformBuffer.addUniform("vReflectionColor", 3);
  37395. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  37396. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  37397. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  37398. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  37399. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  37400. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  37401. this._uniformBuffer.addUniform("pointSize", 1);
  37402. this._uniformBuffer.create();
  37403. };
  37404. PBRBaseMaterial.prototype.unbind = function () {
  37405. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  37406. this._uniformBuffer.setTexture("reflectionSampler", null);
  37407. }
  37408. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  37409. this._uniformBuffer.setTexture("refractionSampler", null);
  37410. }
  37411. _super.prototype.unbind.call(this);
  37412. };
  37413. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  37414. this._activeEffect.setMatrix("world", world);
  37415. };
  37416. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  37417. var scene = this.getScene();
  37418. var defines = subMesh._materialDefines;
  37419. if (!defines) {
  37420. return;
  37421. }
  37422. var effect = subMesh.effect;
  37423. if (!effect) {
  37424. return;
  37425. }
  37426. this._activeEffect = effect;
  37427. // Matrices
  37428. this.bindOnlyWorldMatrix(world);
  37429. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37430. // Bones
  37431. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37432. var reflectionTexture = null;
  37433. if (mustRebind) {
  37434. this._uniformBuffer.bindToEffect(effect, "Material");
  37435. this.bindViewProjection(effect);
  37436. reflectionTexture = this._getReflectionTexture();
  37437. var refractionTexture = this._getRefractionTexture();
  37438. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37439. // Texture uniforms
  37440. if (scene.texturesEnabled) {
  37441. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37442. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37443. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37444. }
  37445. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37446. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37447. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37448. }
  37449. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37450. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37451. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37452. }
  37453. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37454. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37455. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37456. var polynomials = reflectionTexture.sphericalPolynomial;
  37457. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37458. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37459. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37460. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37461. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37462. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37463. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37464. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37465. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37466. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37467. }
  37468. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37469. }
  37470. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37471. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37472. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37473. }
  37474. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37475. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37476. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37477. }
  37478. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37479. if (this._metallicTexture) {
  37480. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37481. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37482. }
  37483. else if (this._reflectivityTexture) {
  37484. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37485. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37486. }
  37487. if (this._microSurfaceTexture) {
  37488. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37489. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37490. }
  37491. }
  37492. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37493. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37494. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37495. if (scene._mirroredCameraPosition) {
  37496. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37497. }
  37498. else {
  37499. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37500. }
  37501. }
  37502. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37503. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37504. var depth = 1.0;
  37505. if (!refractionTexture.isCube) {
  37506. if (refractionTexture.depth) {
  37507. depth = refractionTexture.depth;
  37508. }
  37509. }
  37510. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37511. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37512. }
  37513. }
  37514. // Point size
  37515. if (this.pointsCloud) {
  37516. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37517. }
  37518. // Colors
  37519. if (defines.METALLICWORKFLOW) {
  37520. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37521. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37522. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37523. }
  37524. else {
  37525. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37526. }
  37527. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37528. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37529. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37530. // Misc
  37531. this._lightingInfos.x = this._directIntensity;
  37532. this._lightingInfos.y = this._emissiveIntensity;
  37533. this._lightingInfos.z = this._environmentIntensity;
  37534. this._lightingInfos.w = this._specularIntensity;
  37535. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37536. }
  37537. // Textures
  37538. if (scene.texturesEnabled) {
  37539. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37540. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37541. }
  37542. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37543. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37544. }
  37545. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37546. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37547. }
  37548. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37549. if (defines.LODBASEDMICROSFURACE) {
  37550. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37551. }
  37552. else {
  37553. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37554. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37555. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37556. }
  37557. }
  37558. if (defines.ENVIRONMENTBRDF) {
  37559. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37560. }
  37561. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37562. if (defines.LODBASEDMICROSFURACE) {
  37563. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37564. }
  37565. else {
  37566. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37567. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37568. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37569. }
  37570. }
  37571. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37572. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37573. }
  37574. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37575. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37576. }
  37577. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37578. if (this._metallicTexture) {
  37579. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37580. }
  37581. else if (this._reflectivityTexture) {
  37582. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37583. }
  37584. if (this._microSurfaceTexture) {
  37585. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37586. }
  37587. }
  37588. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37589. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37590. }
  37591. }
  37592. // Clip plane
  37593. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37594. // Colors
  37595. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37596. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37597. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37598. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37599. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37600. }
  37601. if (mustRebind || !this.isFrozen) {
  37602. // Lights
  37603. if (scene.lightsEnabled && !this._disableLighting) {
  37604. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37605. }
  37606. // View
  37607. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37608. this.bindView(effect);
  37609. }
  37610. // Fog
  37611. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37612. // Morph targets
  37613. if (defines.NUM_MORPH_INFLUENCERS) {
  37614. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37615. }
  37616. // image processing
  37617. this._imageProcessingConfiguration.bind(this._activeEffect);
  37618. // Log. depth
  37619. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37620. }
  37621. this._uniformBuffer.update();
  37622. this._afterBind(mesh);
  37623. };
  37624. PBRBaseMaterial.prototype.getAnimatables = function () {
  37625. var results = [];
  37626. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37627. results.push(this._albedoTexture);
  37628. }
  37629. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37630. results.push(this._ambientTexture);
  37631. }
  37632. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37633. results.push(this._opacityTexture);
  37634. }
  37635. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37636. results.push(this._reflectionTexture);
  37637. }
  37638. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37639. results.push(this._emissiveTexture);
  37640. }
  37641. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37642. results.push(this._metallicTexture);
  37643. }
  37644. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37645. results.push(this._reflectivityTexture);
  37646. }
  37647. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37648. results.push(this._bumpTexture);
  37649. }
  37650. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37651. results.push(this._lightmapTexture);
  37652. }
  37653. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37654. results.push(this._refractionTexture);
  37655. }
  37656. return results;
  37657. };
  37658. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37659. if (this._reflectionTexture) {
  37660. return this._reflectionTexture;
  37661. }
  37662. return this.getScene().environmentTexture;
  37663. };
  37664. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37665. if (this._refractionTexture) {
  37666. return this._refractionTexture;
  37667. }
  37668. if (this._linkRefractionWithTransparency) {
  37669. return this.getScene().environmentTexture;
  37670. }
  37671. return null;
  37672. };
  37673. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37674. if (forceDisposeTextures) {
  37675. if (this._albedoTexture) {
  37676. this._albedoTexture.dispose();
  37677. }
  37678. if (this._ambientTexture) {
  37679. this._ambientTexture.dispose();
  37680. }
  37681. if (this._opacityTexture) {
  37682. this._opacityTexture.dispose();
  37683. }
  37684. if (this._reflectionTexture) {
  37685. this._reflectionTexture.dispose();
  37686. }
  37687. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37688. this._environmentBRDFTexture.dispose();
  37689. }
  37690. if (this._emissiveTexture) {
  37691. this._emissiveTexture.dispose();
  37692. }
  37693. if (this._metallicTexture) {
  37694. this._metallicTexture.dispose();
  37695. }
  37696. if (this._reflectivityTexture) {
  37697. this._reflectivityTexture.dispose();
  37698. }
  37699. if (this._bumpTexture) {
  37700. this._bumpTexture.dispose();
  37701. }
  37702. if (this._lightmapTexture) {
  37703. this._lightmapTexture.dispose();
  37704. }
  37705. if (this._refractionTexture) {
  37706. this._refractionTexture.dispose();
  37707. }
  37708. }
  37709. this._renderTargets.dispose();
  37710. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37711. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37712. }
  37713. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37714. };
  37715. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37716. __decorate([
  37717. BABYLON.serializeAsImageProcessingConfiguration()
  37718. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37719. __decorate([
  37720. BABYLON.serialize()
  37721. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37722. __decorate([
  37723. BABYLON.serialize()
  37724. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37725. return PBRBaseMaterial;
  37726. }(BABYLON.PushMaterial));
  37727. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37728. })(BABYLON || (BABYLON = {}));
  37729. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37730. var BABYLON;
  37731. (function (BABYLON) {
  37732. /**
  37733. * The Physically based simple base material of BJS.
  37734. *
  37735. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37736. * It is used as the base class for both the specGloss and metalRough conventions.
  37737. */
  37738. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37739. __extends(PBRBaseSimpleMaterial, _super);
  37740. /**
  37741. * Instantiates a new PBRMaterial instance.
  37742. *
  37743. * @param name The material name
  37744. * @param scene The scene the material will be use in.
  37745. */
  37746. function PBRBaseSimpleMaterial(name, scene) {
  37747. var _this = _super.call(this, name, scene) || this;
  37748. /**
  37749. * Number of Simultaneous lights allowed on the material.
  37750. */
  37751. _this.maxSimultaneousLights = 4;
  37752. /**
  37753. * If sets to true, disables all the lights affecting the material.
  37754. */
  37755. _this.disableLighting = false;
  37756. /**
  37757. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37758. */
  37759. _this.invertNormalMapX = false;
  37760. /**
  37761. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37762. */
  37763. _this.invertNormalMapY = false;
  37764. /**
  37765. * Emissivie color used to self-illuminate the model.
  37766. */
  37767. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37768. /**
  37769. * Occlusion Channel Strenght.
  37770. */
  37771. _this.occlusionStrength = 1.0;
  37772. _this.useLightmapAsShadowmap = false;
  37773. _this._useAlphaFromAlbedoTexture = true;
  37774. _this._useAmbientInGrayScale = true;
  37775. return _this;
  37776. }
  37777. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37778. /**
  37779. * Gets the current double sided mode.
  37780. */
  37781. get: function () {
  37782. return this._twoSidedLighting;
  37783. },
  37784. /**
  37785. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37786. */
  37787. set: function (value) {
  37788. if (this._twoSidedLighting === value) {
  37789. return;
  37790. }
  37791. this._twoSidedLighting = value;
  37792. this.backFaceCulling = !value;
  37793. this._markAllSubMeshesAsTexturesDirty();
  37794. },
  37795. enumerable: true,
  37796. configurable: true
  37797. });
  37798. /**
  37799. * Return the active textures of the material.
  37800. */
  37801. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37802. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37803. if (this.environmentTexture) {
  37804. activeTextures.push(this.environmentTexture);
  37805. }
  37806. if (this.normalTexture) {
  37807. activeTextures.push(this.normalTexture);
  37808. }
  37809. if (this.emissiveTexture) {
  37810. activeTextures.push(this.emissiveTexture);
  37811. }
  37812. if (this.occlusionTexture) {
  37813. activeTextures.push(this.occlusionTexture);
  37814. }
  37815. if (this.lightmapTexture) {
  37816. activeTextures.push(this.lightmapTexture);
  37817. }
  37818. return activeTextures;
  37819. };
  37820. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37821. if (_super.prototype.hasTexture.call(this, texture)) {
  37822. return true;
  37823. }
  37824. if (this.lightmapTexture === texture) {
  37825. return true;
  37826. }
  37827. return false;
  37828. };
  37829. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37830. return "PBRBaseSimpleMaterial";
  37831. };
  37832. __decorate([
  37833. BABYLON.serialize(),
  37834. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37835. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37836. __decorate([
  37837. BABYLON.serialize(),
  37838. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37839. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37840. __decorate([
  37841. BABYLON.serializeAsTexture(),
  37842. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37843. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37844. __decorate([
  37845. BABYLON.serialize(),
  37846. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37847. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37848. __decorate([
  37849. BABYLON.serialize(),
  37850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37851. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37852. __decorate([
  37853. BABYLON.serializeAsTexture(),
  37854. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37855. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37856. __decorate([
  37857. BABYLON.serializeAsColor3("emissive"),
  37858. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37859. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37860. __decorate([
  37861. BABYLON.serializeAsTexture(),
  37862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37863. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37864. __decorate([
  37865. BABYLON.serialize(),
  37866. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37867. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37868. __decorate([
  37869. BABYLON.serializeAsTexture(),
  37870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37871. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37872. __decorate([
  37873. BABYLON.serialize(),
  37874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37875. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37876. __decorate([
  37877. BABYLON.serialize()
  37878. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37879. __decorate([
  37880. BABYLON.serializeAsTexture(),
  37881. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37882. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37883. __decorate([
  37884. BABYLON.serialize(),
  37885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37886. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37887. return PBRBaseSimpleMaterial;
  37888. }(BABYLON.PBRBaseMaterial));
  37889. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37890. })(BABYLON || (BABYLON = {}));
  37891. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37892. var BABYLON;
  37893. (function (BABYLON) {
  37894. /**
  37895. * The Physically based material of BJS.
  37896. *
  37897. * This offers the main features of a standard PBR material.
  37898. * For more information, please refer to the documentation :
  37899. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37900. */
  37901. var PBRMaterial = /** @class */ (function (_super) {
  37902. __extends(PBRMaterial, _super);
  37903. /**
  37904. * Instantiates a new PBRMaterial instance.
  37905. *
  37906. * @param name The material name
  37907. * @param scene The scene the material will be use in.
  37908. */
  37909. function PBRMaterial(name, scene) {
  37910. var _this = _super.call(this, name, scene) || this;
  37911. /**
  37912. * Intensity of the direct lights e.g. the four lights available in your scene.
  37913. * This impacts both the direct diffuse and specular highlights.
  37914. */
  37915. _this.directIntensity = 1.0;
  37916. /**
  37917. * Intensity of the emissive part of the material.
  37918. * This helps controlling the emissive effect without modifying the emissive color.
  37919. */
  37920. _this.emissiveIntensity = 1.0;
  37921. /**
  37922. * Intensity of the environment e.g. how much the environment will light the object
  37923. * either through harmonics for rough material or through the refelction for shiny ones.
  37924. */
  37925. _this.environmentIntensity = 1.0;
  37926. /**
  37927. * This is a special control allowing the reduction of the specular highlights coming from the
  37928. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37929. */
  37930. _this.specularIntensity = 1.0;
  37931. /**
  37932. * Debug Control allowing disabling the bump map on this material.
  37933. */
  37934. _this.disableBumpMap = false;
  37935. /**
  37936. * AKA Occlusion Texture Intensity in other nomenclature.
  37937. */
  37938. _this.ambientTextureStrength = 1.0;
  37939. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37940. /**
  37941. * AKA Diffuse Color in other nomenclature.
  37942. */
  37943. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37944. /**
  37945. * AKA Specular Color in other nomenclature.
  37946. */
  37947. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37948. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37949. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37950. /**
  37951. * AKA Glossiness in other nomenclature.
  37952. */
  37953. _this.microSurface = 1.0;
  37954. /**
  37955. * source material index of refraction (IOR)' / 'destination material IOR.
  37956. */
  37957. _this.indexOfRefraction = 0.66;
  37958. /**
  37959. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37960. */
  37961. _this.invertRefractionY = false;
  37962. /**
  37963. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37964. * Materials half opaque for instance using refraction could benefit from this control.
  37965. */
  37966. _this.linkRefractionWithTransparency = false;
  37967. _this.useLightmapAsShadowmap = false;
  37968. /**
  37969. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37970. */
  37971. _this.useAlphaFromAlbedoTexture = false;
  37972. /**
  37973. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37974. */
  37975. _this.forceAlphaTest = false;
  37976. /**
  37977. * Defines the alpha limits in alpha test mode.
  37978. */
  37979. _this.alphaCutOff = 0.4;
  37980. /**
  37981. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37982. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37983. */
  37984. _this.useSpecularOverAlpha = true;
  37985. /**
  37986. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37987. */
  37988. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37989. /**
  37990. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37991. */
  37992. _this.useRoughnessFromMetallicTextureAlpha = true;
  37993. /**
  37994. * Specifies if the metallic texture contains the roughness information in its green channel.
  37995. */
  37996. _this.useRoughnessFromMetallicTextureGreen = false;
  37997. /**
  37998. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37999. */
  38000. _this.useMetallnessFromMetallicTextureBlue = false;
  38001. /**
  38002. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  38003. */
  38004. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  38005. /**
  38006. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  38007. */
  38008. _this.useAmbientInGrayScale = false;
  38009. /**
  38010. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  38011. * The material will try to infer what glossiness each pixel should be.
  38012. */
  38013. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  38014. /**
  38015. * BJS is using an harcoded light falloff based on a manually sets up range.
  38016. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  38017. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  38018. */
  38019. _this.usePhysicalLightFalloff = true;
  38020. /**
  38021. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  38022. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  38023. */
  38024. _this.useRadianceOverAlpha = true;
  38025. /**
  38026. * Allows using the bump map in parallax mode.
  38027. */
  38028. _this.useParallax = false;
  38029. /**
  38030. * Allows using the bump map in parallax occlusion mode.
  38031. */
  38032. _this.useParallaxOcclusion = false;
  38033. /**
  38034. * Controls the scale bias of the parallax mode.
  38035. */
  38036. _this.parallaxScaleBias = 0.05;
  38037. /**
  38038. * If sets to true, disables all the lights affecting the material.
  38039. */
  38040. _this.disableLighting = false;
  38041. /**
  38042. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  38043. */
  38044. _this.forceIrradianceInFragment = false;
  38045. /**
  38046. * Number of Simultaneous lights allowed on the material.
  38047. */
  38048. _this.maxSimultaneousLights = 4;
  38049. /**
  38050. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38051. */
  38052. _this.invertNormalMapX = false;
  38053. /**
  38054. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38055. */
  38056. _this.invertNormalMapY = false;
  38057. /**
  38058. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38059. */
  38060. _this.twoSidedLighting = false;
  38061. /**
  38062. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38063. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  38064. */
  38065. _this.useAlphaFresnel = false;
  38066. /**
  38067. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38068. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  38069. */
  38070. _this.useLinearAlphaFresnel = false;
  38071. /**
  38072. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  38073. * And/Or occlude the blended part.
  38074. */
  38075. _this.environmentBRDFTexture = null;
  38076. /**
  38077. * Force normal to face away from face.
  38078. */
  38079. _this.forceNormalForward = false;
  38080. /**
  38081. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  38082. * makes the reflect vector face the model (under horizon).
  38083. */
  38084. _this.useHorizonOcclusion = true;
  38085. /**
  38086. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  38087. * too much the area relying on ambient texture to define their ambient occlusion.
  38088. */
  38089. _this.useRadianceOcclusion = true;
  38090. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  38091. return _this;
  38092. }
  38093. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  38094. /**
  38095. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  38096. */
  38097. get: function () {
  38098. return this._PBRMATERIAL_OPAQUE;
  38099. },
  38100. enumerable: true,
  38101. configurable: true
  38102. });
  38103. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  38104. /**
  38105. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  38106. */
  38107. get: function () {
  38108. return this._PBRMATERIAL_ALPHATEST;
  38109. },
  38110. enumerable: true,
  38111. configurable: true
  38112. });
  38113. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  38114. /**
  38115. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38116. */
  38117. get: function () {
  38118. return this._PBRMATERIAL_ALPHABLEND;
  38119. },
  38120. enumerable: true,
  38121. configurable: true
  38122. });
  38123. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  38124. /**
  38125. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  38126. * They are also discarded below the alpha cutoff threshold to improve performances.
  38127. */
  38128. get: function () {
  38129. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  38130. },
  38131. enumerable: true,
  38132. configurable: true
  38133. });
  38134. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  38135. /**
  38136. * Gets the image processing configuration used either in this material.
  38137. */
  38138. get: function () {
  38139. return this._imageProcessingConfiguration;
  38140. },
  38141. /**
  38142. * Sets the Default image processing configuration used either in the this material.
  38143. *
  38144. * If sets to null, the scene one is in use.
  38145. */
  38146. set: function (value) {
  38147. this._attachImageProcessingConfiguration(value);
  38148. // Ensure the effect will be rebuilt.
  38149. this._markAllSubMeshesAsTexturesDirty();
  38150. },
  38151. enumerable: true,
  38152. configurable: true
  38153. });
  38154. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  38155. /**
  38156. * Gets wether the color curves effect is enabled.
  38157. */
  38158. get: function () {
  38159. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38160. },
  38161. /**
  38162. * Sets wether the color curves effect is enabled.
  38163. */
  38164. set: function (value) {
  38165. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38166. },
  38167. enumerable: true,
  38168. configurable: true
  38169. });
  38170. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  38171. /**
  38172. * Gets wether the color grading effect is enabled.
  38173. */
  38174. get: function () {
  38175. return this.imageProcessingConfiguration.colorGradingEnabled;
  38176. },
  38177. /**
  38178. * Gets wether the color grading effect is enabled.
  38179. */
  38180. set: function (value) {
  38181. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38182. },
  38183. enumerable: true,
  38184. configurable: true
  38185. });
  38186. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  38187. /**
  38188. * Gets wether tonemapping is enabled or not.
  38189. */
  38190. get: function () {
  38191. return this._imageProcessingConfiguration.toneMappingEnabled;
  38192. },
  38193. /**
  38194. * Sets wether tonemapping is enabled or not
  38195. */
  38196. set: function (value) {
  38197. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38198. },
  38199. enumerable: true,
  38200. configurable: true
  38201. });
  38202. ;
  38203. ;
  38204. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  38205. /**
  38206. * The camera exposure used on this material.
  38207. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38208. * This corresponds to a photographic exposure.
  38209. */
  38210. get: function () {
  38211. return this._imageProcessingConfiguration.exposure;
  38212. },
  38213. /**
  38214. * The camera exposure used on this material.
  38215. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38216. * This corresponds to a photographic exposure.
  38217. */
  38218. set: function (value) {
  38219. this._imageProcessingConfiguration.exposure = value;
  38220. },
  38221. enumerable: true,
  38222. configurable: true
  38223. });
  38224. ;
  38225. ;
  38226. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  38227. /**
  38228. * Gets The camera contrast used on this material.
  38229. */
  38230. get: function () {
  38231. return this._imageProcessingConfiguration.contrast;
  38232. },
  38233. /**
  38234. * Sets The camera contrast used on this material.
  38235. */
  38236. set: function (value) {
  38237. this._imageProcessingConfiguration.contrast = value;
  38238. },
  38239. enumerable: true,
  38240. configurable: true
  38241. });
  38242. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  38243. /**
  38244. * Gets the Color Grading 2D Lookup Texture.
  38245. */
  38246. get: function () {
  38247. return this._imageProcessingConfiguration.colorGradingTexture;
  38248. },
  38249. /**
  38250. * Sets the Color Grading 2D Lookup Texture.
  38251. */
  38252. set: function (value) {
  38253. this._imageProcessingConfiguration.colorGradingTexture = value;
  38254. },
  38255. enumerable: true,
  38256. configurable: true
  38257. });
  38258. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  38259. /**
  38260. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38261. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38262. * 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;
  38263. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38264. */
  38265. get: function () {
  38266. return this._imageProcessingConfiguration.colorCurves;
  38267. },
  38268. /**
  38269. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38270. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38271. * 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;
  38272. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38273. */
  38274. set: function (value) {
  38275. this._imageProcessingConfiguration.colorCurves = value;
  38276. },
  38277. enumerable: true,
  38278. configurable: true
  38279. });
  38280. PBRMaterial.prototype.getClassName = function () {
  38281. return "PBRMaterial";
  38282. };
  38283. PBRMaterial.prototype.getActiveTextures = function () {
  38284. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38285. if (this._albedoTexture) {
  38286. activeTextures.push(this._albedoTexture);
  38287. }
  38288. if (this._ambientTexture) {
  38289. activeTextures.push(this._ambientTexture);
  38290. }
  38291. if (this._opacityTexture) {
  38292. activeTextures.push(this._opacityTexture);
  38293. }
  38294. if (this._reflectionTexture) {
  38295. activeTextures.push(this._reflectionTexture);
  38296. }
  38297. if (this._emissiveTexture) {
  38298. activeTextures.push(this._emissiveTexture);
  38299. }
  38300. if (this._reflectivityTexture) {
  38301. activeTextures.push(this._reflectivityTexture);
  38302. }
  38303. if (this._metallicTexture) {
  38304. activeTextures.push(this._metallicTexture);
  38305. }
  38306. if (this._microSurfaceTexture) {
  38307. activeTextures.push(this._microSurfaceTexture);
  38308. }
  38309. if (this._bumpTexture) {
  38310. activeTextures.push(this._bumpTexture);
  38311. }
  38312. if (this._lightmapTexture) {
  38313. activeTextures.push(this._lightmapTexture);
  38314. }
  38315. if (this._refractionTexture) {
  38316. activeTextures.push(this._refractionTexture);
  38317. }
  38318. return activeTextures;
  38319. };
  38320. PBRMaterial.prototype.hasTexture = function (texture) {
  38321. if (_super.prototype.hasTexture.call(this, texture)) {
  38322. return true;
  38323. }
  38324. if (this._albedoTexture === texture) {
  38325. return true;
  38326. }
  38327. if (this._ambientTexture === texture) {
  38328. return true;
  38329. }
  38330. if (this._opacityTexture === texture) {
  38331. return true;
  38332. }
  38333. if (this._reflectionTexture === texture) {
  38334. return true;
  38335. }
  38336. if (this._reflectivityTexture === texture) {
  38337. return true;
  38338. }
  38339. if (this._metallicTexture === texture) {
  38340. return true;
  38341. }
  38342. if (this._microSurfaceTexture === texture) {
  38343. return true;
  38344. }
  38345. if (this._bumpTexture === texture) {
  38346. return true;
  38347. }
  38348. if (this._lightmapTexture === texture) {
  38349. return true;
  38350. }
  38351. if (this._refractionTexture === texture) {
  38352. return true;
  38353. }
  38354. return false;
  38355. };
  38356. PBRMaterial.prototype.clone = function (name) {
  38357. var _this = this;
  38358. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  38359. clone.id = name;
  38360. clone.name = name;
  38361. return clone;
  38362. };
  38363. PBRMaterial.prototype.serialize = function () {
  38364. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38365. serializationObject.customType = "BABYLON.PBRMaterial";
  38366. return serializationObject;
  38367. };
  38368. // Statics
  38369. PBRMaterial.Parse = function (source, scene, rootUrl) {
  38370. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  38371. };
  38372. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  38373. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  38374. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  38375. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  38376. __decorate([
  38377. BABYLON.serialize(),
  38378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38379. ], PBRMaterial.prototype, "directIntensity", void 0);
  38380. __decorate([
  38381. BABYLON.serialize(),
  38382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38383. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  38384. __decorate([
  38385. BABYLON.serialize(),
  38386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38387. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  38388. __decorate([
  38389. BABYLON.serialize(),
  38390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38391. ], PBRMaterial.prototype, "specularIntensity", void 0);
  38392. __decorate([
  38393. BABYLON.serialize(),
  38394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38395. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  38396. __decorate([
  38397. BABYLON.serializeAsTexture(),
  38398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38399. ], PBRMaterial.prototype, "albedoTexture", void 0);
  38400. __decorate([
  38401. BABYLON.serializeAsTexture(),
  38402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38403. ], PBRMaterial.prototype, "ambientTexture", void 0);
  38404. __decorate([
  38405. BABYLON.serialize(),
  38406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38407. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  38408. __decorate([
  38409. BABYLON.serializeAsTexture(),
  38410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38411. ], PBRMaterial.prototype, "opacityTexture", void 0);
  38412. __decorate([
  38413. BABYLON.serializeAsTexture(),
  38414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38415. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  38416. __decorate([
  38417. BABYLON.serializeAsTexture(),
  38418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38419. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  38420. __decorate([
  38421. BABYLON.serializeAsTexture(),
  38422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38423. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  38424. __decorate([
  38425. BABYLON.serializeAsTexture(),
  38426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38427. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38428. __decorate([
  38429. BABYLON.serialize(),
  38430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38431. ], PBRMaterial.prototype, "metallic", void 0);
  38432. __decorate([
  38433. BABYLON.serialize(),
  38434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38435. ], PBRMaterial.prototype, "roughness", void 0);
  38436. __decorate([
  38437. BABYLON.serializeAsTexture(),
  38438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38439. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38440. __decorate([
  38441. BABYLON.serializeAsTexture(),
  38442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38443. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38444. __decorate([
  38445. BABYLON.serializeAsTexture(),
  38446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38447. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38448. __decorate([
  38449. BABYLON.serializeAsTexture(),
  38450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38451. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38452. __decorate([
  38453. BABYLON.serializeAsColor3("ambient"),
  38454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38455. ], PBRMaterial.prototype, "ambientColor", void 0);
  38456. __decorate([
  38457. BABYLON.serializeAsColor3("albedo"),
  38458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38459. ], PBRMaterial.prototype, "albedoColor", void 0);
  38460. __decorate([
  38461. BABYLON.serializeAsColor3("reflectivity"),
  38462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38463. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38464. __decorate([
  38465. BABYLON.serializeAsColor3("reflection"),
  38466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38467. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38468. __decorate([
  38469. BABYLON.serializeAsColor3("emissive"),
  38470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38471. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38472. __decorate([
  38473. BABYLON.serialize(),
  38474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38475. ], PBRMaterial.prototype, "microSurface", void 0);
  38476. __decorate([
  38477. BABYLON.serialize(),
  38478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38479. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38480. __decorate([
  38481. BABYLON.serialize(),
  38482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38483. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38484. __decorate([
  38485. BABYLON.serialize(),
  38486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38487. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38488. __decorate([
  38489. BABYLON.serialize(),
  38490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38491. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38492. __decorate([
  38493. BABYLON.serialize(),
  38494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38495. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38496. __decorate([
  38497. BABYLON.serialize(),
  38498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38499. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38500. __decorate([
  38501. BABYLON.serialize(),
  38502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38503. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38504. __decorate([
  38505. BABYLON.serialize(),
  38506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38507. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38508. __decorate([
  38509. BABYLON.serialize(),
  38510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38511. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38512. __decorate([
  38513. BABYLON.serialize(),
  38514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38515. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38516. __decorate([
  38517. BABYLON.serialize(),
  38518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38519. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38520. __decorate([
  38521. BABYLON.serialize(),
  38522. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38523. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38524. __decorate([
  38525. BABYLON.serialize(),
  38526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38527. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38528. __decorate([
  38529. BABYLON.serialize(),
  38530. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38531. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38532. __decorate([
  38533. BABYLON.serialize(),
  38534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38535. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38536. __decorate([
  38537. BABYLON.serialize(),
  38538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38539. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38540. __decorate([
  38541. BABYLON.serialize(),
  38542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38543. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38544. __decorate([
  38545. BABYLON.serialize(),
  38546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38547. ], PBRMaterial.prototype, "useParallax", void 0);
  38548. __decorate([
  38549. BABYLON.serialize(),
  38550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38551. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38552. __decorate([
  38553. BABYLON.serialize(),
  38554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38555. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38556. __decorate([
  38557. BABYLON.serialize(),
  38558. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38559. ], PBRMaterial.prototype, "disableLighting", void 0);
  38560. __decorate([
  38561. BABYLON.serialize(),
  38562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38563. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38564. __decorate([
  38565. BABYLON.serialize(),
  38566. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38567. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38568. __decorate([
  38569. BABYLON.serialize(),
  38570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38571. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38572. __decorate([
  38573. BABYLON.serialize(),
  38574. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38575. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38576. __decorate([
  38577. BABYLON.serialize(),
  38578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38579. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38580. __decorate([
  38581. BABYLON.serialize(),
  38582. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38583. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38584. __decorate([
  38585. BABYLON.serialize(),
  38586. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38587. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38588. __decorate([
  38589. BABYLON.serializeAsTexture(),
  38590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38591. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38592. __decorate([
  38593. BABYLON.serialize(),
  38594. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38595. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38596. __decorate([
  38597. BABYLON.serialize(),
  38598. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38599. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38600. __decorate([
  38601. BABYLON.serialize(),
  38602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38603. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38604. return PBRMaterial;
  38605. }(BABYLON.PBRBaseMaterial));
  38606. BABYLON.PBRMaterial = PBRMaterial;
  38607. })(BABYLON || (BABYLON = {}));
  38608. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38609. var BABYLON;
  38610. (function (BABYLON) {
  38611. /**
  38612. * The PBR material of BJS following the metal roughness convention.
  38613. *
  38614. * This fits to the PBR convention in the GLTF definition:
  38615. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38616. */
  38617. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38618. __extends(PBRMetallicRoughnessMaterial, _super);
  38619. /**
  38620. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38621. *
  38622. * @param name The material name
  38623. * @param scene The scene the material will be use in.
  38624. */
  38625. function PBRMetallicRoughnessMaterial(name, scene) {
  38626. var _this = _super.call(this, name, scene) || this;
  38627. _this._useRoughnessFromMetallicTextureAlpha = false;
  38628. _this._useRoughnessFromMetallicTextureGreen = true;
  38629. _this._useMetallnessFromMetallicTextureBlue = true;
  38630. _this._forceMetallicWorkflow = true;
  38631. return _this;
  38632. }
  38633. /**
  38634. * Return the currrent class name of the material.
  38635. */
  38636. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38637. return "PBRMetallicRoughnessMaterial";
  38638. };
  38639. /**
  38640. * Return the active textures of the material.
  38641. */
  38642. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38643. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38644. if (this.baseTexture) {
  38645. activeTextures.push(this.baseTexture);
  38646. }
  38647. if (this.metallicRoughnessTexture) {
  38648. activeTextures.push(this.metallicRoughnessTexture);
  38649. }
  38650. return activeTextures;
  38651. };
  38652. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38653. if (_super.prototype.hasTexture.call(this, texture)) {
  38654. return true;
  38655. }
  38656. if (this.baseTexture === texture) {
  38657. return true;
  38658. }
  38659. if (this.metallicRoughnessTexture === texture) {
  38660. return true;
  38661. }
  38662. return false;
  38663. };
  38664. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38665. var _this = this;
  38666. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38667. clone.id = name;
  38668. clone.name = name;
  38669. return clone;
  38670. };
  38671. /**
  38672. * Serialize the material to a parsable JSON object.
  38673. */
  38674. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38675. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38676. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38677. return serializationObject;
  38678. };
  38679. /**
  38680. * Parses a JSON object correponding to the serialize function.
  38681. */
  38682. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38683. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38684. };
  38685. __decorate([
  38686. BABYLON.serializeAsColor3(),
  38687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38688. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38689. __decorate([
  38690. BABYLON.serializeAsTexture(),
  38691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38692. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38693. __decorate([
  38694. BABYLON.serialize(),
  38695. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38696. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38697. __decorate([
  38698. BABYLON.serialize(),
  38699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38700. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38701. __decorate([
  38702. BABYLON.serializeAsTexture(),
  38703. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38704. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38705. return PBRMetallicRoughnessMaterial;
  38706. }(BABYLON.PBRBaseSimpleMaterial));
  38707. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38708. })(BABYLON || (BABYLON = {}));
  38709. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38710. var BABYLON;
  38711. (function (BABYLON) {
  38712. /**
  38713. * The PBR material of BJS following the specular glossiness convention.
  38714. *
  38715. * This fits to the PBR convention in the GLTF definition:
  38716. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38717. */
  38718. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38719. __extends(PBRSpecularGlossinessMaterial, _super);
  38720. /**
  38721. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38722. *
  38723. * @param name The material name
  38724. * @param scene The scene the material will be use in.
  38725. */
  38726. function PBRSpecularGlossinessMaterial(name, scene) {
  38727. var _this = _super.call(this, name, scene) || this;
  38728. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38729. return _this;
  38730. }
  38731. /**
  38732. * Return the currrent class name of the material.
  38733. */
  38734. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38735. return "PBRSpecularGlossinessMaterial";
  38736. };
  38737. /**
  38738. * Return the active textures of the material.
  38739. */
  38740. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38741. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38742. if (this.diffuseTexture) {
  38743. activeTextures.push(this.diffuseTexture);
  38744. }
  38745. if (this.specularGlossinessTexture) {
  38746. activeTextures.push(this.specularGlossinessTexture);
  38747. }
  38748. return activeTextures;
  38749. };
  38750. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38751. if (_super.prototype.hasTexture.call(this, texture)) {
  38752. return true;
  38753. }
  38754. if (this.diffuseTexture === texture) {
  38755. return true;
  38756. }
  38757. if (this.specularGlossinessTexture === texture) {
  38758. return true;
  38759. }
  38760. return false;
  38761. };
  38762. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38763. var _this = this;
  38764. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38765. clone.id = name;
  38766. clone.name = name;
  38767. return clone;
  38768. };
  38769. /**
  38770. * Serialize the material to a parsable JSON object.
  38771. */
  38772. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38773. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38774. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38775. return serializationObject;
  38776. };
  38777. /**
  38778. * Parses a JSON object correponding to the serialize function.
  38779. */
  38780. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38781. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38782. };
  38783. __decorate([
  38784. BABYLON.serializeAsColor3("diffuse"),
  38785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38786. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38787. __decorate([
  38788. BABYLON.serializeAsTexture(),
  38789. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38790. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38791. __decorate([
  38792. BABYLON.serializeAsColor3("specular"),
  38793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38794. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38795. __decorate([
  38796. BABYLON.serialize(),
  38797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38798. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38799. __decorate([
  38800. BABYLON.serializeAsTexture(),
  38801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38802. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38803. return PBRSpecularGlossinessMaterial;
  38804. }(BABYLON.PBRBaseSimpleMaterial));
  38805. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38806. })(BABYLON || (BABYLON = {}));
  38807. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38808. var BABYLON;
  38809. (function (BABYLON) {
  38810. BABYLON.CameraInputTypes = {};
  38811. var CameraInputsManager = /** @class */ (function () {
  38812. function CameraInputsManager(camera) {
  38813. this.attached = {};
  38814. this.camera = camera;
  38815. this.checkInputs = function () { };
  38816. }
  38817. CameraInputsManager.prototype.add = function (input) {
  38818. var type = input.getSimpleName();
  38819. if (this.attached[type]) {
  38820. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38821. return;
  38822. }
  38823. this.attached[type] = input;
  38824. input.camera = this.camera;
  38825. //for checkInputs, we are dynamically creating a function
  38826. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38827. if (input.checkInputs) {
  38828. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38829. }
  38830. if (this.attachedElement) {
  38831. input.attachControl(this.attachedElement);
  38832. }
  38833. };
  38834. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38835. for (var cam in this.attached) {
  38836. var input = this.attached[cam];
  38837. if (input === inputToRemove) {
  38838. input.detachControl(this.attachedElement);
  38839. input.camera = null;
  38840. delete this.attached[cam];
  38841. this.rebuildInputCheck();
  38842. }
  38843. }
  38844. };
  38845. CameraInputsManager.prototype.removeByType = function (inputType) {
  38846. for (var cam in this.attached) {
  38847. var input = this.attached[cam];
  38848. if (input.getClassName() === inputType) {
  38849. input.detachControl(this.attachedElement);
  38850. input.camera = null;
  38851. delete this.attached[cam];
  38852. this.rebuildInputCheck();
  38853. }
  38854. }
  38855. };
  38856. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38857. var current = this.checkInputs;
  38858. return function () {
  38859. current();
  38860. fn();
  38861. };
  38862. };
  38863. CameraInputsManager.prototype.attachInput = function (input) {
  38864. if (this.attachedElement) {
  38865. input.attachControl(this.attachedElement, this.noPreventDefault);
  38866. }
  38867. };
  38868. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38869. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38870. if (this.attachedElement) {
  38871. return;
  38872. }
  38873. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38874. this.attachedElement = element;
  38875. this.noPreventDefault = noPreventDefault;
  38876. for (var cam in this.attached) {
  38877. this.attached[cam].attachControl(element, noPreventDefault);
  38878. }
  38879. };
  38880. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38881. if (disconnect === void 0) { disconnect = false; }
  38882. if (this.attachedElement !== element) {
  38883. return;
  38884. }
  38885. for (var cam in this.attached) {
  38886. this.attached[cam].detachControl(element);
  38887. if (disconnect) {
  38888. this.attached[cam].camera = null;
  38889. }
  38890. }
  38891. this.attachedElement = null;
  38892. };
  38893. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38894. this.checkInputs = function () { };
  38895. for (var cam in this.attached) {
  38896. var input = this.attached[cam];
  38897. if (input.checkInputs) {
  38898. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38899. }
  38900. }
  38901. };
  38902. CameraInputsManager.prototype.clear = function () {
  38903. if (this.attachedElement) {
  38904. this.detachElement(this.attachedElement, true);
  38905. }
  38906. this.attached = {};
  38907. this.attachedElement = null;
  38908. this.checkInputs = function () { };
  38909. };
  38910. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38911. var inputs = {};
  38912. for (var cam in this.attached) {
  38913. var input = this.attached[cam];
  38914. var res = BABYLON.SerializationHelper.Serialize(input);
  38915. inputs[input.getClassName()] = res;
  38916. }
  38917. serializedCamera.inputsmgr = inputs;
  38918. };
  38919. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38920. var parsedInputs = parsedCamera.inputsmgr;
  38921. if (parsedInputs) {
  38922. this.clear();
  38923. for (var n in parsedInputs) {
  38924. var construct = BABYLON.CameraInputTypes[n];
  38925. if (construct) {
  38926. var parsedinput = parsedInputs[n];
  38927. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38928. this.add(input);
  38929. }
  38930. }
  38931. }
  38932. else {
  38933. //2016-03-08 this part is for managing backward compatibility
  38934. for (var n in this.attached) {
  38935. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38936. if (construct) {
  38937. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38938. this.remove(this.attached[n]);
  38939. this.add(input);
  38940. }
  38941. }
  38942. }
  38943. };
  38944. return CameraInputsManager;
  38945. }());
  38946. BABYLON.CameraInputsManager = CameraInputsManager;
  38947. })(BABYLON || (BABYLON = {}));
  38948. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38949. var BABYLON;
  38950. (function (BABYLON) {
  38951. var TargetCamera = /** @class */ (function (_super) {
  38952. __extends(TargetCamera, _super);
  38953. function TargetCamera(name, position, scene) {
  38954. var _this = _super.call(this, name, position, scene) || this;
  38955. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38956. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38957. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38958. _this.speed = 2.0;
  38959. _this.noRotationConstraint = false;
  38960. _this.lockedTarget = null;
  38961. _this._currentTarget = BABYLON.Vector3.Zero();
  38962. _this._viewMatrix = BABYLON.Matrix.Zero();
  38963. _this._camMatrix = BABYLON.Matrix.Zero();
  38964. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38965. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38966. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38967. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38968. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38969. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38970. _this._tempMatrix = BABYLON.Matrix.Zero();
  38971. return _this;
  38972. }
  38973. TargetCamera.prototype.getFrontPosition = function (distance) {
  38974. this.getWorldMatrix();
  38975. var direction = this.getTarget().subtract(this.position);
  38976. direction.normalize();
  38977. direction.scaleInPlace(distance);
  38978. return this.globalPosition.add(direction);
  38979. };
  38980. TargetCamera.prototype._getLockedTargetPosition = function () {
  38981. if (!this.lockedTarget) {
  38982. return null;
  38983. }
  38984. if (this.lockedTarget.absolutePosition) {
  38985. this.lockedTarget.computeWorldMatrix();
  38986. }
  38987. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38988. };
  38989. TargetCamera.prototype.storeState = function () {
  38990. this._storedPosition = this.position.clone();
  38991. this._storedRotation = this.rotation.clone();
  38992. if (this.rotationQuaternion) {
  38993. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38994. }
  38995. return _super.prototype.storeState.call(this);
  38996. };
  38997. /**
  38998. * Restored camera state. You must call storeState() first
  38999. */
  39000. TargetCamera.prototype._restoreStateValues = function () {
  39001. if (!_super.prototype._restoreStateValues.call(this)) {
  39002. return false;
  39003. }
  39004. this.position = this._storedPosition.clone();
  39005. this.rotation = this._storedRotation.clone();
  39006. if (this.rotationQuaternion) {
  39007. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  39008. }
  39009. this.cameraDirection.copyFromFloats(0, 0, 0);
  39010. this.cameraRotation.copyFromFloats(0, 0);
  39011. return true;
  39012. };
  39013. // Cache
  39014. TargetCamera.prototype._initCache = function () {
  39015. _super.prototype._initCache.call(this);
  39016. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39017. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39018. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  39019. };
  39020. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  39021. if (!ignoreParentClass) {
  39022. _super.prototype._updateCache.call(this);
  39023. }
  39024. var lockedTargetPosition = this._getLockedTargetPosition();
  39025. if (!lockedTargetPosition) {
  39026. this._cache.lockedTarget = null;
  39027. }
  39028. else {
  39029. if (!this._cache.lockedTarget) {
  39030. this._cache.lockedTarget = lockedTargetPosition.clone();
  39031. }
  39032. else {
  39033. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  39034. }
  39035. }
  39036. this._cache.rotation.copyFrom(this.rotation);
  39037. if (this.rotationQuaternion)
  39038. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39039. };
  39040. // Synchronized
  39041. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  39042. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  39043. return false;
  39044. }
  39045. var lockedTargetPosition = this._getLockedTargetPosition();
  39046. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  39047. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  39048. };
  39049. // Methods
  39050. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  39051. var engine = this.getEngine();
  39052. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  39053. };
  39054. // Target
  39055. TargetCamera.prototype.setTarget = function (target) {
  39056. this.upVector.normalize();
  39057. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  39058. this._camMatrix.invert();
  39059. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  39060. var vDir = target.subtract(this.position);
  39061. if (vDir.x >= 0.0) {
  39062. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  39063. }
  39064. else {
  39065. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  39066. }
  39067. this.rotation.z = 0;
  39068. if (isNaN(this.rotation.x)) {
  39069. this.rotation.x = 0;
  39070. }
  39071. if (isNaN(this.rotation.y)) {
  39072. this.rotation.y = 0;
  39073. }
  39074. if (isNaN(this.rotation.z)) {
  39075. this.rotation.z = 0;
  39076. }
  39077. if (this.rotationQuaternion) {
  39078. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39079. }
  39080. };
  39081. /**
  39082. * Return the current target position of the camera. This value is expressed in local space.
  39083. */
  39084. TargetCamera.prototype.getTarget = function () {
  39085. return this._currentTarget;
  39086. };
  39087. TargetCamera.prototype._decideIfNeedsToMove = function () {
  39088. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39089. };
  39090. TargetCamera.prototype._updatePosition = function () {
  39091. if (this.parent) {
  39092. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  39093. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  39094. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  39095. return;
  39096. }
  39097. this.position.addInPlace(this.cameraDirection);
  39098. };
  39099. TargetCamera.prototype._checkInputs = function () {
  39100. var needToMove = this._decideIfNeedsToMove();
  39101. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  39102. // Move
  39103. if (needToMove) {
  39104. this._updatePosition();
  39105. }
  39106. // Rotate
  39107. if (needToRotate) {
  39108. this.rotation.x += this.cameraRotation.x;
  39109. this.rotation.y += this.cameraRotation.y;
  39110. //rotate, if quaternion is set and rotation was used
  39111. if (this.rotationQuaternion) {
  39112. var len = this.rotation.lengthSquared();
  39113. if (len) {
  39114. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  39115. }
  39116. }
  39117. if (!this.noRotationConstraint) {
  39118. var limit = (Math.PI / 2) * 0.95;
  39119. if (this.rotation.x > limit)
  39120. this.rotation.x = limit;
  39121. if (this.rotation.x < -limit)
  39122. this.rotation.x = -limit;
  39123. }
  39124. }
  39125. // Inertia
  39126. if (needToMove) {
  39127. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  39128. this.cameraDirection.x = 0;
  39129. }
  39130. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  39131. this.cameraDirection.y = 0;
  39132. }
  39133. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  39134. this.cameraDirection.z = 0;
  39135. }
  39136. this.cameraDirection.scaleInPlace(this.inertia);
  39137. }
  39138. if (needToRotate) {
  39139. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  39140. this.cameraRotation.x = 0;
  39141. }
  39142. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39143. this.cameraRotation.y = 0;
  39144. }
  39145. this.cameraRotation.scaleInPlace(this.inertia);
  39146. }
  39147. _super.prototype._checkInputs.call(this);
  39148. };
  39149. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39150. if (this.rotationQuaternion) {
  39151. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39152. }
  39153. else {
  39154. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39155. }
  39156. //update the up vector!
  39157. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39158. };
  39159. TargetCamera.prototype._getViewMatrix = function () {
  39160. if (this.lockedTarget) {
  39161. this.setTarget(this._getLockedTargetPosition());
  39162. }
  39163. // Compute
  39164. this._updateCameraRotationMatrix();
  39165. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39166. // Computing target and final matrix
  39167. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39168. if (this.getScene().useRightHandedSystem) {
  39169. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39170. }
  39171. else {
  39172. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39173. }
  39174. return this._viewMatrix;
  39175. };
  39176. /**
  39177. * @override
  39178. * Override Camera.createRigCamera
  39179. */
  39180. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39181. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39182. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39183. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39184. if (!this.rotationQuaternion) {
  39185. this.rotationQuaternion = new BABYLON.Quaternion();
  39186. }
  39187. rigCamera._cameraRigParams = {};
  39188. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39189. }
  39190. return rigCamera;
  39191. }
  39192. return null;
  39193. };
  39194. /**
  39195. * @override
  39196. * Override Camera._updateRigCameras
  39197. */
  39198. TargetCamera.prototype._updateRigCameras = function () {
  39199. var camLeft = this._rigCameras[0];
  39200. var camRight = this._rigCameras[1];
  39201. switch (this.cameraRigMode) {
  39202. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39203. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39204. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39205. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39206. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39207. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39208. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39209. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39210. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39211. camLeft.setTarget(this.getTarget());
  39212. camRight.setTarget(this.getTarget());
  39213. break;
  39214. case BABYLON.Camera.RIG_MODE_VR:
  39215. if (camLeft.rotationQuaternion) {
  39216. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39217. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39218. }
  39219. else {
  39220. camLeft.rotation.copyFrom(this.rotation);
  39221. camRight.rotation.copyFrom(this.rotation);
  39222. }
  39223. camLeft.position.copyFrom(this.position);
  39224. camRight.position.copyFrom(this.position);
  39225. break;
  39226. }
  39227. _super.prototype._updateRigCameras.call(this);
  39228. };
  39229. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39230. if (!this._rigCamTransformMatrix) {
  39231. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39232. }
  39233. var target = this.getTarget();
  39234. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39235. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39236. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39237. };
  39238. TargetCamera.prototype.getClassName = function () {
  39239. return "TargetCamera";
  39240. };
  39241. __decorate([
  39242. BABYLON.serializeAsVector3()
  39243. ], TargetCamera.prototype, "rotation", void 0);
  39244. __decorate([
  39245. BABYLON.serialize()
  39246. ], TargetCamera.prototype, "speed", void 0);
  39247. __decorate([
  39248. BABYLON.serializeAsMeshReference("lockedTargetId")
  39249. ], TargetCamera.prototype, "lockedTarget", void 0);
  39250. return TargetCamera;
  39251. }(BABYLON.Camera));
  39252. BABYLON.TargetCamera = TargetCamera;
  39253. })(BABYLON || (BABYLON = {}));
  39254. //# sourceMappingURL=babylon.targetCamera.js.map
  39255. var BABYLON;
  39256. (function (BABYLON) {
  39257. var FreeCameraMouseInput = /** @class */ (function () {
  39258. function FreeCameraMouseInput(touchEnabled) {
  39259. if (touchEnabled === void 0) { touchEnabled = true; }
  39260. this.touchEnabled = touchEnabled;
  39261. this.buttons = [0, 1, 2];
  39262. this.angularSensibility = 2000.0;
  39263. this.previousPosition = null;
  39264. }
  39265. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  39266. var _this = this;
  39267. var engine = this.camera.getEngine();
  39268. if (!this._pointerInput) {
  39269. this._pointerInput = function (p, s) {
  39270. var evt = p.event;
  39271. if (engine.isInVRExclusivePointerMode) {
  39272. return;
  39273. }
  39274. if (!_this.touchEnabled && evt.pointerType === "touch") {
  39275. return;
  39276. }
  39277. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39278. return;
  39279. }
  39280. var srcElement = (evt.srcElement || evt.target);
  39281. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39282. try {
  39283. srcElement.setPointerCapture(evt.pointerId);
  39284. }
  39285. catch (e) {
  39286. //Nothing to do with the error. Execution will continue.
  39287. }
  39288. _this.previousPosition = {
  39289. x: evt.clientX,
  39290. y: evt.clientY
  39291. };
  39292. if (!noPreventDefault) {
  39293. evt.preventDefault();
  39294. element.focus();
  39295. }
  39296. }
  39297. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39298. try {
  39299. srcElement.releasePointerCapture(evt.pointerId);
  39300. }
  39301. catch (e) {
  39302. //Nothing to do with the error.
  39303. }
  39304. _this.previousPosition = null;
  39305. if (!noPreventDefault) {
  39306. evt.preventDefault();
  39307. }
  39308. }
  39309. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39310. if (!_this.previousPosition || engine.isPointerLock) {
  39311. return;
  39312. }
  39313. var offsetX = evt.clientX - _this.previousPosition.x;
  39314. var offsetY = evt.clientY - _this.previousPosition.y;
  39315. if (_this.camera.getScene().useRightHandedSystem) {
  39316. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39317. }
  39318. else {
  39319. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39320. }
  39321. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39322. _this.previousPosition = {
  39323. x: evt.clientX,
  39324. y: evt.clientY
  39325. };
  39326. if (!noPreventDefault) {
  39327. evt.preventDefault();
  39328. }
  39329. }
  39330. };
  39331. }
  39332. this._onMouseMove = function (evt) {
  39333. if (!engine.isPointerLock) {
  39334. return;
  39335. }
  39336. if (engine.isInVRExclusivePointerMode) {
  39337. return;
  39338. }
  39339. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39340. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39341. if (_this.camera.getScene().useRightHandedSystem) {
  39342. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  39343. }
  39344. else {
  39345. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  39346. }
  39347. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  39348. _this.previousPosition = null;
  39349. if (!noPreventDefault) {
  39350. evt.preventDefault();
  39351. }
  39352. };
  39353. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  39354. element.addEventListener("mousemove", this._onMouseMove, false);
  39355. };
  39356. FreeCameraMouseInput.prototype.detachControl = function (element) {
  39357. if (this._observer && element) {
  39358. this.camera.getScene().onPointerObservable.remove(this._observer);
  39359. if (this._onMouseMove) {
  39360. element.removeEventListener("mousemove", this._onMouseMove);
  39361. }
  39362. this._observer = null;
  39363. this._onMouseMove = null;
  39364. this.previousPosition = null;
  39365. }
  39366. };
  39367. FreeCameraMouseInput.prototype.getClassName = function () {
  39368. return "FreeCameraMouseInput";
  39369. };
  39370. FreeCameraMouseInput.prototype.getSimpleName = function () {
  39371. return "mouse";
  39372. };
  39373. __decorate([
  39374. BABYLON.serialize()
  39375. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  39376. __decorate([
  39377. BABYLON.serialize()
  39378. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  39379. return FreeCameraMouseInput;
  39380. }());
  39381. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  39382. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  39383. })(BABYLON || (BABYLON = {}));
  39384. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  39385. var BABYLON;
  39386. (function (BABYLON) {
  39387. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  39388. function FreeCameraKeyboardMoveInput() {
  39389. this._keys = new Array();
  39390. this.keysUp = [38];
  39391. this.keysDown = [40];
  39392. this.keysLeft = [37];
  39393. this.keysRight = [39];
  39394. }
  39395. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39396. var _this = this;
  39397. if (this._onCanvasBlurObserver) {
  39398. return;
  39399. }
  39400. this._scene = this.camera.getScene();
  39401. this._engine = this._scene.getEngine();
  39402. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39403. _this._keys = [];
  39404. });
  39405. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39406. var evt = info.event;
  39407. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39408. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39409. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39410. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39411. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39412. var index = _this._keys.indexOf(evt.keyCode);
  39413. if (index === -1) {
  39414. _this._keys.push(evt.keyCode);
  39415. }
  39416. if (!noPreventDefault) {
  39417. evt.preventDefault();
  39418. }
  39419. }
  39420. }
  39421. else {
  39422. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39423. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39424. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39425. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  39426. var index = _this._keys.indexOf(evt.keyCode);
  39427. if (index >= 0) {
  39428. _this._keys.splice(index, 1);
  39429. }
  39430. if (!noPreventDefault) {
  39431. evt.preventDefault();
  39432. }
  39433. }
  39434. }
  39435. });
  39436. };
  39437. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39438. if (this._scene) {
  39439. if (this._onKeyboardObserver) {
  39440. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39441. }
  39442. if (this._onCanvasBlurObserver) {
  39443. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39444. }
  39445. this._onKeyboardObserver = null;
  39446. this._onCanvasBlurObserver = null;
  39447. }
  39448. this._keys = [];
  39449. };
  39450. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39451. if (this._onKeyboardObserver) {
  39452. var camera = this.camera;
  39453. // Keyboard
  39454. for (var index = 0; index < this._keys.length; index++) {
  39455. var keyCode = this._keys[index];
  39456. var speed = camera._computeLocalCameraSpeed();
  39457. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39458. camera._localDirection.copyFromFloats(-speed, 0, 0);
  39459. }
  39460. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39461. camera._localDirection.copyFromFloats(0, 0, speed);
  39462. }
  39463. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39464. camera._localDirection.copyFromFloats(speed, 0, 0);
  39465. }
  39466. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39467. camera._localDirection.copyFromFloats(0, 0, -speed);
  39468. }
  39469. if (camera.getScene().useRightHandedSystem) {
  39470. camera._localDirection.z *= -1;
  39471. }
  39472. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  39473. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  39474. camera.cameraDirection.addInPlace(camera._transformedDirection);
  39475. }
  39476. }
  39477. };
  39478. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  39479. return "FreeCameraKeyboardMoveInput";
  39480. };
  39481. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  39482. this._keys = [];
  39483. };
  39484. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39485. return "keyboard";
  39486. };
  39487. __decorate([
  39488. BABYLON.serialize()
  39489. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39490. __decorate([
  39491. BABYLON.serialize()
  39492. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39493. __decorate([
  39494. BABYLON.serialize()
  39495. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39496. __decorate([
  39497. BABYLON.serialize()
  39498. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39499. return FreeCameraKeyboardMoveInput;
  39500. }());
  39501. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  39502. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  39503. })(BABYLON || (BABYLON = {}));
  39504. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  39505. var BABYLON;
  39506. (function (BABYLON) {
  39507. var FreeCameraInputsManager = /** @class */ (function (_super) {
  39508. __extends(FreeCameraInputsManager, _super);
  39509. function FreeCameraInputsManager(camera) {
  39510. return _super.call(this, camera) || this;
  39511. }
  39512. FreeCameraInputsManager.prototype.addKeyboard = function () {
  39513. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  39514. return this;
  39515. };
  39516. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  39517. if (touchEnabled === void 0) { touchEnabled = true; }
  39518. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  39519. return this;
  39520. };
  39521. FreeCameraInputsManager.prototype.addGamepad = function () {
  39522. this.add(new BABYLON.FreeCameraGamepadInput());
  39523. return this;
  39524. };
  39525. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  39526. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  39527. return this;
  39528. };
  39529. FreeCameraInputsManager.prototype.addTouch = function () {
  39530. this.add(new BABYLON.FreeCameraTouchInput());
  39531. return this;
  39532. };
  39533. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  39534. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  39535. return this;
  39536. };
  39537. return FreeCameraInputsManager;
  39538. }(BABYLON.CameraInputsManager));
  39539. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  39540. })(BABYLON || (BABYLON = {}));
  39541. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  39542. var BABYLON;
  39543. (function (BABYLON) {
  39544. var FreeCamera = /** @class */ (function (_super) {
  39545. __extends(FreeCamera, _super);
  39546. function FreeCamera(name, position, scene) {
  39547. var _this = _super.call(this, name, position, scene) || this;
  39548. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39549. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39550. _this.checkCollisions = false;
  39551. _this.applyGravity = false;
  39552. _this._needMoveForGravity = false;
  39553. _this._oldPosition = BABYLON.Vector3.Zero();
  39554. _this._diffPosition = BABYLON.Vector3.Zero();
  39555. _this._newPosition = BABYLON.Vector3.Zero();
  39556. // Collisions
  39557. _this._collisionMask = -1;
  39558. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39559. if (collidedMesh === void 0) { collidedMesh = null; }
  39560. //TODO move this to the collision coordinator!
  39561. if (_this.getScene().workerCollisions)
  39562. newPosition.multiplyInPlace(_this._collider._radius);
  39563. var updatePosition = function (newPos) {
  39564. _this._newPosition.copyFrom(newPos);
  39565. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39566. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39567. _this.position.addInPlace(_this._diffPosition);
  39568. if (_this.onCollide && collidedMesh) {
  39569. _this.onCollide(collidedMesh);
  39570. }
  39571. }
  39572. };
  39573. updatePosition(newPosition);
  39574. };
  39575. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39576. _this.inputs.addKeyboard().addMouse();
  39577. return _this;
  39578. }
  39579. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39580. //-- begin properties for backward compatibility for inputs
  39581. get: function () {
  39582. var mouse = this.inputs.attached["mouse"];
  39583. if (mouse)
  39584. return mouse.angularSensibility;
  39585. return 0;
  39586. },
  39587. set: function (value) {
  39588. var mouse = this.inputs.attached["mouse"];
  39589. if (mouse)
  39590. mouse.angularSensibility = value;
  39591. },
  39592. enumerable: true,
  39593. configurable: true
  39594. });
  39595. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39596. get: function () {
  39597. var keyboard = this.inputs.attached["keyboard"];
  39598. if (keyboard)
  39599. return keyboard.keysUp;
  39600. return [];
  39601. },
  39602. set: function (value) {
  39603. var keyboard = this.inputs.attached["keyboard"];
  39604. if (keyboard)
  39605. keyboard.keysUp = value;
  39606. },
  39607. enumerable: true,
  39608. configurable: true
  39609. });
  39610. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39611. get: function () {
  39612. var keyboard = this.inputs.attached["keyboard"];
  39613. if (keyboard)
  39614. return keyboard.keysDown;
  39615. return [];
  39616. },
  39617. set: function (value) {
  39618. var keyboard = this.inputs.attached["keyboard"];
  39619. if (keyboard)
  39620. keyboard.keysDown = value;
  39621. },
  39622. enumerable: true,
  39623. configurable: true
  39624. });
  39625. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39626. get: function () {
  39627. var keyboard = this.inputs.attached["keyboard"];
  39628. if (keyboard)
  39629. return keyboard.keysLeft;
  39630. return [];
  39631. },
  39632. set: function (value) {
  39633. var keyboard = this.inputs.attached["keyboard"];
  39634. if (keyboard)
  39635. keyboard.keysLeft = value;
  39636. },
  39637. enumerable: true,
  39638. configurable: true
  39639. });
  39640. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39641. get: function () {
  39642. var keyboard = this.inputs.attached["keyboard"];
  39643. if (keyboard)
  39644. return keyboard.keysRight;
  39645. return [];
  39646. },
  39647. set: function (value) {
  39648. var keyboard = this.inputs.attached["keyboard"];
  39649. if (keyboard)
  39650. keyboard.keysRight = value;
  39651. },
  39652. enumerable: true,
  39653. configurable: true
  39654. });
  39655. // Controls
  39656. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39657. this.inputs.attachElement(element, noPreventDefault);
  39658. };
  39659. FreeCamera.prototype.detachControl = function (element) {
  39660. this.inputs.detachElement(element);
  39661. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39662. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39663. };
  39664. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39665. get: function () {
  39666. return this._collisionMask;
  39667. },
  39668. set: function (mask) {
  39669. this._collisionMask = !isNaN(mask) ? mask : -1;
  39670. },
  39671. enumerable: true,
  39672. configurable: true
  39673. });
  39674. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39675. var globalPosition;
  39676. if (this.parent) {
  39677. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39678. }
  39679. else {
  39680. globalPosition = this.position;
  39681. }
  39682. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39683. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39684. if (!this._collider) {
  39685. this._collider = new BABYLON.Collider();
  39686. }
  39687. this._collider._radius = this.ellipsoid;
  39688. this._collider.collisionMask = this._collisionMask;
  39689. //no need for clone, as long as gravity is not on.
  39690. var actualDisplacement = displacement;
  39691. //add gravity to the direction to prevent the dual-collision checking
  39692. if (this.applyGravity) {
  39693. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39694. actualDisplacement = displacement.add(this.getScene().gravity);
  39695. }
  39696. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39697. };
  39698. FreeCamera.prototype._checkInputs = function () {
  39699. if (!this._localDirection) {
  39700. this._localDirection = BABYLON.Vector3.Zero();
  39701. this._transformedDirection = BABYLON.Vector3.Zero();
  39702. }
  39703. this.inputs.checkInputs();
  39704. _super.prototype._checkInputs.call(this);
  39705. };
  39706. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39707. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39708. };
  39709. FreeCamera.prototype._updatePosition = function () {
  39710. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39711. this._collideWithWorld(this.cameraDirection);
  39712. }
  39713. else {
  39714. _super.prototype._updatePosition.call(this);
  39715. }
  39716. };
  39717. FreeCamera.prototype.dispose = function () {
  39718. this.inputs.clear();
  39719. _super.prototype.dispose.call(this);
  39720. };
  39721. FreeCamera.prototype.getClassName = function () {
  39722. return "FreeCamera";
  39723. };
  39724. __decorate([
  39725. BABYLON.serializeAsVector3()
  39726. ], FreeCamera.prototype, "ellipsoid", void 0);
  39727. __decorate([
  39728. BABYLON.serializeAsVector3()
  39729. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39730. __decorate([
  39731. BABYLON.serialize()
  39732. ], FreeCamera.prototype, "checkCollisions", void 0);
  39733. __decorate([
  39734. BABYLON.serialize()
  39735. ], FreeCamera.prototype, "applyGravity", void 0);
  39736. return FreeCamera;
  39737. }(BABYLON.TargetCamera));
  39738. BABYLON.FreeCamera = FreeCamera;
  39739. })(BABYLON || (BABYLON = {}));
  39740. //# sourceMappingURL=babylon.freeCamera.js.map
  39741. var BABYLON;
  39742. (function (BABYLON) {
  39743. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39744. function ArcRotateCameraKeyboardMoveInput() {
  39745. this._keys = new Array();
  39746. this.keysUp = [38];
  39747. this.keysDown = [40];
  39748. this.keysLeft = [37];
  39749. this.keysRight = [39];
  39750. this.keysReset = [220];
  39751. this.panningSensibility = 50.0;
  39752. this.zoomingSensibility = 25.0;
  39753. this.useAltToZoom = true;
  39754. }
  39755. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39756. var _this = this;
  39757. if (this._onCanvasBlurObserver) {
  39758. return;
  39759. }
  39760. this._scene = this.camera.getScene();
  39761. this._engine = this._scene.getEngine();
  39762. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39763. _this._keys = [];
  39764. });
  39765. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39766. var evt = info.event;
  39767. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39768. _this._ctrlPressed = evt.ctrlKey;
  39769. _this._altPressed = evt.altKey;
  39770. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39771. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39772. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39773. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39774. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39775. var index = _this._keys.indexOf(evt.keyCode);
  39776. if (index === -1) {
  39777. _this._keys.push(evt.keyCode);
  39778. }
  39779. if (evt.preventDefault) {
  39780. if (!noPreventDefault) {
  39781. evt.preventDefault();
  39782. }
  39783. }
  39784. }
  39785. }
  39786. else {
  39787. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39788. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39789. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39790. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39791. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39792. var index = _this._keys.indexOf(evt.keyCode);
  39793. if (index >= 0) {
  39794. _this._keys.splice(index, 1);
  39795. }
  39796. if (evt.preventDefault) {
  39797. if (!noPreventDefault) {
  39798. evt.preventDefault();
  39799. }
  39800. }
  39801. }
  39802. }
  39803. });
  39804. };
  39805. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39806. if (this._scene) {
  39807. if (this._onKeyboardObserver) {
  39808. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39809. }
  39810. if (this._onCanvasBlurObserver) {
  39811. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39812. }
  39813. this._onKeyboardObserver = null;
  39814. this._onCanvasBlurObserver = null;
  39815. }
  39816. this._keys = [];
  39817. };
  39818. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39819. if (this._onKeyboardObserver) {
  39820. var camera = this.camera;
  39821. for (var index = 0; index < this._keys.length; index++) {
  39822. var keyCode = this._keys[index];
  39823. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39824. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39825. camera.inertialPanningX -= 1 / this.panningSensibility;
  39826. }
  39827. else {
  39828. camera.inertialAlphaOffset -= 0.01;
  39829. }
  39830. }
  39831. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39832. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39833. camera.inertialPanningY += 1 / this.panningSensibility;
  39834. }
  39835. else if (this._altPressed && this.useAltToZoom) {
  39836. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39837. }
  39838. else {
  39839. camera.inertialBetaOffset -= 0.01;
  39840. }
  39841. }
  39842. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39843. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39844. camera.inertialPanningX += 1 / this.panningSensibility;
  39845. }
  39846. else {
  39847. camera.inertialAlphaOffset += 0.01;
  39848. }
  39849. }
  39850. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39851. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39852. camera.inertialPanningY -= 1 / this.panningSensibility;
  39853. }
  39854. else if (this._altPressed && this.useAltToZoom) {
  39855. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39856. }
  39857. else {
  39858. camera.inertialBetaOffset += 0.01;
  39859. }
  39860. }
  39861. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39862. camera.restoreState();
  39863. }
  39864. }
  39865. }
  39866. };
  39867. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39868. return "ArcRotateCameraKeyboardMoveInput";
  39869. };
  39870. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39871. return "keyboard";
  39872. };
  39873. __decorate([
  39874. BABYLON.serialize()
  39875. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39876. __decorate([
  39877. BABYLON.serialize()
  39878. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39879. __decorate([
  39880. BABYLON.serialize()
  39881. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39882. __decorate([
  39883. BABYLON.serialize()
  39884. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39885. __decorate([
  39886. BABYLON.serialize()
  39887. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39888. __decorate([
  39889. BABYLON.serialize()
  39890. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39891. __decorate([
  39892. BABYLON.serialize()
  39893. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39894. __decorate([
  39895. BABYLON.serialize()
  39896. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39897. return ArcRotateCameraKeyboardMoveInput;
  39898. }());
  39899. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39900. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39901. })(BABYLON || (BABYLON = {}));
  39902. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39903. var BABYLON;
  39904. (function (BABYLON) {
  39905. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39906. function ArcRotateCameraMouseWheelInput() {
  39907. this.wheelPrecision = 3.0;
  39908. /**
  39909. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39910. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39911. */
  39912. this.wheelDeltaPercentage = 0;
  39913. }
  39914. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39915. var _this = this;
  39916. this._wheel = function (p, s) {
  39917. //sanity check - this should be a PointerWheel event.
  39918. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39919. return;
  39920. var event = p.event;
  39921. var delta = 0;
  39922. if (event.wheelDelta) {
  39923. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39924. }
  39925. else if (event.detail) {
  39926. delta = -event.detail / _this.wheelPrecision;
  39927. }
  39928. if (delta)
  39929. _this.camera.inertialRadiusOffset += delta;
  39930. if (event.preventDefault) {
  39931. if (!noPreventDefault) {
  39932. event.preventDefault();
  39933. }
  39934. }
  39935. };
  39936. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39937. };
  39938. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39939. if (this._observer && element) {
  39940. this.camera.getScene().onPointerObservable.remove(this._observer);
  39941. this._observer = null;
  39942. this._wheel = null;
  39943. }
  39944. };
  39945. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39946. return "ArcRotateCameraMouseWheelInput";
  39947. };
  39948. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39949. return "mousewheel";
  39950. };
  39951. __decorate([
  39952. BABYLON.serialize()
  39953. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39954. __decorate([
  39955. BABYLON.serialize()
  39956. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39957. return ArcRotateCameraMouseWheelInput;
  39958. }());
  39959. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39960. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39961. })(BABYLON || (BABYLON = {}));
  39962. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39963. var BABYLON;
  39964. (function (BABYLON) {
  39965. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39966. function ArcRotateCameraPointersInput() {
  39967. this.buttons = [0, 1, 2];
  39968. this.angularSensibilityX = 1000.0;
  39969. this.angularSensibilityY = 1000.0;
  39970. this.pinchPrecision = 12.0;
  39971. /**
  39972. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39973. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39974. */
  39975. this.pinchDeltaPercentage = 0;
  39976. this.panningSensibility = 1000.0;
  39977. this.multiTouchPanning = true;
  39978. this.multiTouchPanAndZoom = true;
  39979. this._isPanClick = false;
  39980. this.pinchInwards = true;
  39981. }
  39982. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39983. var _this = this;
  39984. var engine = this.camera.getEngine();
  39985. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39986. var pointA = null;
  39987. var pointB = null;
  39988. var previousPinchSquaredDistance = 0;
  39989. var initialDistance = 0;
  39990. var twoFingerActivityCount = 0;
  39991. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39992. this._pointerInput = function (p, s) {
  39993. var evt = p.event;
  39994. var isTouch = p.event.pointerType === "touch";
  39995. if (engine.isInVRExclusivePointerMode) {
  39996. return;
  39997. }
  39998. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39999. return;
  40000. }
  40001. var srcElement = (evt.srcElement || evt.target);
  40002. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  40003. try {
  40004. srcElement.setPointerCapture(evt.pointerId);
  40005. }
  40006. catch (e) {
  40007. //Nothing to do with the error. Execution will continue.
  40008. }
  40009. // Manage panning with pan button click
  40010. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  40011. // manage pointers
  40012. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  40013. if (pointA === null) {
  40014. pointA = cacheSoloPointer;
  40015. }
  40016. else if (pointB === null) {
  40017. pointB = cacheSoloPointer;
  40018. }
  40019. if (!noPreventDefault) {
  40020. evt.preventDefault();
  40021. element.focus();
  40022. }
  40023. }
  40024. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  40025. _this.camera.restoreState();
  40026. }
  40027. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  40028. try {
  40029. srcElement.releasePointerCapture(evt.pointerId);
  40030. }
  40031. catch (e) {
  40032. //Nothing to do with the error.
  40033. }
  40034. cacheSoloPointer = null;
  40035. previousPinchSquaredDistance = 0;
  40036. previousMultiTouchPanPosition.isPaning = false;
  40037. previousMultiTouchPanPosition.isPinching = false;
  40038. twoFingerActivityCount = 0;
  40039. initialDistance = 0;
  40040. if (!isTouch) {
  40041. pointB = null; // Mouse and pen are mono pointer
  40042. }
  40043. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  40044. //but emptying completly pointers collection is required to fix a bug on iPhone :
  40045. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  40046. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  40047. if (engine.badOS) {
  40048. pointA = pointB = null;
  40049. }
  40050. else {
  40051. //only remove the impacted pointer in case of multitouch allowing on most
  40052. //platforms switching from rotate to zoom and pan seamlessly.
  40053. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  40054. pointA = pointB;
  40055. pointB = null;
  40056. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40057. }
  40058. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  40059. pointB = null;
  40060. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  40061. }
  40062. else {
  40063. pointA = pointB = null;
  40064. }
  40065. }
  40066. if (!noPreventDefault) {
  40067. evt.preventDefault();
  40068. }
  40069. }
  40070. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  40071. if (!noPreventDefault) {
  40072. evt.preventDefault();
  40073. }
  40074. // One button down
  40075. if (pointA && pointB === null && cacheSoloPointer) {
  40076. if (_this.panningSensibility !== 0 &&
  40077. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  40078. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  40079. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  40080. }
  40081. else {
  40082. var offsetX = evt.clientX - cacheSoloPointer.x;
  40083. var offsetY = evt.clientY - cacheSoloPointer.y;
  40084. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40085. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40086. }
  40087. cacheSoloPointer.x = evt.clientX;
  40088. cacheSoloPointer.y = evt.clientY;
  40089. }
  40090. else if (pointA && pointB) {
  40091. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  40092. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  40093. ed.x = evt.clientX;
  40094. ed.y = evt.clientY;
  40095. var direction = _this.pinchInwards ? 1 : -1;
  40096. var distX = pointA.x - pointB.x;
  40097. var distY = pointA.y - pointB.y;
  40098. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  40099. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  40100. if (previousPinchSquaredDistance === 0) {
  40101. initialDistance = pinchDistance;
  40102. previousPinchSquaredDistance = pinchSquaredDistance;
  40103. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  40104. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  40105. return;
  40106. }
  40107. if (_this.multiTouchPanAndZoom) {
  40108. if (_this.pinchDeltaPercentage) {
  40109. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40110. }
  40111. else {
  40112. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40113. (_this.pinchPrecision *
  40114. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40115. direction);
  40116. }
  40117. if (_this.panningSensibility !== 0) {
  40118. var pointersCenterX = (pointA.x + pointB.x) / 2;
  40119. var pointersCenterY = (pointA.y + pointB.y) / 2;
  40120. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  40121. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  40122. previousMultiTouchPanPosition.x = pointersCenterX;
  40123. previousMultiTouchPanPosition.y = pointersCenterY;
  40124. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  40125. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  40126. }
  40127. }
  40128. else {
  40129. twoFingerActivityCount++;
  40130. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  40131. if (_this.pinchDeltaPercentage) {
  40132. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  40133. }
  40134. else {
  40135. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  40136. (_this.pinchPrecision *
  40137. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  40138. direction);
  40139. }
  40140. previousMultiTouchPanPosition.isPaning = false;
  40141. previousMultiTouchPanPosition.isPinching = true;
  40142. }
  40143. else {
  40144. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  40145. if (!previousMultiTouchPanPosition.isPaning) {
  40146. previousMultiTouchPanPosition.isPaning = true;
  40147. previousMultiTouchPanPosition.isPinching = false;
  40148. previousMultiTouchPanPosition.x = ed.x;
  40149. previousMultiTouchPanPosition.y = ed.y;
  40150. return;
  40151. }
  40152. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  40153. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  40154. }
  40155. }
  40156. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  40157. previousMultiTouchPanPosition.x = ed.x;
  40158. previousMultiTouchPanPosition.y = ed.y;
  40159. }
  40160. }
  40161. previousPinchSquaredDistance = pinchSquaredDistance;
  40162. }
  40163. }
  40164. };
  40165. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  40166. this._onContextMenu = function (evt) {
  40167. evt.preventDefault();
  40168. };
  40169. if (!this.camera._useCtrlForPanning) {
  40170. element.addEventListener("contextmenu", this._onContextMenu, false);
  40171. }
  40172. this._onLostFocus = function () {
  40173. //this._keys = [];
  40174. pointA = pointB = null;
  40175. previousPinchSquaredDistance = 0;
  40176. previousMultiTouchPanPosition.isPaning = false;
  40177. previousMultiTouchPanPosition.isPinching = false;
  40178. twoFingerActivityCount = 0;
  40179. cacheSoloPointer = null;
  40180. initialDistance = 0;
  40181. };
  40182. this._onMouseMove = function (evt) {
  40183. if (!engine.isPointerLock) {
  40184. return;
  40185. }
  40186. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  40187. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  40188. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  40189. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  40190. if (!noPreventDefault) {
  40191. evt.preventDefault();
  40192. }
  40193. };
  40194. this._onGestureStart = function (e) {
  40195. if (window.MSGesture === undefined) {
  40196. return;
  40197. }
  40198. if (!_this._MSGestureHandler) {
  40199. _this._MSGestureHandler = new MSGesture();
  40200. _this._MSGestureHandler.target = element;
  40201. }
  40202. _this._MSGestureHandler.addPointer(e.pointerId);
  40203. };
  40204. this._onGesture = function (e) {
  40205. _this.camera.radius *= e.scale;
  40206. if (e.preventDefault) {
  40207. if (!noPreventDefault) {
  40208. e.stopPropagation();
  40209. e.preventDefault();
  40210. }
  40211. }
  40212. };
  40213. element.addEventListener("mousemove", this._onMouseMove, false);
  40214. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  40215. element.addEventListener("MSGestureChange", this._onGesture, false);
  40216. BABYLON.Tools.RegisterTopRootEvents([
  40217. { name: "blur", handler: this._onLostFocus }
  40218. ]);
  40219. };
  40220. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  40221. if (this._onLostFocus) {
  40222. BABYLON.Tools.UnregisterTopRootEvents([
  40223. { name: "blur", handler: this._onLostFocus }
  40224. ]);
  40225. }
  40226. if (element && this._observer) {
  40227. this.camera.getScene().onPointerObservable.remove(this._observer);
  40228. this._observer = null;
  40229. if (this._onContextMenu) {
  40230. element.removeEventListener("contextmenu", this._onContextMenu);
  40231. }
  40232. if (this._onMouseMove) {
  40233. element.removeEventListener("mousemove", this._onMouseMove);
  40234. }
  40235. if (this._onGestureStart) {
  40236. element.removeEventListener("MSPointerDown", this._onGestureStart);
  40237. }
  40238. if (this._onGesture) {
  40239. element.removeEventListener("MSGestureChange", this._onGesture);
  40240. }
  40241. this._isPanClick = false;
  40242. this.pinchInwards = true;
  40243. this._onMouseMove = null;
  40244. this._onGestureStart = null;
  40245. this._onGesture = null;
  40246. this._MSGestureHandler = null;
  40247. this._onLostFocus = null;
  40248. this._onContextMenu = null;
  40249. }
  40250. };
  40251. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  40252. return "ArcRotateCameraPointersInput";
  40253. };
  40254. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  40255. return "pointers";
  40256. };
  40257. __decorate([
  40258. BABYLON.serialize()
  40259. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  40260. __decorate([
  40261. BABYLON.serialize()
  40262. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  40263. __decorate([
  40264. BABYLON.serialize()
  40265. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  40266. __decorate([
  40267. BABYLON.serialize()
  40268. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  40269. __decorate([
  40270. BABYLON.serialize()
  40271. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  40272. __decorate([
  40273. BABYLON.serialize()
  40274. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  40275. __decorate([
  40276. BABYLON.serialize()
  40277. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  40278. __decorate([
  40279. BABYLON.serialize()
  40280. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  40281. return ArcRotateCameraPointersInput;
  40282. }());
  40283. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  40284. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  40285. })(BABYLON || (BABYLON = {}));
  40286. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  40287. var BABYLON;
  40288. (function (BABYLON) {
  40289. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40290. __extends(ArcRotateCameraInputsManager, _super);
  40291. function ArcRotateCameraInputsManager(camera) {
  40292. return _super.call(this, camera) || this;
  40293. }
  40294. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40295. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40296. return this;
  40297. };
  40298. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40299. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40300. return this;
  40301. };
  40302. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40303. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40304. return this;
  40305. };
  40306. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40307. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40308. return this;
  40309. };
  40310. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40311. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40312. return this;
  40313. };
  40314. return ArcRotateCameraInputsManager;
  40315. }(BABYLON.CameraInputsManager));
  40316. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40317. })(BABYLON || (BABYLON = {}));
  40318. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40319. var BABYLON;
  40320. (function (BABYLON) {
  40321. var ArcRotateCamera = /** @class */ (function (_super) {
  40322. __extends(ArcRotateCamera, _super);
  40323. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  40324. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  40325. _this.inertialAlphaOffset = 0;
  40326. _this.inertialBetaOffset = 0;
  40327. _this.inertialRadiusOffset = 0;
  40328. _this.lowerAlphaLimit = null;
  40329. _this.upperAlphaLimit = null;
  40330. _this.lowerBetaLimit = 0.01;
  40331. _this.upperBetaLimit = Math.PI;
  40332. _this.lowerRadiusLimit = null;
  40333. _this.upperRadiusLimit = null;
  40334. _this.inertialPanningX = 0;
  40335. _this.inertialPanningY = 0;
  40336. _this.pinchToPanMaxDistance = 20;
  40337. _this.panningDistanceLimit = null;
  40338. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  40339. _this.panningInertia = 0.9;
  40340. //-- end properties for backward compatibility for inputs
  40341. _this.zoomOnFactor = 1;
  40342. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  40343. _this.allowUpsideDown = true;
  40344. _this._viewMatrix = new BABYLON.Matrix();
  40345. // Panning
  40346. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  40347. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  40348. _this.checkCollisions = false;
  40349. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40350. _this._previousPosition = BABYLON.Vector3.Zero();
  40351. _this._collisionVelocity = BABYLON.Vector3.Zero();
  40352. _this._newPosition = BABYLON.Vector3.Zero();
  40353. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  40354. if (collidedMesh === void 0) { collidedMesh = null; }
  40355. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  40356. newPosition.multiplyInPlace(_this._collider._radius);
  40357. }
  40358. if (!collidedMesh) {
  40359. _this._previousPosition.copyFrom(_this.position);
  40360. }
  40361. else {
  40362. _this.setPosition(newPosition);
  40363. if (_this.onCollide) {
  40364. _this.onCollide(collidedMesh);
  40365. }
  40366. }
  40367. // Recompute because of constraints
  40368. var cosa = Math.cos(_this.alpha);
  40369. var sina = Math.sin(_this.alpha);
  40370. var cosb = Math.cos(_this.beta);
  40371. var sinb = Math.sin(_this.beta);
  40372. if (sinb === 0) {
  40373. sinb = 0.0001;
  40374. }
  40375. var target = _this._getTargetPosition();
  40376. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  40377. _this.position.copyFrom(_this._newPosition);
  40378. var up = _this.upVector;
  40379. if (_this.allowUpsideDown && _this.beta < 0) {
  40380. up = up.clone();
  40381. up = up.negate();
  40382. }
  40383. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  40384. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  40385. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  40386. _this._collisionTriggered = false;
  40387. };
  40388. _this._target = BABYLON.Vector3.Zero();
  40389. if (target) {
  40390. _this.setTarget(target);
  40391. }
  40392. _this.alpha = alpha;
  40393. _this.beta = beta;
  40394. _this.radius = radius;
  40395. _this.getViewMatrix();
  40396. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  40397. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  40398. return _this;
  40399. }
  40400. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  40401. get: function () {
  40402. return this._target;
  40403. },
  40404. set: function (value) {
  40405. this.setTarget(value);
  40406. },
  40407. enumerable: true,
  40408. configurable: true
  40409. });
  40410. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  40411. //-- begin properties for backward compatibility for inputs
  40412. get: function () {
  40413. var pointers = this.inputs.attached["pointers"];
  40414. if (pointers)
  40415. return pointers.angularSensibilityX;
  40416. return 0;
  40417. },
  40418. set: function (value) {
  40419. var pointers = this.inputs.attached["pointers"];
  40420. if (pointers) {
  40421. pointers.angularSensibilityX = value;
  40422. }
  40423. },
  40424. enumerable: true,
  40425. configurable: true
  40426. });
  40427. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  40428. get: function () {
  40429. var pointers = this.inputs.attached["pointers"];
  40430. if (pointers)
  40431. return pointers.angularSensibilityY;
  40432. return 0;
  40433. },
  40434. set: function (value) {
  40435. var pointers = this.inputs.attached["pointers"];
  40436. if (pointers) {
  40437. pointers.angularSensibilityY = value;
  40438. }
  40439. },
  40440. enumerable: true,
  40441. configurable: true
  40442. });
  40443. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  40444. get: function () {
  40445. var pointers = this.inputs.attached["pointers"];
  40446. if (pointers)
  40447. return pointers.pinchPrecision;
  40448. return 0;
  40449. },
  40450. set: function (value) {
  40451. var pointers = this.inputs.attached["pointers"];
  40452. if (pointers) {
  40453. pointers.pinchPrecision = value;
  40454. }
  40455. },
  40456. enumerable: true,
  40457. configurable: true
  40458. });
  40459. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  40460. get: function () {
  40461. var pointers = this.inputs.attached["pointers"];
  40462. if (pointers)
  40463. return pointers.pinchDeltaPercentage;
  40464. return 0;
  40465. },
  40466. set: function (value) {
  40467. var pointers = this.inputs.attached["pointers"];
  40468. if (pointers) {
  40469. pointers.pinchDeltaPercentage = value;
  40470. }
  40471. },
  40472. enumerable: true,
  40473. configurable: true
  40474. });
  40475. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40476. get: function () {
  40477. var pointers = this.inputs.attached["pointers"];
  40478. if (pointers)
  40479. return pointers.panningSensibility;
  40480. return 0;
  40481. },
  40482. set: function (value) {
  40483. var pointers = this.inputs.attached["pointers"];
  40484. if (pointers) {
  40485. pointers.panningSensibility = value;
  40486. }
  40487. },
  40488. enumerable: true,
  40489. configurable: true
  40490. });
  40491. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40492. get: function () {
  40493. var keyboard = this.inputs.attached["keyboard"];
  40494. if (keyboard)
  40495. return keyboard.keysUp;
  40496. return [];
  40497. },
  40498. set: function (value) {
  40499. var keyboard = this.inputs.attached["keyboard"];
  40500. if (keyboard)
  40501. keyboard.keysUp = value;
  40502. },
  40503. enumerable: true,
  40504. configurable: true
  40505. });
  40506. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40507. get: function () {
  40508. var keyboard = this.inputs.attached["keyboard"];
  40509. if (keyboard)
  40510. return keyboard.keysDown;
  40511. return [];
  40512. },
  40513. set: function (value) {
  40514. var keyboard = this.inputs.attached["keyboard"];
  40515. if (keyboard)
  40516. keyboard.keysDown = value;
  40517. },
  40518. enumerable: true,
  40519. configurable: true
  40520. });
  40521. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40522. get: function () {
  40523. var keyboard = this.inputs.attached["keyboard"];
  40524. if (keyboard)
  40525. return keyboard.keysLeft;
  40526. return [];
  40527. },
  40528. set: function (value) {
  40529. var keyboard = this.inputs.attached["keyboard"];
  40530. if (keyboard)
  40531. keyboard.keysLeft = value;
  40532. },
  40533. enumerable: true,
  40534. configurable: true
  40535. });
  40536. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40537. get: function () {
  40538. var keyboard = this.inputs.attached["keyboard"];
  40539. if (keyboard)
  40540. return keyboard.keysRight;
  40541. return [];
  40542. },
  40543. set: function (value) {
  40544. var keyboard = this.inputs.attached["keyboard"];
  40545. if (keyboard)
  40546. keyboard.keysRight = value;
  40547. },
  40548. enumerable: true,
  40549. configurable: true
  40550. });
  40551. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40552. get: function () {
  40553. var mousewheel = this.inputs.attached["mousewheel"];
  40554. if (mousewheel)
  40555. return mousewheel.wheelPrecision;
  40556. return 0;
  40557. },
  40558. set: function (value) {
  40559. var mousewheel = this.inputs.attached["mousewheel"];
  40560. if (mousewheel)
  40561. mousewheel.wheelPrecision = value;
  40562. },
  40563. enumerable: true,
  40564. configurable: true
  40565. });
  40566. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40567. get: function () {
  40568. var mousewheel = this.inputs.attached["mousewheel"];
  40569. if (mousewheel)
  40570. return mousewheel.wheelDeltaPercentage;
  40571. return 0;
  40572. },
  40573. set: function (value) {
  40574. var mousewheel = this.inputs.attached["mousewheel"];
  40575. if (mousewheel)
  40576. mousewheel.wheelDeltaPercentage = value;
  40577. },
  40578. enumerable: true,
  40579. configurable: true
  40580. });
  40581. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40582. get: function () {
  40583. return this._bouncingBehavior;
  40584. },
  40585. enumerable: true,
  40586. configurable: true
  40587. });
  40588. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40589. get: function () {
  40590. return this._bouncingBehavior != null;
  40591. },
  40592. set: function (value) {
  40593. if (value === this.useBouncingBehavior) {
  40594. return;
  40595. }
  40596. if (value) {
  40597. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40598. this.addBehavior(this._bouncingBehavior);
  40599. }
  40600. else if (this._bouncingBehavior) {
  40601. this.removeBehavior(this._bouncingBehavior);
  40602. this._bouncingBehavior = null;
  40603. }
  40604. },
  40605. enumerable: true,
  40606. configurable: true
  40607. });
  40608. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40609. get: function () {
  40610. return this._framingBehavior;
  40611. },
  40612. enumerable: true,
  40613. configurable: true
  40614. });
  40615. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40616. get: function () {
  40617. return this._framingBehavior != null;
  40618. },
  40619. set: function (value) {
  40620. if (value === this.useFramingBehavior) {
  40621. return;
  40622. }
  40623. if (value) {
  40624. this._framingBehavior = new BABYLON.FramingBehavior();
  40625. this.addBehavior(this._framingBehavior);
  40626. }
  40627. else if (this._framingBehavior) {
  40628. this.removeBehavior(this._framingBehavior);
  40629. this._framingBehavior = null;
  40630. }
  40631. },
  40632. enumerable: true,
  40633. configurable: true
  40634. });
  40635. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40636. get: function () {
  40637. return this._autoRotationBehavior;
  40638. },
  40639. enumerable: true,
  40640. configurable: true
  40641. });
  40642. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40643. get: function () {
  40644. return this._autoRotationBehavior != null;
  40645. },
  40646. set: function (value) {
  40647. if (value === this.useAutoRotationBehavior) {
  40648. return;
  40649. }
  40650. if (value) {
  40651. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40652. this.addBehavior(this._autoRotationBehavior);
  40653. }
  40654. else if (this._autoRotationBehavior) {
  40655. this.removeBehavior(this._autoRotationBehavior);
  40656. this._autoRotationBehavior = null;
  40657. }
  40658. },
  40659. enumerable: true,
  40660. configurable: true
  40661. });
  40662. // Cache
  40663. ArcRotateCamera.prototype._initCache = function () {
  40664. _super.prototype._initCache.call(this);
  40665. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40666. this._cache.alpha = undefined;
  40667. this._cache.beta = undefined;
  40668. this._cache.radius = undefined;
  40669. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40670. };
  40671. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40672. if (!ignoreParentClass) {
  40673. _super.prototype._updateCache.call(this);
  40674. }
  40675. this._cache._target.copyFrom(this._getTargetPosition());
  40676. this._cache.alpha = this.alpha;
  40677. this._cache.beta = this.beta;
  40678. this._cache.radius = this.radius;
  40679. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40680. };
  40681. ArcRotateCamera.prototype._getTargetPosition = function () {
  40682. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40683. var pos = this._targetHost.getAbsolutePosition();
  40684. if (this._targetBoundingCenter) {
  40685. pos.addToRef(this._targetBoundingCenter, this._target);
  40686. }
  40687. else {
  40688. this._target.copyFrom(pos);
  40689. }
  40690. }
  40691. var lockedTargetPosition = this._getLockedTargetPosition();
  40692. if (lockedTargetPosition) {
  40693. return lockedTargetPosition;
  40694. }
  40695. return this._target;
  40696. };
  40697. ArcRotateCamera.prototype.storeState = function () {
  40698. this._storedAlpha = this.alpha;
  40699. this._storedBeta = this.beta;
  40700. this._storedRadius = this.radius;
  40701. this._storedTarget = this._getTargetPosition().clone();
  40702. return _super.prototype.storeState.call(this);
  40703. };
  40704. /**
  40705. * Restored camera state. You must call storeState() first
  40706. */
  40707. ArcRotateCamera.prototype._restoreStateValues = function () {
  40708. if (!_super.prototype._restoreStateValues.call(this)) {
  40709. return false;
  40710. }
  40711. this.alpha = this._storedAlpha;
  40712. this.beta = this._storedBeta;
  40713. this.radius = this._storedRadius;
  40714. this.setTarget(this._storedTarget.clone());
  40715. this.inertialAlphaOffset = 0;
  40716. this.inertialBetaOffset = 0;
  40717. this.inertialRadiusOffset = 0;
  40718. this.inertialPanningX = 0;
  40719. this.inertialPanningY = 0;
  40720. return true;
  40721. };
  40722. // Synchronized
  40723. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40724. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40725. return false;
  40726. return this._cache._target.equals(this._getTargetPosition())
  40727. && this._cache.alpha === this.alpha
  40728. && this._cache.beta === this.beta
  40729. && this._cache.radius === this.radius
  40730. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40731. };
  40732. // Methods
  40733. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40734. var _this = this;
  40735. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40736. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40737. this._useCtrlForPanning = useCtrlForPanning;
  40738. this._panningMouseButton = panningMouseButton;
  40739. this.inputs.attachElement(element, noPreventDefault);
  40740. this._reset = function () {
  40741. _this.inertialAlphaOffset = 0;
  40742. _this.inertialBetaOffset = 0;
  40743. _this.inertialRadiusOffset = 0;
  40744. _this.inertialPanningX = 0;
  40745. _this.inertialPanningY = 0;
  40746. };
  40747. };
  40748. ArcRotateCamera.prototype.detachControl = function (element) {
  40749. this.inputs.detachElement(element);
  40750. if (this._reset) {
  40751. this._reset();
  40752. }
  40753. };
  40754. ArcRotateCamera.prototype._checkInputs = function () {
  40755. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40756. if (this._collisionTriggered) {
  40757. return;
  40758. }
  40759. this.inputs.checkInputs();
  40760. // Inertia
  40761. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40762. if (this.getScene().useRightHandedSystem) {
  40763. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40764. }
  40765. else {
  40766. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40767. }
  40768. this.beta += this.inertialBetaOffset;
  40769. this.radius -= this.inertialRadiusOffset;
  40770. this.inertialAlphaOffset *= this.inertia;
  40771. this.inertialBetaOffset *= this.inertia;
  40772. this.inertialRadiusOffset *= this.inertia;
  40773. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40774. this.inertialAlphaOffset = 0;
  40775. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40776. this.inertialBetaOffset = 0;
  40777. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40778. this.inertialRadiusOffset = 0;
  40779. }
  40780. // Panning inertia
  40781. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40782. if (!this._localDirection) {
  40783. this._localDirection = BABYLON.Vector3.Zero();
  40784. this._transformedDirection = BABYLON.Vector3.Zero();
  40785. }
  40786. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40787. this._localDirection.multiplyInPlace(this.panningAxis);
  40788. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40789. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40790. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40791. if (!this.panningAxis.y) {
  40792. this._transformedDirection.y = 0;
  40793. }
  40794. if (!this._targetHost) {
  40795. if (this.panningDistanceLimit) {
  40796. this._transformedDirection.addInPlace(this._target);
  40797. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40798. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40799. this._target.copyFrom(this._transformedDirection);
  40800. }
  40801. }
  40802. else {
  40803. this._target.addInPlace(this._transformedDirection);
  40804. }
  40805. }
  40806. this.inertialPanningX *= this.panningInertia;
  40807. this.inertialPanningY *= this.panningInertia;
  40808. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40809. this.inertialPanningX = 0;
  40810. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40811. this.inertialPanningY = 0;
  40812. }
  40813. // Limits
  40814. this._checkLimits();
  40815. _super.prototype._checkInputs.call(this);
  40816. };
  40817. ArcRotateCamera.prototype._checkLimits = function () {
  40818. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40819. if (this.allowUpsideDown && this.beta > Math.PI) {
  40820. this.beta = this.beta - (2 * Math.PI);
  40821. }
  40822. }
  40823. else {
  40824. if (this.beta < this.lowerBetaLimit) {
  40825. this.beta = this.lowerBetaLimit;
  40826. }
  40827. }
  40828. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40829. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40830. this.beta = this.beta + (2 * Math.PI);
  40831. }
  40832. }
  40833. else {
  40834. if (this.beta > this.upperBetaLimit) {
  40835. this.beta = this.upperBetaLimit;
  40836. }
  40837. }
  40838. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40839. this.alpha = this.lowerAlphaLimit;
  40840. }
  40841. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40842. this.alpha = this.upperAlphaLimit;
  40843. }
  40844. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40845. this.radius = this.lowerRadiusLimit;
  40846. }
  40847. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40848. this.radius = this.upperRadiusLimit;
  40849. }
  40850. };
  40851. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40852. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40853. this.radius = radiusv3.length();
  40854. if (this.radius === 0) {
  40855. this.radius = 0.0001; // Just to avoid division by zero
  40856. }
  40857. // Alpha
  40858. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40859. if (radiusv3.z < 0) {
  40860. this.alpha = 2 * Math.PI - this.alpha;
  40861. }
  40862. // Beta
  40863. this.beta = Math.acos(radiusv3.y / this.radius);
  40864. this._checkLimits();
  40865. };
  40866. ArcRotateCamera.prototype.setPosition = function (position) {
  40867. if (this.position.equals(position)) {
  40868. return;
  40869. }
  40870. this.position.copyFrom(position);
  40871. this.rebuildAnglesAndRadius();
  40872. };
  40873. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40874. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40875. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40876. if (target.getBoundingInfo) {
  40877. if (toBoundingCenter) {
  40878. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40879. }
  40880. else {
  40881. this._targetBoundingCenter = null;
  40882. }
  40883. this._targetHost = target;
  40884. this._target = this._getTargetPosition();
  40885. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40886. }
  40887. else {
  40888. var newTarget = target;
  40889. var currentTarget = this._getTargetPosition();
  40890. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40891. return;
  40892. }
  40893. this._targetHost = null;
  40894. this._target = newTarget;
  40895. this._targetBoundingCenter = null;
  40896. this.onMeshTargetChangedObservable.notifyObservers(null);
  40897. }
  40898. this.rebuildAnglesAndRadius();
  40899. };
  40900. ArcRotateCamera.prototype._getViewMatrix = function () {
  40901. // Compute
  40902. var cosa = Math.cos(this.alpha);
  40903. var sina = Math.sin(this.alpha);
  40904. var cosb = Math.cos(this.beta);
  40905. var sinb = Math.sin(this.beta);
  40906. if (sinb === 0) {
  40907. sinb = 0.0001;
  40908. }
  40909. var target = this._getTargetPosition();
  40910. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40911. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40912. if (!this._collider) {
  40913. this._collider = new BABYLON.Collider();
  40914. }
  40915. this._collider._radius = this.collisionRadius;
  40916. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40917. this._collisionTriggered = true;
  40918. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40919. }
  40920. else {
  40921. this.position.copyFrom(this._newPosition);
  40922. var up = this.upVector;
  40923. if (this.allowUpsideDown && sinb < 0) {
  40924. up = up.clone();
  40925. up = up.negate();
  40926. }
  40927. if (this.getScene().useRightHandedSystem) {
  40928. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40929. }
  40930. else {
  40931. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40932. }
  40933. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40934. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40935. }
  40936. this._currentTarget = target;
  40937. return this._viewMatrix;
  40938. };
  40939. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40940. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40941. meshes = meshes || this.getScene().meshes;
  40942. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40943. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40944. this.radius = distance * this.zoomOnFactor;
  40945. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40946. };
  40947. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40948. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40949. var meshesOrMinMaxVector;
  40950. var distance;
  40951. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40952. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40953. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40954. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40955. }
  40956. else {
  40957. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40958. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40959. distance = minMaxVectorAndDistance.distance;
  40960. }
  40961. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40962. if (!doNotUpdateMaxZ) {
  40963. this.maxZ = distance * 2;
  40964. }
  40965. };
  40966. /**
  40967. * @override
  40968. * Override Camera.createRigCamera
  40969. */
  40970. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40971. var alphaShift = 0;
  40972. switch (this.cameraRigMode) {
  40973. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40974. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40975. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40976. case BABYLON.Camera.RIG_MODE_VR:
  40977. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40978. break;
  40979. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40980. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40981. break;
  40982. }
  40983. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40984. rigCam._cameraRigParams = {};
  40985. return rigCam;
  40986. };
  40987. /**
  40988. * @override
  40989. * Override Camera._updateRigCameras
  40990. */
  40991. ArcRotateCamera.prototype._updateRigCameras = function () {
  40992. var camLeft = this._rigCameras[0];
  40993. var camRight = this._rigCameras[1];
  40994. camLeft.beta = camRight.beta = this.beta;
  40995. camLeft.radius = camRight.radius = this.radius;
  40996. switch (this.cameraRigMode) {
  40997. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40998. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40999. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  41000. case BABYLON.Camera.RIG_MODE_VR:
  41001. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41002. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41003. break;
  41004. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  41005. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  41006. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  41007. break;
  41008. }
  41009. _super.prototype._updateRigCameras.call(this);
  41010. };
  41011. ArcRotateCamera.prototype.dispose = function () {
  41012. this.inputs.clear();
  41013. _super.prototype.dispose.call(this);
  41014. };
  41015. ArcRotateCamera.prototype.getClassName = function () {
  41016. return "ArcRotateCamera";
  41017. };
  41018. __decorate([
  41019. BABYLON.serialize()
  41020. ], ArcRotateCamera.prototype, "alpha", void 0);
  41021. __decorate([
  41022. BABYLON.serialize()
  41023. ], ArcRotateCamera.prototype, "beta", void 0);
  41024. __decorate([
  41025. BABYLON.serialize()
  41026. ], ArcRotateCamera.prototype, "radius", void 0);
  41027. __decorate([
  41028. BABYLON.serializeAsVector3("target")
  41029. ], ArcRotateCamera.prototype, "_target", void 0);
  41030. __decorate([
  41031. BABYLON.serialize()
  41032. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  41033. __decorate([
  41034. BABYLON.serialize()
  41035. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  41036. __decorate([
  41037. BABYLON.serialize()
  41038. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  41039. __decorate([
  41040. BABYLON.serialize()
  41041. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  41042. __decorate([
  41043. BABYLON.serialize()
  41044. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  41045. __decorate([
  41046. BABYLON.serialize()
  41047. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  41048. __decorate([
  41049. BABYLON.serialize()
  41050. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  41051. __decorate([
  41052. BABYLON.serialize()
  41053. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  41054. __decorate([
  41055. BABYLON.serialize()
  41056. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  41057. __decorate([
  41058. BABYLON.serialize()
  41059. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  41060. __decorate([
  41061. BABYLON.serialize()
  41062. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  41063. __decorate([
  41064. BABYLON.serialize()
  41065. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  41066. __decorate([
  41067. BABYLON.serialize()
  41068. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  41069. __decorate([
  41070. BABYLON.serializeAsVector3()
  41071. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  41072. __decorate([
  41073. BABYLON.serialize()
  41074. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  41075. __decorate([
  41076. BABYLON.serialize()
  41077. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  41078. __decorate([
  41079. BABYLON.serialize()
  41080. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  41081. return ArcRotateCamera;
  41082. }(BABYLON.TargetCamera));
  41083. BABYLON.ArcRotateCamera = ArcRotateCamera;
  41084. })(BABYLON || (BABYLON = {}));
  41085. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  41086. var BABYLON;
  41087. (function (BABYLON) {
  41088. var HemisphericLight = /** @class */ (function (_super) {
  41089. __extends(HemisphericLight, _super);
  41090. /**
  41091. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  41092. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  41093. * The HemisphericLight can't cast shadows.
  41094. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41095. */
  41096. function HemisphericLight(name, direction, scene) {
  41097. var _this = _super.call(this, name, scene) || this;
  41098. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  41099. _this.direction = direction || BABYLON.Vector3.Up();
  41100. return _this;
  41101. }
  41102. HemisphericLight.prototype._buildUniformLayout = function () {
  41103. this._uniformBuffer.addUniform("vLightData", 4);
  41104. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41105. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41106. this._uniformBuffer.addUniform("vLightGround", 3);
  41107. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41108. this._uniformBuffer.addUniform("depthValues", 2);
  41109. this._uniformBuffer.create();
  41110. };
  41111. /**
  41112. * Returns the string "HemisphericLight".
  41113. */
  41114. HemisphericLight.prototype.getClassName = function () {
  41115. return "HemisphericLight";
  41116. };
  41117. /**
  41118. * Sets the HemisphericLight direction towards the passed target (Vector3).
  41119. * Returns the updated direction.
  41120. */
  41121. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  41122. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  41123. return this.direction;
  41124. };
  41125. HemisphericLight.prototype.getShadowGenerator = function () {
  41126. return null;
  41127. };
  41128. /**
  41129. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  41130. * Returns the HemisphericLight.
  41131. */
  41132. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  41133. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41134. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  41135. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  41136. return this;
  41137. };
  41138. HemisphericLight.prototype._getWorldMatrix = function () {
  41139. if (!this._worldMatrix) {
  41140. this._worldMatrix = BABYLON.Matrix.Identity();
  41141. }
  41142. return this._worldMatrix;
  41143. };
  41144. /**
  41145. * Returns the integer 3.
  41146. */
  41147. HemisphericLight.prototype.getTypeID = function () {
  41148. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  41149. };
  41150. __decorate([
  41151. BABYLON.serializeAsColor3()
  41152. ], HemisphericLight.prototype, "groundColor", void 0);
  41153. __decorate([
  41154. BABYLON.serializeAsVector3()
  41155. ], HemisphericLight.prototype, "direction", void 0);
  41156. return HemisphericLight;
  41157. }(BABYLON.Light));
  41158. BABYLON.HemisphericLight = HemisphericLight;
  41159. })(BABYLON || (BABYLON = {}));
  41160. //# sourceMappingURL=babylon.hemisphericLight.js.map
  41161. var BABYLON;
  41162. (function (BABYLON) {
  41163. var ShadowLight = /** @class */ (function (_super) {
  41164. __extends(ShadowLight, _super);
  41165. function ShadowLight() {
  41166. var _this = _super !== null && _super.apply(this, arguments) || this;
  41167. _this._needProjectionMatrixCompute = true;
  41168. return _this;
  41169. }
  41170. Object.defineProperty(ShadowLight.prototype, "direction", {
  41171. get: function () {
  41172. return this._direction;
  41173. },
  41174. set: function (value) {
  41175. this._direction = value;
  41176. },
  41177. enumerable: true,
  41178. configurable: true
  41179. });
  41180. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  41181. get: function () {
  41182. return this._shadowMinZ;
  41183. },
  41184. set: function (value) {
  41185. this._shadowMinZ = value;
  41186. this.forceProjectionMatrixCompute();
  41187. },
  41188. enumerable: true,
  41189. configurable: true
  41190. });
  41191. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  41192. get: function () {
  41193. return this._shadowMaxZ;
  41194. },
  41195. set: function (value) {
  41196. this._shadowMaxZ = value;
  41197. this.forceProjectionMatrixCompute();
  41198. },
  41199. enumerable: true,
  41200. configurable: true
  41201. });
  41202. /**
  41203. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  41204. */
  41205. ShadowLight.prototype.computeTransformedInformation = function () {
  41206. if (this.parent && this.parent.getWorldMatrix) {
  41207. if (!this.transformedPosition) {
  41208. this.transformedPosition = BABYLON.Vector3.Zero();
  41209. }
  41210. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  41211. // In case the direction is present.
  41212. if (this.direction) {
  41213. if (!this.transformedDirection) {
  41214. this.transformedDirection = BABYLON.Vector3.Zero();
  41215. }
  41216. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  41217. }
  41218. return true;
  41219. }
  41220. return false;
  41221. };
  41222. /**
  41223. * Return the depth scale used for the shadow map.
  41224. */
  41225. ShadowLight.prototype.getDepthScale = function () {
  41226. return 50.0;
  41227. };
  41228. /**
  41229. * Returns the light direction (Vector3) for any passed face index.
  41230. */
  41231. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  41232. return this.transformedDirection ? this.transformedDirection : this.direction;
  41233. };
  41234. /**
  41235. * Returns the ShadowLight absolute position in the World.
  41236. */
  41237. ShadowLight.prototype.getAbsolutePosition = function () {
  41238. return this.transformedPosition ? this.transformedPosition : this.position;
  41239. };
  41240. /**
  41241. * Sets the ShadowLight direction toward the passed target (Vector3).
  41242. * Returns the updated ShadowLight direction (Vector3).
  41243. */
  41244. ShadowLight.prototype.setDirectionToTarget = function (target) {
  41245. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  41246. return this.direction;
  41247. };
  41248. /**
  41249. * Returns the light rotation (Vector3).
  41250. */
  41251. ShadowLight.prototype.getRotation = function () {
  41252. this.direction.normalize();
  41253. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  41254. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  41255. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  41256. };
  41257. /**
  41258. * Boolean : false by default.
  41259. */
  41260. ShadowLight.prototype.needCube = function () {
  41261. return false;
  41262. };
  41263. /**
  41264. * Specifies wether or not the projection matrix should be recomputed this frame.
  41265. */
  41266. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  41267. return this._needProjectionMatrixCompute;
  41268. };
  41269. /**
  41270. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  41271. */
  41272. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  41273. this._needProjectionMatrixCompute = true;
  41274. };
  41275. /**
  41276. * Get the world matrix of the sahdow lights.
  41277. */
  41278. ShadowLight.prototype._getWorldMatrix = function () {
  41279. if (!this._worldMatrix) {
  41280. this._worldMatrix = BABYLON.Matrix.Identity();
  41281. }
  41282. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  41283. return this._worldMatrix;
  41284. };
  41285. /**
  41286. * Gets the minZ used for shadow according to both the scene and the light.
  41287. * @param activeCamera
  41288. */
  41289. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  41290. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  41291. };
  41292. /**
  41293. * Gets the maxZ used for shadow according to both the scene and the light.
  41294. * @param activeCamera
  41295. */
  41296. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  41297. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  41298. };
  41299. /**
  41300. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  41301. * Returns the light.
  41302. */
  41303. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41304. if (this.customProjectionMatrixBuilder) {
  41305. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  41306. }
  41307. else {
  41308. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41309. }
  41310. return this;
  41311. };
  41312. __decorate([
  41313. BABYLON.serializeAsVector3()
  41314. ], ShadowLight.prototype, "position", void 0);
  41315. __decorate([
  41316. BABYLON.serializeAsVector3()
  41317. ], ShadowLight.prototype, "direction", null);
  41318. __decorate([
  41319. BABYLON.serialize()
  41320. ], ShadowLight.prototype, "shadowMinZ", null);
  41321. __decorate([
  41322. BABYLON.serialize()
  41323. ], ShadowLight.prototype, "shadowMaxZ", null);
  41324. return ShadowLight;
  41325. }(BABYLON.Light));
  41326. BABYLON.ShadowLight = ShadowLight;
  41327. })(BABYLON || (BABYLON = {}));
  41328. //# sourceMappingURL=babylon.shadowLight.js.map
  41329. var BABYLON;
  41330. (function (BABYLON) {
  41331. var PointLight = /** @class */ (function (_super) {
  41332. __extends(PointLight, _super);
  41333. /**
  41334. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  41335. * A PointLight emits the light in every direction.
  41336. * It can cast shadows.
  41337. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  41338. * ```javascript
  41339. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  41340. * ```
  41341. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41342. */
  41343. function PointLight(name, position, scene) {
  41344. var _this = _super.call(this, name, scene) || this;
  41345. _this._shadowAngle = Math.PI / 2;
  41346. _this.position = position;
  41347. return _this;
  41348. }
  41349. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  41350. /**
  41351. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41352. * This specifies what angle the shadow will use to be created.
  41353. *
  41354. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41355. */
  41356. get: function () {
  41357. return this._shadowAngle;
  41358. },
  41359. /**
  41360. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41361. * This specifies what angle the shadow will use to be created.
  41362. *
  41363. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  41364. */
  41365. set: function (value) {
  41366. this._shadowAngle = value;
  41367. this.forceProjectionMatrixCompute();
  41368. },
  41369. enumerable: true,
  41370. configurable: true
  41371. });
  41372. Object.defineProperty(PointLight.prototype, "direction", {
  41373. get: function () {
  41374. return this._direction;
  41375. },
  41376. /**
  41377. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  41378. */
  41379. set: function (value) {
  41380. var previousNeedCube = this.needCube();
  41381. this._direction = value;
  41382. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  41383. this._shadowGenerator.recreateShadowMap();
  41384. }
  41385. },
  41386. enumerable: true,
  41387. configurable: true
  41388. });
  41389. /**
  41390. * Returns the string "PointLight"
  41391. */
  41392. PointLight.prototype.getClassName = function () {
  41393. return "PointLight";
  41394. };
  41395. /**
  41396. * Returns the integer 0.
  41397. */
  41398. PointLight.prototype.getTypeID = function () {
  41399. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  41400. };
  41401. /**
  41402. * Specifies wether or not the shadowmap should be a cube texture.
  41403. */
  41404. PointLight.prototype.needCube = function () {
  41405. return !this.direction;
  41406. };
  41407. /**
  41408. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  41409. */
  41410. PointLight.prototype.getShadowDirection = function (faceIndex) {
  41411. if (this.direction) {
  41412. return _super.prototype.getShadowDirection.call(this, faceIndex);
  41413. }
  41414. else {
  41415. switch (faceIndex) {
  41416. case 0:
  41417. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  41418. case 1:
  41419. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  41420. case 2:
  41421. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  41422. case 3:
  41423. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  41424. case 4:
  41425. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  41426. case 5:
  41427. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  41428. }
  41429. }
  41430. return BABYLON.Vector3.Zero();
  41431. };
  41432. /**
  41433. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41434. * - fov = PI / 2
  41435. * - aspect ratio : 1.0
  41436. * - z-near and far equal to the active camera minZ and maxZ.
  41437. * Returns the PointLight.
  41438. */
  41439. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41440. var activeCamera = this.getScene().activeCamera;
  41441. if (!activeCamera) {
  41442. return;
  41443. }
  41444. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41445. };
  41446. PointLight.prototype._buildUniformLayout = function () {
  41447. this._uniformBuffer.addUniform("vLightData", 4);
  41448. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41449. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41450. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41451. this._uniformBuffer.addUniform("depthValues", 2);
  41452. this._uniformBuffer.create();
  41453. };
  41454. /**
  41455. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41456. * Returns the PointLight.
  41457. */
  41458. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41459. if (this.computeTransformedInformation()) {
  41460. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41461. return this;
  41462. }
  41463. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41464. return this;
  41465. };
  41466. __decorate([
  41467. BABYLON.serialize()
  41468. ], PointLight.prototype, "shadowAngle", null);
  41469. return PointLight;
  41470. }(BABYLON.ShadowLight));
  41471. BABYLON.PointLight = PointLight;
  41472. })(BABYLON || (BABYLON = {}));
  41473. //# sourceMappingURL=babylon.pointLight.js.map
  41474. var BABYLON;
  41475. (function (BABYLON) {
  41476. var DirectionalLight = /** @class */ (function (_super) {
  41477. __extends(DirectionalLight, _super);
  41478. /**
  41479. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41480. * The directional light is emitted from everywhere in the given direction.
  41481. * It can cast shawdows.
  41482. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41483. */
  41484. function DirectionalLight(name, direction, scene) {
  41485. var _this = _super.call(this, name, scene) || this;
  41486. _this._shadowFrustumSize = 0;
  41487. _this._shadowOrthoScale = 0.5;
  41488. _this.autoUpdateExtends = true;
  41489. // Cache
  41490. _this._orthoLeft = Number.MAX_VALUE;
  41491. _this._orthoRight = Number.MIN_VALUE;
  41492. _this._orthoTop = Number.MIN_VALUE;
  41493. _this._orthoBottom = Number.MAX_VALUE;
  41494. _this.position = direction.scale(-1.0);
  41495. _this.direction = direction;
  41496. return _this;
  41497. }
  41498. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41499. /**
  41500. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41501. */
  41502. get: function () {
  41503. return this._shadowFrustumSize;
  41504. },
  41505. /**
  41506. * Specifies a fix frustum size for the shadow generation.
  41507. */
  41508. set: function (value) {
  41509. this._shadowFrustumSize = value;
  41510. this.forceProjectionMatrixCompute();
  41511. },
  41512. enumerable: true,
  41513. configurable: true
  41514. });
  41515. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41516. get: function () {
  41517. return this._shadowOrthoScale;
  41518. },
  41519. set: function (value) {
  41520. this._shadowOrthoScale = value;
  41521. this.forceProjectionMatrixCompute();
  41522. },
  41523. enumerable: true,
  41524. configurable: true
  41525. });
  41526. /**
  41527. * Returns the string "DirectionalLight".
  41528. */
  41529. DirectionalLight.prototype.getClassName = function () {
  41530. return "DirectionalLight";
  41531. };
  41532. /**
  41533. * Returns the integer 1.
  41534. */
  41535. DirectionalLight.prototype.getTypeID = function () {
  41536. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41537. };
  41538. /**
  41539. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41540. * Returns the DirectionalLight Shadow projection matrix.
  41541. */
  41542. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41543. if (this.shadowFrustumSize > 0) {
  41544. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41545. }
  41546. else {
  41547. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41548. }
  41549. };
  41550. /**
  41551. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41552. * Returns the DirectionalLight Shadow projection matrix.
  41553. */
  41554. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41555. var activeCamera = this.getScene().activeCamera;
  41556. if (!activeCamera) {
  41557. return;
  41558. }
  41559. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41560. };
  41561. /**
  41562. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41563. * Returns the DirectionalLight Shadow projection matrix.
  41564. */
  41565. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41566. var activeCamera = this.getScene().activeCamera;
  41567. if (!activeCamera) {
  41568. return;
  41569. }
  41570. // Check extends
  41571. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41572. var tempVector3 = BABYLON.Vector3.Zero();
  41573. this._orthoLeft = Number.MAX_VALUE;
  41574. this._orthoRight = Number.MIN_VALUE;
  41575. this._orthoTop = Number.MIN_VALUE;
  41576. this._orthoBottom = Number.MAX_VALUE;
  41577. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41578. var mesh = renderList[meshIndex];
  41579. if (!mesh) {
  41580. continue;
  41581. }
  41582. var boundingInfo = mesh.getBoundingInfo();
  41583. var boundingBox = boundingInfo.boundingBox;
  41584. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41585. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41586. if (tempVector3.x < this._orthoLeft)
  41587. this._orthoLeft = tempVector3.x;
  41588. if (tempVector3.y < this._orthoBottom)
  41589. this._orthoBottom = tempVector3.y;
  41590. if (tempVector3.x > this._orthoRight)
  41591. this._orthoRight = tempVector3.x;
  41592. if (tempVector3.y > this._orthoTop)
  41593. this._orthoTop = tempVector3.y;
  41594. }
  41595. }
  41596. }
  41597. var xOffset = this._orthoRight - this._orthoLeft;
  41598. var yOffset = this._orthoTop - this._orthoBottom;
  41599. 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);
  41600. };
  41601. DirectionalLight.prototype._buildUniformLayout = function () {
  41602. this._uniformBuffer.addUniform("vLightData", 4);
  41603. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41604. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41605. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41606. this._uniformBuffer.addUniform("depthValues", 2);
  41607. this._uniformBuffer.create();
  41608. };
  41609. /**
  41610. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41611. * Returns the DirectionalLight.
  41612. */
  41613. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41614. if (this.computeTransformedInformation()) {
  41615. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41616. return this;
  41617. }
  41618. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41619. return this;
  41620. };
  41621. /**
  41622. * Gets the minZ used for shadow according to both the scene and the light.
  41623. *
  41624. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41625. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41626. * @param activeCamera
  41627. */
  41628. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41629. return 1;
  41630. };
  41631. /**
  41632. * Gets the maxZ used for shadow according to both the scene and the light.
  41633. *
  41634. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41635. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41636. * @param activeCamera
  41637. */
  41638. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41639. return 1;
  41640. };
  41641. __decorate([
  41642. BABYLON.serialize()
  41643. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41644. __decorate([
  41645. BABYLON.serialize()
  41646. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41647. __decorate([
  41648. BABYLON.serialize()
  41649. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41650. return DirectionalLight;
  41651. }(BABYLON.ShadowLight));
  41652. BABYLON.DirectionalLight = DirectionalLight;
  41653. })(BABYLON || (BABYLON = {}));
  41654. //# sourceMappingURL=babylon.directionalLight.js.map
  41655. var BABYLON;
  41656. (function (BABYLON) {
  41657. var SpotLight = /** @class */ (function (_super) {
  41658. __extends(SpotLight, _super);
  41659. /**
  41660. * Creates a SpotLight object in the scene with the passed parameters :
  41661. * - `position` (Vector3) is the initial SpotLight position,
  41662. * - `direction` (Vector3) is the initial SpotLight direction,
  41663. * - `angle` (float, in radians) is the spot light cone angle,
  41664. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41665. * A spot light is a simply light oriented cone.
  41666. * It can cast shadows.
  41667. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41668. */
  41669. function SpotLight(name, position, direction, angle, exponent, scene) {
  41670. var _this = _super.call(this, name, scene) || this;
  41671. _this.position = position;
  41672. _this.direction = direction;
  41673. _this.angle = angle;
  41674. _this.exponent = exponent;
  41675. return _this;
  41676. }
  41677. Object.defineProperty(SpotLight.prototype, "angle", {
  41678. get: function () {
  41679. return this._angle;
  41680. },
  41681. set: function (value) {
  41682. this._angle = value;
  41683. this.forceProjectionMatrixCompute();
  41684. },
  41685. enumerable: true,
  41686. configurable: true
  41687. });
  41688. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41689. get: function () {
  41690. return this._shadowAngleScale;
  41691. },
  41692. /**
  41693. * Allows scaling the angle of the light for shadow generation only.
  41694. */
  41695. set: function (value) {
  41696. this._shadowAngleScale = value;
  41697. this.forceProjectionMatrixCompute();
  41698. },
  41699. enumerable: true,
  41700. configurable: true
  41701. });
  41702. /**
  41703. * Returns the string "SpotLight".
  41704. */
  41705. SpotLight.prototype.getClassName = function () {
  41706. return "SpotLight";
  41707. };
  41708. /**
  41709. * Returns the integer 2.
  41710. */
  41711. SpotLight.prototype.getTypeID = function () {
  41712. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41713. };
  41714. /**
  41715. * 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.
  41716. * Returns the SpotLight.
  41717. */
  41718. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41719. var activeCamera = this.getScene().activeCamera;
  41720. if (!activeCamera) {
  41721. return;
  41722. }
  41723. this._shadowAngleScale = this._shadowAngleScale || 1;
  41724. var angle = this._shadowAngleScale * this._angle;
  41725. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41726. };
  41727. SpotLight.prototype._buildUniformLayout = function () {
  41728. this._uniformBuffer.addUniform("vLightData", 4);
  41729. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41730. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41731. this._uniformBuffer.addUniform("vLightDirection", 3);
  41732. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41733. this._uniformBuffer.addUniform("depthValues", 2);
  41734. this._uniformBuffer.create();
  41735. };
  41736. /**
  41737. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41738. * Return the SpotLight.
  41739. */
  41740. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41741. var normalizeDirection;
  41742. if (this.computeTransformedInformation()) {
  41743. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41744. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41745. }
  41746. else {
  41747. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41748. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41749. }
  41750. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41751. return this;
  41752. };
  41753. __decorate([
  41754. BABYLON.serialize()
  41755. ], SpotLight.prototype, "angle", null);
  41756. __decorate([
  41757. BABYLON.serialize()
  41758. /**
  41759. * Allows scaling the angle of the light for shadow generation only.
  41760. */
  41761. ], SpotLight.prototype, "shadowAngleScale", null);
  41762. __decorate([
  41763. BABYLON.serialize()
  41764. ], SpotLight.prototype, "exponent", void 0);
  41765. return SpotLight;
  41766. }(BABYLON.ShadowLight));
  41767. BABYLON.SpotLight = SpotLight;
  41768. })(BABYLON || (BABYLON = {}));
  41769. //# sourceMappingURL=babylon.spotLight.js.map
  41770. var BABYLON;
  41771. (function (BABYLON) {
  41772. var AnimationRange = /** @class */ (function () {
  41773. function AnimationRange(name, from, to) {
  41774. this.name = name;
  41775. this.from = from;
  41776. this.to = to;
  41777. }
  41778. AnimationRange.prototype.clone = function () {
  41779. return new AnimationRange(this.name, this.from, this.to);
  41780. };
  41781. return AnimationRange;
  41782. }());
  41783. BABYLON.AnimationRange = AnimationRange;
  41784. /**
  41785. * Composed of a frame, and an action function
  41786. */
  41787. var AnimationEvent = /** @class */ (function () {
  41788. function AnimationEvent(frame, action, onlyOnce) {
  41789. this.frame = frame;
  41790. this.action = action;
  41791. this.onlyOnce = onlyOnce;
  41792. this.isDone = false;
  41793. }
  41794. return AnimationEvent;
  41795. }());
  41796. BABYLON.AnimationEvent = AnimationEvent;
  41797. var PathCursor = /** @class */ (function () {
  41798. function PathCursor(path) {
  41799. this.path = path;
  41800. this._onchange = new Array();
  41801. this.value = 0;
  41802. this.animations = new Array();
  41803. }
  41804. PathCursor.prototype.getPoint = function () {
  41805. var point = this.path.getPointAtLengthPosition(this.value);
  41806. return new BABYLON.Vector3(point.x, 0, point.y);
  41807. };
  41808. PathCursor.prototype.moveAhead = function (step) {
  41809. if (step === void 0) { step = 0.002; }
  41810. this.move(step);
  41811. return this;
  41812. };
  41813. PathCursor.prototype.moveBack = function (step) {
  41814. if (step === void 0) { step = 0.002; }
  41815. this.move(-step);
  41816. return this;
  41817. };
  41818. PathCursor.prototype.move = function (step) {
  41819. if (Math.abs(step) > 1) {
  41820. throw "step size should be less than 1.";
  41821. }
  41822. this.value += step;
  41823. this.ensureLimits();
  41824. this.raiseOnChange();
  41825. return this;
  41826. };
  41827. PathCursor.prototype.ensureLimits = function () {
  41828. while (this.value > 1) {
  41829. this.value -= 1;
  41830. }
  41831. while (this.value < 0) {
  41832. this.value += 1;
  41833. }
  41834. return this;
  41835. };
  41836. // used by animation engine
  41837. PathCursor.prototype.raiseOnChange = function () {
  41838. var _this = this;
  41839. this._onchange.forEach(function (f) { return f(_this); });
  41840. return this;
  41841. };
  41842. PathCursor.prototype.onchange = function (f) {
  41843. this._onchange.push(f);
  41844. return this;
  41845. };
  41846. return PathCursor;
  41847. }());
  41848. BABYLON.PathCursor = PathCursor;
  41849. var AnimationKeyInterpolation;
  41850. (function (AnimationKeyInterpolation) {
  41851. /**
  41852. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  41853. */
  41854. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  41855. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  41856. var Animation = /** @class */ (function () {
  41857. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41858. this.name = name;
  41859. this.targetProperty = targetProperty;
  41860. this.framePerSecond = framePerSecond;
  41861. this.dataType = dataType;
  41862. this.loopMode = loopMode;
  41863. this.enableBlending = enableBlending;
  41864. this._runtimeAnimations = new Array();
  41865. // The set of event that will be linked to this animation
  41866. this._events = new Array();
  41867. this.blendingSpeed = 0.01;
  41868. this._ranges = {};
  41869. this.targetPropertyPath = targetProperty.split(".");
  41870. this.dataType = dataType;
  41871. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41872. }
  41873. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41874. var dataType = undefined;
  41875. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41876. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41877. }
  41878. else if (from instanceof BABYLON.Quaternion) {
  41879. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41880. }
  41881. else if (from instanceof BABYLON.Vector3) {
  41882. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41883. }
  41884. else if (from instanceof BABYLON.Vector2) {
  41885. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41886. }
  41887. else if (from instanceof BABYLON.Color3) {
  41888. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41889. }
  41890. else if (from instanceof BABYLON.Size) {
  41891. dataType = Animation.ANIMATIONTYPE_SIZE;
  41892. }
  41893. if (dataType == undefined) {
  41894. return null;
  41895. }
  41896. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41897. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41898. animation.setKeys(keys);
  41899. if (easingFunction !== undefined) {
  41900. animation.setEasingFunction(easingFunction);
  41901. }
  41902. return animation;
  41903. };
  41904. /**
  41905. * Sets up an animation.
  41906. * @param property the property to animate
  41907. * @param animationType the animation type to apply
  41908. * @param easingFunction the easing function used in the animation
  41909. * @returns The created animation
  41910. */
  41911. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41912. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41913. animation.setEasingFunction(easingFunction);
  41914. return animation;
  41915. };
  41916. /**
  41917. * Create and start an animation on a node
  41918. * @param {string} name defines the name of the global animation that will be run on all nodes
  41919. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41920. * @param {string} targetProperty defines property to animate
  41921. * @param {number} framePerSecond defines the number of frame per second yo use
  41922. * @param {number} totalFrame defines the number of frames in total
  41923. * @param {any} from defines the initial value
  41924. * @param {any} to defines the final value
  41925. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41926. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41927. * @param onAnimationEnd defines the callback to call when animation end
  41928. * @returns the animatable created for this animation
  41929. */
  41930. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41931. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41932. if (!animation) {
  41933. return null;
  41934. }
  41935. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41936. };
  41937. /**
  41938. * Create and start an animation on a node and its descendants
  41939. * @param {string} name defines the name of the global animation that will be run on all nodes
  41940. * @param {BABYLON.Node} node defines the root node where the animation will take place
  41941. * @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.
  41942. * @param {string} targetProperty defines property to animate
  41943. * @param {number} framePerSecond defines the number of frame per second yo use
  41944. * @param {number} totalFrame defines the number of frames in total
  41945. * @param {any} from defines the initial value
  41946. * @param {any} to defines the final value
  41947. * @param {number} loopMode defines which loop mode you want to use (off by default)
  41948. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  41949. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  41950. * @returns the list of animatables created for all nodes
  41951. * @example https://www.babylonjs-playground.com/#MH0VLI
  41952. */
  41953. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41954. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41955. if (!animation) {
  41956. return null;
  41957. }
  41958. var scene = node.getScene();
  41959. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41960. };
  41961. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41962. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41963. if (!animation) {
  41964. return null;
  41965. }
  41966. node.animations.push(animation);
  41967. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41968. };
  41969. /**
  41970. * Transition property of the Camera to the target Value.
  41971. * @param property The property to transition
  41972. * @param targetValue The target Value of the property
  41973. * @param host The object where the property to animate belongs
  41974. * @param scene Scene used to run the animation
  41975. * @param frameRate Framerate (in frame/s) to use
  41976. * @param transition The transition type we want to use
  41977. * @param duration The duration of the animation, in milliseconds
  41978. * @param onAnimationEnd Call back trigger at the end of the animation.
  41979. */
  41980. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41981. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41982. if (duration <= 0) {
  41983. host[property] = targetValue;
  41984. if (onAnimationEnd) {
  41985. onAnimationEnd();
  41986. }
  41987. return null;
  41988. }
  41989. var endFrame = frameRate * (duration / 1000);
  41990. transition.setKeys([{
  41991. frame: 0,
  41992. value: host[property].clone ? host[property].clone() : host[property]
  41993. },
  41994. {
  41995. frame: endFrame,
  41996. value: targetValue
  41997. }]);
  41998. if (!host.animations) {
  41999. host.animations = [];
  42000. }
  42001. host.animations.push(transition);
  42002. var animation = scene.beginAnimation(host, 0, endFrame, false);
  42003. animation.onAnimationEnd = onAnimationEnd;
  42004. return animation;
  42005. };
  42006. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  42007. /**
  42008. * Return the array of runtime animations currently using this animation
  42009. */
  42010. get: function () {
  42011. return this._runtimeAnimations;
  42012. },
  42013. enumerable: true,
  42014. configurable: true
  42015. });
  42016. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  42017. get: function () {
  42018. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  42019. var runtimeAnimation = _a[_i];
  42020. if (!runtimeAnimation.isStopped) {
  42021. return true;
  42022. }
  42023. }
  42024. return false;
  42025. },
  42026. enumerable: true,
  42027. configurable: true
  42028. });
  42029. // Methods
  42030. /**
  42031. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  42032. */
  42033. Animation.prototype.toString = function (fullDetails) {
  42034. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  42035. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  42036. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  42037. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  42038. if (fullDetails) {
  42039. ret += ", Ranges: {";
  42040. var first = true;
  42041. for (var name in this._ranges) {
  42042. if (first) {
  42043. ret += ", ";
  42044. first = false;
  42045. }
  42046. ret += name;
  42047. }
  42048. ret += "}";
  42049. }
  42050. return ret;
  42051. };
  42052. /**
  42053. * Add an event to this animation.
  42054. */
  42055. Animation.prototype.addEvent = function (event) {
  42056. this._events.push(event);
  42057. };
  42058. /**
  42059. * Remove all events found at the given frame
  42060. * @param frame
  42061. */
  42062. Animation.prototype.removeEvents = function (frame) {
  42063. for (var index = 0; index < this._events.length; index++) {
  42064. if (this._events[index].frame === frame) {
  42065. this._events.splice(index, 1);
  42066. index--;
  42067. }
  42068. }
  42069. };
  42070. Animation.prototype.getEvents = function () {
  42071. return this._events;
  42072. };
  42073. Animation.prototype.createRange = function (name, from, to) {
  42074. // check name not already in use; could happen for bones after serialized
  42075. if (!this._ranges[name]) {
  42076. this._ranges[name] = new AnimationRange(name, from, to);
  42077. }
  42078. };
  42079. Animation.prototype.deleteRange = function (name, deleteFrames) {
  42080. if (deleteFrames === void 0) { deleteFrames = true; }
  42081. var range = this._ranges[name];
  42082. if (!range) {
  42083. return;
  42084. }
  42085. if (deleteFrames) {
  42086. var from = range.from;
  42087. var to = range.to;
  42088. // this loop MUST go high to low for multiple splices to work
  42089. for (var key = this._keys.length - 1; key >= 0; key--) {
  42090. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  42091. this._keys.splice(key, 1);
  42092. }
  42093. }
  42094. }
  42095. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  42096. };
  42097. Animation.prototype.getRange = function (name) {
  42098. return this._ranges[name];
  42099. };
  42100. Animation.prototype.getKeys = function () {
  42101. return this._keys;
  42102. };
  42103. Animation.prototype.getHighestFrame = function () {
  42104. var ret = 0;
  42105. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  42106. if (ret < this._keys[key].frame) {
  42107. ret = this._keys[key].frame;
  42108. }
  42109. }
  42110. return ret;
  42111. };
  42112. Animation.prototype.getEasingFunction = function () {
  42113. return this._easingFunction;
  42114. };
  42115. Animation.prototype.setEasingFunction = function (easingFunction) {
  42116. this._easingFunction = easingFunction;
  42117. };
  42118. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  42119. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  42120. };
  42121. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42122. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42123. };
  42124. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  42125. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  42126. };
  42127. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42128. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  42129. };
  42130. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  42131. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  42132. };
  42133. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42134. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42135. };
  42136. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  42137. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  42138. };
  42139. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  42140. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  42141. };
  42142. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  42143. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  42144. };
  42145. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  42146. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  42147. };
  42148. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  42149. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  42150. };
  42151. Animation.prototype.clone = function () {
  42152. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  42153. clone.enableBlending = this.enableBlending;
  42154. clone.blendingSpeed = this.blendingSpeed;
  42155. if (this._keys) {
  42156. clone.setKeys(this._keys);
  42157. }
  42158. if (this._ranges) {
  42159. clone._ranges = {};
  42160. for (var name in this._ranges) {
  42161. var range = this._ranges[name];
  42162. if (!range) {
  42163. continue;
  42164. }
  42165. clone._ranges[name] = range.clone();
  42166. }
  42167. }
  42168. return clone;
  42169. };
  42170. Animation.prototype.setKeys = function (values) {
  42171. this._keys = values.slice(0);
  42172. };
  42173. Animation.prototype.serialize = function () {
  42174. var serializationObject = {};
  42175. serializationObject.name = this.name;
  42176. serializationObject.property = this.targetProperty;
  42177. serializationObject.framePerSecond = this.framePerSecond;
  42178. serializationObject.dataType = this.dataType;
  42179. serializationObject.loopBehavior = this.loopMode;
  42180. serializationObject.enableBlending = this.enableBlending;
  42181. serializationObject.blendingSpeed = this.blendingSpeed;
  42182. var dataType = this.dataType;
  42183. serializationObject.keys = [];
  42184. var keys = this.getKeys();
  42185. for (var index = 0; index < keys.length; index++) {
  42186. var animationKey = keys[index];
  42187. var key = {};
  42188. key.frame = animationKey.frame;
  42189. switch (dataType) {
  42190. case Animation.ANIMATIONTYPE_FLOAT:
  42191. key.values = [animationKey.value];
  42192. break;
  42193. case Animation.ANIMATIONTYPE_QUATERNION:
  42194. case Animation.ANIMATIONTYPE_MATRIX:
  42195. case Animation.ANIMATIONTYPE_VECTOR3:
  42196. case Animation.ANIMATIONTYPE_COLOR3:
  42197. key.values = animationKey.value.asArray();
  42198. break;
  42199. }
  42200. serializationObject.keys.push(key);
  42201. }
  42202. serializationObject.ranges = [];
  42203. for (var name in this._ranges) {
  42204. var source = this._ranges[name];
  42205. if (!source) {
  42206. continue;
  42207. }
  42208. var range = {};
  42209. range.name = name;
  42210. range.from = source.from;
  42211. range.to = source.to;
  42212. serializationObject.ranges.push(range);
  42213. }
  42214. return serializationObject;
  42215. };
  42216. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  42217. get: function () {
  42218. return Animation._ANIMATIONTYPE_FLOAT;
  42219. },
  42220. enumerable: true,
  42221. configurable: true
  42222. });
  42223. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  42224. get: function () {
  42225. return Animation._ANIMATIONTYPE_VECTOR3;
  42226. },
  42227. enumerable: true,
  42228. configurable: true
  42229. });
  42230. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  42231. get: function () {
  42232. return Animation._ANIMATIONTYPE_VECTOR2;
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  42238. get: function () {
  42239. return Animation._ANIMATIONTYPE_SIZE;
  42240. },
  42241. enumerable: true,
  42242. configurable: true
  42243. });
  42244. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  42245. get: function () {
  42246. return Animation._ANIMATIONTYPE_QUATERNION;
  42247. },
  42248. enumerable: true,
  42249. configurable: true
  42250. });
  42251. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  42252. get: function () {
  42253. return Animation._ANIMATIONTYPE_MATRIX;
  42254. },
  42255. enumerable: true,
  42256. configurable: true
  42257. });
  42258. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  42259. get: function () {
  42260. return Animation._ANIMATIONTYPE_COLOR3;
  42261. },
  42262. enumerable: true,
  42263. configurable: true
  42264. });
  42265. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  42266. get: function () {
  42267. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  42268. },
  42269. enumerable: true,
  42270. configurable: true
  42271. });
  42272. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  42273. get: function () {
  42274. return Animation._ANIMATIONLOOPMODE_CYCLE;
  42275. },
  42276. enumerable: true,
  42277. configurable: true
  42278. });
  42279. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  42280. get: function () {
  42281. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  42282. },
  42283. enumerable: true,
  42284. configurable: true
  42285. });
  42286. Animation.Parse = function (parsedAnimation) {
  42287. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  42288. var dataType = parsedAnimation.dataType;
  42289. var keys = [];
  42290. var data;
  42291. var index;
  42292. if (parsedAnimation.enableBlending) {
  42293. animation.enableBlending = parsedAnimation.enableBlending;
  42294. }
  42295. if (parsedAnimation.blendingSpeed) {
  42296. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  42297. }
  42298. for (index = 0; index < parsedAnimation.keys.length; index++) {
  42299. var key = parsedAnimation.keys[index];
  42300. var inTangent;
  42301. var outTangent;
  42302. switch (dataType) {
  42303. case Animation.ANIMATIONTYPE_FLOAT:
  42304. data = key.values[0];
  42305. if (key.values.length >= 1) {
  42306. inTangent = key.values[1];
  42307. }
  42308. if (key.values.length >= 2) {
  42309. outTangent = key.values[2];
  42310. }
  42311. break;
  42312. case Animation.ANIMATIONTYPE_QUATERNION:
  42313. data = BABYLON.Quaternion.FromArray(key.values);
  42314. if (key.values.length >= 8) {
  42315. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  42316. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  42317. inTangent = _inTangent;
  42318. }
  42319. }
  42320. if (key.values.length >= 12) {
  42321. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  42322. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  42323. outTangent = _outTangent;
  42324. }
  42325. }
  42326. break;
  42327. case Animation.ANIMATIONTYPE_MATRIX:
  42328. data = BABYLON.Matrix.FromArray(key.values);
  42329. break;
  42330. case Animation.ANIMATIONTYPE_COLOR3:
  42331. data = BABYLON.Color3.FromArray(key.values);
  42332. break;
  42333. case Animation.ANIMATIONTYPE_VECTOR3:
  42334. default:
  42335. data = BABYLON.Vector3.FromArray(key.values);
  42336. break;
  42337. }
  42338. var keyData = {};
  42339. keyData.frame = key.frame;
  42340. keyData.value = data;
  42341. if (inTangent != undefined) {
  42342. keyData.inTangent = inTangent;
  42343. }
  42344. if (outTangent != undefined) {
  42345. keyData.outTangent = outTangent;
  42346. }
  42347. keys.push(keyData);
  42348. }
  42349. animation.setKeys(keys);
  42350. if (parsedAnimation.ranges) {
  42351. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  42352. data = parsedAnimation.ranges[index];
  42353. animation.createRange(data.name, data.from, data.to);
  42354. }
  42355. }
  42356. return animation;
  42357. };
  42358. Animation.AppendSerializedAnimations = function (source, destination) {
  42359. if (source.animations) {
  42360. destination.animations = [];
  42361. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  42362. var animation = source.animations[animationIndex];
  42363. destination.animations.push(animation.serialize());
  42364. }
  42365. }
  42366. };
  42367. Animation.AllowMatricesInterpolation = false;
  42368. // Statics
  42369. Animation._ANIMATIONTYPE_FLOAT = 0;
  42370. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  42371. Animation._ANIMATIONTYPE_QUATERNION = 2;
  42372. Animation._ANIMATIONTYPE_MATRIX = 3;
  42373. Animation._ANIMATIONTYPE_COLOR3 = 4;
  42374. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  42375. Animation._ANIMATIONTYPE_SIZE = 6;
  42376. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  42377. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  42378. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  42379. return Animation;
  42380. }());
  42381. BABYLON.Animation = Animation;
  42382. })(BABYLON || (BABYLON = {}));
  42383. //# sourceMappingURL=babylon.animation.js.map
  42384. var BABYLON;
  42385. (function (BABYLON) {
  42386. /**
  42387. * This class defines the direct association between an animation and a target
  42388. */
  42389. var TargetedAnimation = /** @class */ (function () {
  42390. function TargetedAnimation() {
  42391. }
  42392. return TargetedAnimation;
  42393. }());
  42394. BABYLON.TargetedAnimation = TargetedAnimation;
  42395. /**
  42396. * Use this class to create coordinated animations on multiple targets
  42397. */
  42398. var AnimationGroup = /** @class */ (function () {
  42399. function AnimationGroup(name, scene) {
  42400. if (scene === void 0) { scene = null; }
  42401. this.name = name;
  42402. this._targetedAnimations = new Array();
  42403. this._animatables = new Array();
  42404. this._from = Number.MAX_VALUE;
  42405. this._to = -Number.MAX_VALUE;
  42406. this._speedRatio = 1;
  42407. this.onAnimationEndObservable = new BABYLON.Observable();
  42408. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  42409. this._scene.animationGroups.push(this);
  42410. }
  42411. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  42412. /**
  42413. * Define if the animations are started
  42414. */
  42415. get: function () {
  42416. return this._isStarted;
  42417. },
  42418. enumerable: true,
  42419. configurable: true
  42420. });
  42421. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  42422. /**
  42423. * Gets or sets the speed ratio to use for all animations
  42424. */
  42425. get: function () {
  42426. return this._speedRatio;
  42427. },
  42428. /**
  42429. * Gets or sets the speed ratio to use for all animations
  42430. */
  42431. set: function (value) {
  42432. if (this._speedRatio === value) {
  42433. return;
  42434. }
  42435. this._speedRatio = value;
  42436. for (var index = 0; index < this._animatables.length; index++) {
  42437. var animatable = this._animatables[index];
  42438. animatable.speedRatio = this._speedRatio;
  42439. }
  42440. },
  42441. enumerable: true,
  42442. configurable: true
  42443. });
  42444. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  42445. /**
  42446. * Gets the targeted animations for this animation group
  42447. */
  42448. get: function () {
  42449. return this._targetedAnimations;
  42450. },
  42451. enumerable: true,
  42452. configurable: true
  42453. });
  42454. /**
  42455. * Add an animation (with its target) in the group
  42456. * @param animation defines the animation we want to add
  42457. * @param target defines the target of the animation
  42458. * @returns the {BABYLON.TargetedAnimation} object
  42459. */
  42460. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  42461. var targetedAnimation = {
  42462. animation: animation,
  42463. target: target
  42464. };
  42465. var keys = animation.getKeys();
  42466. if (this._from > keys[0].frame) {
  42467. this._from = keys[0].frame;
  42468. }
  42469. if (this._to < keys[keys.length - 1].frame) {
  42470. this._to = keys[keys.length - 1].frame;
  42471. }
  42472. this._targetedAnimations.push(targetedAnimation);
  42473. return targetedAnimation;
  42474. };
  42475. /**
  42476. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  42477. * It can add constant keys at begin or end
  42478. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  42479. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  42480. */
  42481. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  42482. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  42483. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  42484. beginFrame = Math.max(beginFrame, this._from);
  42485. endFrame = Math.min(endFrame, this._to);
  42486. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42487. var targetedAnimation = this._targetedAnimations[index];
  42488. var keys = targetedAnimation.animation.getKeys();
  42489. var startKey = keys[0];
  42490. var endKey = keys[keys.length - 1];
  42491. if (startKey.frame > beginFrame) {
  42492. var newKey = {
  42493. frame: beginFrame,
  42494. value: startKey.value,
  42495. inTangent: startKey.inTangent,
  42496. outTangent: startKey.outTangent,
  42497. interpolation: startKey.interpolation
  42498. };
  42499. keys.splice(0, 0, newKey);
  42500. }
  42501. if (endKey.frame < endFrame) {
  42502. var newKey = {
  42503. frame: endFrame,
  42504. value: endKey.value,
  42505. inTangent: endKey.outTangent,
  42506. outTangent: endKey.outTangent,
  42507. interpolation: endKey.interpolation
  42508. };
  42509. keys.push(newKey);
  42510. }
  42511. }
  42512. return this;
  42513. };
  42514. /**
  42515. * Start all animations on given targets
  42516. * @param loop defines if animations must loop
  42517. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42518. */
  42519. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42520. var _this = this;
  42521. if (loop === void 0) { loop = false; }
  42522. if (speedRatio === void 0) { speedRatio = 1; }
  42523. if (this._isStarted || this._targetedAnimations.length === 0) {
  42524. return this;
  42525. }
  42526. var _loop_1 = function () {
  42527. var targetedAnimation = this_1._targetedAnimations[index];
  42528. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42529. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42530. }));
  42531. };
  42532. var this_1 = this;
  42533. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42534. _loop_1();
  42535. }
  42536. this._speedRatio = speedRatio;
  42537. this._isStarted = true;
  42538. return this;
  42539. };
  42540. /**
  42541. * Pause all animations
  42542. */
  42543. AnimationGroup.prototype.pause = function () {
  42544. if (!this._isStarted) {
  42545. return this;
  42546. }
  42547. for (var index = 0; index < this._animatables.length; index++) {
  42548. var animatable = this._animatables[index];
  42549. animatable.pause();
  42550. }
  42551. return this;
  42552. };
  42553. /**
  42554. * Play all animations to initial state
  42555. * This function will start() the animations if they were not started or will restart() them if they were paused
  42556. * @param loop defines if animations must loop
  42557. */
  42558. AnimationGroup.prototype.play = function (loop) {
  42559. if (this.isStarted) {
  42560. if (loop !== undefined) {
  42561. for (var index = 0; index < this._animatables.length; index++) {
  42562. var animatable = this._animatables[index];
  42563. animatable.loopAnimation = loop;
  42564. }
  42565. }
  42566. this.restart();
  42567. }
  42568. else {
  42569. this.start(loop, this._speedRatio);
  42570. }
  42571. return this;
  42572. };
  42573. /**
  42574. * Reset all animations to initial state
  42575. */
  42576. AnimationGroup.prototype.reset = function () {
  42577. if (!this._isStarted) {
  42578. return this;
  42579. }
  42580. for (var index = 0; index < this._animatables.length; index++) {
  42581. var animatable = this._animatables[index];
  42582. animatable.reset();
  42583. }
  42584. return this;
  42585. };
  42586. /**
  42587. * Restart animations from key 0
  42588. */
  42589. AnimationGroup.prototype.restart = function () {
  42590. if (!this._isStarted) {
  42591. return this;
  42592. }
  42593. for (var index = 0; index < this._animatables.length; index++) {
  42594. var animatable = this._animatables[index];
  42595. animatable.restart();
  42596. }
  42597. return this;
  42598. };
  42599. /**
  42600. * Stop all animations
  42601. */
  42602. AnimationGroup.prototype.stop = function () {
  42603. if (!this._isStarted) {
  42604. return this;
  42605. }
  42606. for (var index = 0; index < this._animatables.length; index++) {
  42607. var animatable = this._animatables[index];
  42608. animatable.stop();
  42609. }
  42610. this._isStarted = false;
  42611. return this;
  42612. };
  42613. /**
  42614. * Dispose all associated resources
  42615. */
  42616. AnimationGroup.prototype.dispose = function () {
  42617. this._targetedAnimations = [];
  42618. this._animatables = [];
  42619. var index = this._scene.animationGroups.indexOf(this);
  42620. if (index > -1) {
  42621. this._scene.animationGroups.splice(index, 1);
  42622. }
  42623. };
  42624. return AnimationGroup;
  42625. }());
  42626. BABYLON.AnimationGroup = AnimationGroup;
  42627. })(BABYLON || (BABYLON = {}));
  42628. //# sourceMappingURL=babylon.animationGroup.js.map
  42629. var BABYLON;
  42630. (function (BABYLON) {
  42631. var RuntimeAnimation = /** @class */ (function () {
  42632. function RuntimeAnimation(target, animation) {
  42633. this._offsetsCache = {};
  42634. this._highLimitsCache = {};
  42635. this._stopped = false;
  42636. this._blendingFactor = 0;
  42637. this._ratioOffset = 0;
  42638. this._animation = animation;
  42639. this._target = target;
  42640. animation._runtimeAnimations.push(this);
  42641. }
  42642. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42643. get: function () {
  42644. return this._animation;
  42645. },
  42646. enumerable: true,
  42647. configurable: true
  42648. });
  42649. RuntimeAnimation.prototype.reset = function () {
  42650. this._offsetsCache = {};
  42651. this._highLimitsCache = {};
  42652. this.currentFrame = 0;
  42653. this._blendingFactor = 0;
  42654. this._originalBlendValue = null;
  42655. };
  42656. RuntimeAnimation.prototype.isStopped = function () {
  42657. return this._stopped;
  42658. };
  42659. RuntimeAnimation.prototype.dispose = function () {
  42660. var index = this._animation.runtimeAnimations.indexOf(this);
  42661. if (index > -1) {
  42662. this._animation.runtimeAnimations.splice(index, 1);
  42663. }
  42664. };
  42665. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42666. if (typeof value === "function") {
  42667. return value();
  42668. }
  42669. return value;
  42670. };
  42671. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42672. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42673. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42674. }
  42675. this.currentFrame = currentFrame;
  42676. var keys = this._animation.getKeys();
  42677. // Try to get a hash to find the right key
  42678. 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));
  42679. if (keys[startKeyIndex].frame >= currentFrame) {
  42680. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42681. startKeyIndex--;
  42682. }
  42683. }
  42684. for (var key = startKeyIndex; key < keys.length; key++) {
  42685. var endKey = keys[key + 1];
  42686. if (endKey.frame >= currentFrame) {
  42687. var startKey = keys[key];
  42688. var startValue = this._getKeyValue(startKey.value);
  42689. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  42690. return startValue;
  42691. }
  42692. var endValue = this._getKeyValue(endKey.value);
  42693. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42694. var frameDelta = endKey.frame - startKey.frame;
  42695. // gradient : percent of currentFrame between the frame inf and the frame sup
  42696. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42697. // check for easingFunction and correction of gradient
  42698. var easingFunction = this._animation.getEasingFunction();
  42699. if (easingFunction != null) {
  42700. gradient = easingFunction.ease(gradient);
  42701. }
  42702. switch (this._animation.dataType) {
  42703. // Float
  42704. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42705. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42706. switch (loopMode) {
  42707. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42708. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42709. return floatValue;
  42710. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42711. return offsetValue * repeatCount + floatValue;
  42712. }
  42713. break;
  42714. // Quaternion
  42715. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42716. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42717. switch (loopMode) {
  42718. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42719. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42720. return quatValue;
  42721. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42722. return quatValue.add(offsetValue.scale(repeatCount));
  42723. }
  42724. return quatValue;
  42725. // Vector3
  42726. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42727. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42728. switch (loopMode) {
  42729. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42730. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42731. return vec3Value;
  42732. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42733. return vec3Value.add(offsetValue.scale(repeatCount));
  42734. }
  42735. // Vector2
  42736. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42737. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42738. switch (loopMode) {
  42739. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42740. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42741. return vec2Value;
  42742. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42743. return vec2Value.add(offsetValue.scale(repeatCount));
  42744. }
  42745. // Size
  42746. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42747. switch (loopMode) {
  42748. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42749. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42750. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42751. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42752. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42753. }
  42754. // Color3
  42755. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42756. switch (loopMode) {
  42757. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42758. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42759. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42760. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42761. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42762. }
  42763. // Matrix
  42764. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42765. switch (loopMode) {
  42766. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42767. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42768. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42769. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42770. }
  42771. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42772. return startValue;
  42773. }
  42774. default:
  42775. break;
  42776. }
  42777. break;
  42778. }
  42779. }
  42780. return this._getKeyValue(keys[keys.length - 1].value);
  42781. };
  42782. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42783. if (blend === void 0) { blend = false; }
  42784. // Set value
  42785. var path;
  42786. var destination;
  42787. var targetPropertyPath = this._animation.targetPropertyPath;
  42788. if (targetPropertyPath.length > 1) {
  42789. var property = this._target[targetPropertyPath[0]];
  42790. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42791. property = property[targetPropertyPath[index]];
  42792. }
  42793. path = targetPropertyPath[targetPropertyPath.length - 1];
  42794. destination = property;
  42795. }
  42796. else {
  42797. path = targetPropertyPath[0];
  42798. destination = this._target;
  42799. }
  42800. // Blending
  42801. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42802. if (!this._originalBlendValue) {
  42803. if (destination[path].clone) {
  42804. this._originalBlendValue = destination[path].clone();
  42805. }
  42806. else {
  42807. this._originalBlendValue = destination[path];
  42808. }
  42809. }
  42810. if (this._originalBlendValue.prototype) {
  42811. if (this._originalBlendValue.prototype.Lerp) {
  42812. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42813. }
  42814. else {
  42815. destination[path] = currentValue;
  42816. }
  42817. }
  42818. else if (this._originalBlendValue.m) {
  42819. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42820. }
  42821. else {
  42822. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42823. }
  42824. this._blendingFactor += this._animation.blendingSpeed;
  42825. }
  42826. else {
  42827. destination[path] = currentValue;
  42828. }
  42829. if (this._target.markAsDirty) {
  42830. this._target.markAsDirty(this._animation.targetProperty);
  42831. }
  42832. };
  42833. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42834. var keys = this._animation.getKeys();
  42835. if (frame < keys[0].frame) {
  42836. frame = keys[0].frame;
  42837. }
  42838. else if (frame > keys[keys.length - 1].frame) {
  42839. frame = keys[keys.length - 1].frame;
  42840. }
  42841. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42842. this.setValue(currentValue);
  42843. };
  42844. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42845. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42846. this._ratioOffset = this._previousRatio - newRatio;
  42847. };
  42848. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42849. if (blend === void 0) { blend = false; }
  42850. var targetPropertyPath = this._animation.targetPropertyPath;
  42851. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42852. this._stopped = true;
  42853. return false;
  42854. }
  42855. var returnValue = true;
  42856. var keys = this._animation.getKeys();
  42857. // Adding a start key at frame 0 if missing
  42858. if (keys[0].frame !== 0) {
  42859. var newKey = { frame: 0, value: keys[0].value };
  42860. keys.splice(0, 0, newKey);
  42861. }
  42862. // Check limits
  42863. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42864. from = keys[0].frame;
  42865. }
  42866. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42867. to = keys[keys.length - 1].frame;
  42868. }
  42869. //to and from cannot be the same key
  42870. if (from === to) {
  42871. if (from > keys[0].frame) {
  42872. from--;
  42873. }
  42874. else if (to < keys[keys.length - 1].frame) {
  42875. to++;
  42876. }
  42877. }
  42878. // Compute ratio
  42879. var range = to - from;
  42880. var offsetValue;
  42881. // ratio represents the frame delta between from and to
  42882. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42883. var highLimitValue = 0;
  42884. this._previousDelay = delay;
  42885. this._previousRatio = ratio;
  42886. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42887. returnValue = false;
  42888. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42889. }
  42890. else {
  42891. // Get max value if required
  42892. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42893. var keyOffset = to.toString() + from.toString();
  42894. if (!this._offsetsCache[keyOffset]) {
  42895. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42896. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42897. switch (this._animation.dataType) {
  42898. // Float
  42899. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42900. this._offsetsCache[keyOffset] = toValue - fromValue;
  42901. break;
  42902. // Quaternion
  42903. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42904. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42905. break;
  42906. // Vector3
  42907. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42908. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42909. // Vector2
  42910. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42911. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42912. // Size
  42913. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42914. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42915. // Color3
  42916. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42917. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42918. default:
  42919. break;
  42920. }
  42921. this._highLimitsCache[keyOffset] = toValue;
  42922. }
  42923. highLimitValue = this._highLimitsCache[keyOffset];
  42924. offsetValue = this._offsetsCache[keyOffset];
  42925. }
  42926. }
  42927. if (offsetValue === undefined) {
  42928. switch (this._animation.dataType) {
  42929. // Float
  42930. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42931. offsetValue = 0;
  42932. break;
  42933. // Quaternion
  42934. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42935. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42936. break;
  42937. // Vector3
  42938. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42939. offsetValue = BABYLON.Vector3.Zero();
  42940. break;
  42941. // Vector2
  42942. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42943. offsetValue = BABYLON.Vector2.Zero();
  42944. break;
  42945. // Size
  42946. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42947. offsetValue = BABYLON.Size.Zero();
  42948. break;
  42949. // Color3
  42950. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42951. offsetValue = BABYLON.Color3.Black();
  42952. }
  42953. }
  42954. // Compute value
  42955. var repeatCount = (ratio / range) >> 0;
  42956. var currentFrame = returnValue ? from + ratio % range : to;
  42957. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42958. // Set value
  42959. this.setValue(currentValue);
  42960. // Check events
  42961. var events = this._animation.getEvents();
  42962. for (var index = 0; index < events.length; index++) {
  42963. // Make sure current frame has passed event frame and that event frame is within the current range
  42964. // Also, handle both forward and reverse animations
  42965. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42966. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42967. var event = events[index];
  42968. if (!event.isDone) {
  42969. // If event should be done only once, remove it.
  42970. if (event.onlyOnce) {
  42971. events.splice(index, 1);
  42972. index--;
  42973. }
  42974. event.isDone = true;
  42975. event.action();
  42976. } // Don't do anything if the event has already be done.
  42977. }
  42978. else if (events[index].isDone && !events[index].onlyOnce) {
  42979. // reset event, the animation is looping
  42980. events[index].isDone = false;
  42981. }
  42982. }
  42983. if (!returnValue) {
  42984. this._stopped = true;
  42985. }
  42986. return returnValue;
  42987. };
  42988. return RuntimeAnimation;
  42989. }());
  42990. BABYLON.RuntimeAnimation = RuntimeAnimation;
  42991. })(BABYLON || (BABYLON = {}));
  42992. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  42993. var BABYLON;
  42994. (function (BABYLON) {
  42995. var Animatable = /** @class */ (function () {
  42996. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  42997. if (fromFrame === void 0) { fromFrame = 0; }
  42998. if (toFrame === void 0) { toFrame = 100; }
  42999. if (loopAnimation === void 0) { loopAnimation = false; }
  43000. if (speedRatio === void 0) { speedRatio = 1.0; }
  43001. this.target = target;
  43002. this.fromFrame = fromFrame;
  43003. this.toFrame = toFrame;
  43004. this.loopAnimation = loopAnimation;
  43005. this.onAnimationEnd = onAnimationEnd;
  43006. this._localDelayOffset = null;
  43007. this._pausedDelay = null;
  43008. this._runtimeAnimations = new Array();
  43009. this._paused = false;
  43010. this._speedRatio = 1;
  43011. this.animationStarted = false;
  43012. if (animations) {
  43013. this.appendAnimations(target, animations);
  43014. }
  43015. this._speedRatio = speedRatio;
  43016. this._scene = scene;
  43017. scene._activeAnimatables.push(this);
  43018. }
  43019. Object.defineProperty(Animatable.prototype, "speedRatio", {
  43020. get: function () {
  43021. return this._speedRatio;
  43022. },
  43023. set: function (value) {
  43024. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  43025. var animation = this._runtimeAnimations[index];
  43026. animation._prepareForSpeedRatioChange(value);
  43027. }
  43028. this._speedRatio = value;
  43029. },
  43030. enumerable: true,
  43031. configurable: true
  43032. });
  43033. // Methods
  43034. Animatable.prototype.getAnimations = function () {
  43035. return this._runtimeAnimations;
  43036. };
  43037. Animatable.prototype.appendAnimations = function (target, animations) {
  43038. for (var index = 0; index < animations.length; index++) {
  43039. var animation = animations[index];
  43040. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  43041. }
  43042. };
  43043. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  43044. var runtimeAnimations = this._runtimeAnimations;
  43045. for (var index = 0; index < runtimeAnimations.length; index++) {
  43046. if (runtimeAnimations[index].animation.targetProperty === property) {
  43047. return runtimeAnimations[index].animation;
  43048. }
  43049. }
  43050. return null;
  43051. };
  43052. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  43053. var runtimeAnimations = this._runtimeAnimations;
  43054. for (var index = 0; index < runtimeAnimations.length; index++) {
  43055. if (runtimeAnimations[index].animation.targetProperty === property) {
  43056. return runtimeAnimations[index];
  43057. }
  43058. }
  43059. return null;
  43060. };
  43061. Animatable.prototype.reset = function () {
  43062. var runtimeAnimations = this._runtimeAnimations;
  43063. for (var index = 0; index < runtimeAnimations.length; index++) {
  43064. runtimeAnimations[index].reset();
  43065. }
  43066. // Reset to original value
  43067. for (index = 0; index < runtimeAnimations.length; index++) {
  43068. var animation = runtimeAnimations[index];
  43069. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  43070. }
  43071. this._localDelayOffset = null;
  43072. this._pausedDelay = null;
  43073. };
  43074. Animatable.prototype.enableBlending = function (blendingSpeed) {
  43075. var runtimeAnimations = this._runtimeAnimations;
  43076. for (var index = 0; index < runtimeAnimations.length; index++) {
  43077. runtimeAnimations[index].animation.enableBlending = true;
  43078. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  43079. }
  43080. };
  43081. Animatable.prototype.disableBlending = function () {
  43082. var runtimeAnimations = this._runtimeAnimations;
  43083. for (var index = 0; index < runtimeAnimations.length; index++) {
  43084. runtimeAnimations[index].animation.enableBlending = false;
  43085. }
  43086. };
  43087. Animatable.prototype.goToFrame = function (frame) {
  43088. var runtimeAnimations = this._runtimeAnimations;
  43089. if (runtimeAnimations[0]) {
  43090. var fps = runtimeAnimations[0].animation.framePerSecond;
  43091. var currentFrame = runtimeAnimations[0].currentFrame;
  43092. var adjustTime = frame - currentFrame;
  43093. var delay = adjustTime * 1000 / fps;
  43094. if (this._localDelayOffset === null) {
  43095. this._localDelayOffset = 0;
  43096. }
  43097. this._localDelayOffset -= delay;
  43098. }
  43099. for (var index = 0; index < runtimeAnimations.length; index++) {
  43100. runtimeAnimations[index].goToFrame(frame);
  43101. }
  43102. };
  43103. Animatable.prototype.pause = function () {
  43104. if (this._paused) {
  43105. return;
  43106. }
  43107. this._paused = true;
  43108. };
  43109. Animatable.prototype.restart = function () {
  43110. this._paused = false;
  43111. };
  43112. Animatable.prototype.stop = function (animationName) {
  43113. if (animationName) {
  43114. var idx = this._scene._activeAnimatables.indexOf(this);
  43115. if (idx > -1) {
  43116. var runtimeAnimations = this._runtimeAnimations;
  43117. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  43118. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  43119. continue;
  43120. }
  43121. runtimeAnimations[index].dispose();
  43122. runtimeAnimations.splice(index, 1);
  43123. }
  43124. if (runtimeAnimations.length == 0) {
  43125. this._scene._activeAnimatables.splice(idx, 1);
  43126. if (this.onAnimationEnd) {
  43127. this.onAnimationEnd();
  43128. }
  43129. }
  43130. }
  43131. }
  43132. else {
  43133. var index = this._scene._activeAnimatables.indexOf(this);
  43134. if (index > -1) {
  43135. this._scene._activeAnimatables.splice(index, 1);
  43136. var runtimeAnimations = this._runtimeAnimations;
  43137. for (var index = 0; index < runtimeAnimations.length; index++) {
  43138. runtimeAnimations[index].dispose();
  43139. }
  43140. if (this.onAnimationEnd) {
  43141. this.onAnimationEnd();
  43142. }
  43143. }
  43144. }
  43145. };
  43146. Animatable.prototype._animate = function (delay) {
  43147. if (this._paused) {
  43148. this.animationStarted = false;
  43149. if (this._pausedDelay === null) {
  43150. this._pausedDelay = delay;
  43151. }
  43152. return true;
  43153. }
  43154. if (this._localDelayOffset === null) {
  43155. this._localDelayOffset = delay;
  43156. }
  43157. else if (this._pausedDelay !== null) {
  43158. this._localDelayOffset += delay - this._pausedDelay;
  43159. this._pausedDelay = null;
  43160. }
  43161. // Animating
  43162. var running = false;
  43163. var runtimeAnimations = this._runtimeAnimations;
  43164. var index;
  43165. for (index = 0; index < runtimeAnimations.length; index++) {
  43166. var animation = runtimeAnimations[index];
  43167. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  43168. running = running || isRunning;
  43169. }
  43170. this.animationStarted = running;
  43171. if (!running) {
  43172. // Remove from active animatables
  43173. index = this._scene._activeAnimatables.indexOf(this);
  43174. this._scene._activeAnimatables.splice(index, 1);
  43175. // Dispose all runtime animations
  43176. for (index = 0; index < runtimeAnimations.length; index++) {
  43177. runtimeAnimations[index].dispose();
  43178. }
  43179. }
  43180. if (!running && this.onAnimationEnd) {
  43181. this.onAnimationEnd();
  43182. this.onAnimationEnd = null;
  43183. }
  43184. return running;
  43185. };
  43186. return Animatable;
  43187. }());
  43188. BABYLON.Animatable = Animatable;
  43189. })(BABYLON || (BABYLON = {}));
  43190. //# sourceMappingURL=babylon.animatable.js.map
  43191. var BABYLON;
  43192. (function (BABYLON) {
  43193. var EasingFunction = /** @class */ (function () {
  43194. function EasingFunction() {
  43195. // Properties
  43196. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  43197. }
  43198. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  43199. get: function () {
  43200. return EasingFunction._EASINGMODE_EASEIN;
  43201. },
  43202. enumerable: true,
  43203. configurable: true
  43204. });
  43205. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  43206. get: function () {
  43207. return EasingFunction._EASINGMODE_EASEOUT;
  43208. },
  43209. enumerable: true,
  43210. configurable: true
  43211. });
  43212. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  43213. get: function () {
  43214. return EasingFunction._EASINGMODE_EASEINOUT;
  43215. },
  43216. enumerable: true,
  43217. configurable: true
  43218. });
  43219. EasingFunction.prototype.setEasingMode = function (easingMode) {
  43220. var n = Math.min(Math.max(easingMode, 0), 2);
  43221. this._easingMode = n;
  43222. };
  43223. EasingFunction.prototype.getEasingMode = function () {
  43224. return this._easingMode;
  43225. };
  43226. EasingFunction.prototype.easeInCore = function (gradient) {
  43227. throw new Error('You must implement this method');
  43228. };
  43229. EasingFunction.prototype.ease = function (gradient) {
  43230. switch (this._easingMode) {
  43231. case EasingFunction.EASINGMODE_EASEIN:
  43232. return this.easeInCore(gradient);
  43233. case EasingFunction.EASINGMODE_EASEOUT:
  43234. return (1 - this.easeInCore(1 - gradient));
  43235. }
  43236. if (gradient >= 0.5) {
  43237. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  43238. }
  43239. return (this.easeInCore(gradient * 2) * 0.5);
  43240. };
  43241. //Statics
  43242. EasingFunction._EASINGMODE_EASEIN = 0;
  43243. EasingFunction._EASINGMODE_EASEOUT = 1;
  43244. EasingFunction._EASINGMODE_EASEINOUT = 2;
  43245. return EasingFunction;
  43246. }());
  43247. BABYLON.EasingFunction = EasingFunction;
  43248. var CircleEase = /** @class */ (function (_super) {
  43249. __extends(CircleEase, _super);
  43250. function CircleEase() {
  43251. return _super !== null && _super.apply(this, arguments) || this;
  43252. }
  43253. CircleEase.prototype.easeInCore = function (gradient) {
  43254. gradient = Math.max(0, Math.min(1, gradient));
  43255. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  43256. };
  43257. return CircleEase;
  43258. }(EasingFunction));
  43259. BABYLON.CircleEase = CircleEase;
  43260. var BackEase = /** @class */ (function (_super) {
  43261. __extends(BackEase, _super);
  43262. function BackEase(amplitude) {
  43263. if (amplitude === void 0) { amplitude = 1; }
  43264. var _this = _super.call(this) || this;
  43265. _this.amplitude = amplitude;
  43266. return _this;
  43267. }
  43268. BackEase.prototype.easeInCore = function (gradient) {
  43269. var num = Math.max(0, this.amplitude);
  43270. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  43271. };
  43272. return BackEase;
  43273. }(EasingFunction));
  43274. BABYLON.BackEase = BackEase;
  43275. var BounceEase = /** @class */ (function (_super) {
  43276. __extends(BounceEase, _super);
  43277. function BounceEase(bounces, bounciness) {
  43278. if (bounces === void 0) { bounces = 3; }
  43279. if (bounciness === void 0) { bounciness = 2; }
  43280. var _this = _super.call(this) || this;
  43281. _this.bounces = bounces;
  43282. _this.bounciness = bounciness;
  43283. return _this;
  43284. }
  43285. BounceEase.prototype.easeInCore = function (gradient) {
  43286. var y = Math.max(0.0, this.bounces);
  43287. var bounciness = this.bounciness;
  43288. if (bounciness <= 1.0) {
  43289. bounciness = 1.001;
  43290. }
  43291. var num9 = Math.pow(bounciness, y);
  43292. var num5 = 1.0 - bounciness;
  43293. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  43294. var num15 = gradient * num4;
  43295. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  43296. var num3 = Math.floor(num65);
  43297. var num13 = num3 + 1.0;
  43298. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  43299. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  43300. var num7 = (num8 + num12) * 0.5;
  43301. var num6 = gradient - num7;
  43302. var num2 = num7 - num8;
  43303. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  43304. };
  43305. return BounceEase;
  43306. }(EasingFunction));
  43307. BABYLON.BounceEase = BounceEase;
  43308. var CubicEase = /** @class */ (function (_super) {
  43309. __extends(CubicEase, _super);
  43310. function CubicEase() {
  43311. return _super !== null && _super.apply(this, arguments) || this;
  43312. }
  43313. CubicEase.prototype.easeInCore = function (gradient) {
  43314. return (gradient * gradient * gradient);
  43315. };
  43316. return CubicEase;
  43317. }(EasingFunction));
  43318. BABYLON.CubicEase = CubicEase;
  43319. var ElasticEase = /** @class */ (function (_super) {
  43320. __extends(ElasticEase, _super);
  43321. function ElasticEase(oscillations, springiness) {
  43322. if (oscillations === void 0) { oscillations = 3; }
  43323. if (springiness === void 0) { springiness = 3; }
  43324. var _this = _super.call(this) || this;
  43325. _this.oscillations = oscillations;
  43326. _this.springiness = springiness;
  43327. return _this;
  43328. }
  43329. ElasticEase.prototype.easeInCore = function (gradient) {
  43330. var num2;
  43331. var num3 = Math.max(0.0, this.oscillations);
  43332. var num = Math.max(0.0, this.springiness);
  43333. if (num == 0) {
  43334. num2 = gradient;
  43335. }
  43336. else {
  43337. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  43338. }
  43339. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  43340. };
  43341. return ElasticEase;
  43342. }(EasingFunction));
  43343. BABYLON.ElasticEase = ElasticEase;
  43344. var ExponentialEase = /** @class */ (function (_super) {
  43345. __extends(ExponentialEase, _super);
  43346. function ExponentialEase(exponent) {
  43347. if (exponent === void 0) { exponent = 2; }
  43348. var _this = _super.call(this) || this;
  43349. _this.exponent = exponent;
  43350. return _this;
  43351. }
  43352. ExponentialEase.prototype.easeInCore = function (gradient) {
  43353. if (this.exponent <= 0) {
  43354. return gradient;
  43355. }
  43356. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  43357. };
  43358. return ExponentialEase;
  43359. }(EasingFunction));
  43360. BABYLON.ExponentialEase = ExponentialEase;
  43361. var PowerEase = /** @class */ (function (_super) {
  43362. __extends(PowerEase, _super);
  43363. function PowerEase(power) {
  43364. if (power === void 0) { power = 2; }
  43365. var _this = _super.call(this) || this;
  43366. _this.power = power;
  43367. return _this;
  43368. }
  43369. PowerEase.prototype.easeInCore = function (gradient) {
  43370. var y = Math.max(0.0, this.power);
  43371. return Math.pow(gradient, y);
  43372. };
  43373. return PowerEase;
  43374. }(EasingFunction));
  43375. BABYLON.PowerEase = PowerEase;
  43376. var QuadraticEase = /** @class */ (function (_super) {
  43377. __extends(QuadraticEase, _super);
  43378. function QuadraticEase() {
  43379. return _super !== null && _super.apply(this, arguments) || this;
  43380. }
  43381. QuadraticEase.prototype.easeInCore = function (gradient) {
  43382. return (gradient * gradient);
  43383. };
  43384. return QuadraticEase;
  43385. }(EasingFunction));
  43386. BABYLON.QuadraticEase = QuadraticEase;
  43387. var QuarticEase = /** @class */ (function (_super) {
  43388. __extends(QuarticEase, _super);
  43389. function QuarticEase() {
  43390. return _super !== null && _super.apply(this, arguments) || this;
  43391. }
  43392. QuarticEase.prototype.easeInCore = function (gradient) {
  43393. return (gradient * gradient * gradient * gradient);
  43394. };
  43395. return QuarticEase;
  43396. }(EasingFunction));
  43397. BABYLON.QuarticEase = QuarticEase;
  43398. var QuinticEase = /** @class */ (function (_super) {
  43399. __extends(QuinticEase, _super);
  43400. function QuinticEase() {
  43401. return _super !== null && _super.apply(this, arguments) || this;
  43402. }
  43403. QuinticEase.prototype.easeInCore = function (gradient) {
  43404. return (gradient * gradient * gradient * gradient * gradient);
  43405. };
  43406. return QuinticEase;
  43407. }(EasingFunction));
  43408. BABYLON.QuinticEase = QuinticEase;
  43409. var SineEase = /** @class */ (function (_super) {
  43410. __extends(SineEase, _super);
  43411. function SineEase() {
  43412. return _super !== null && _super.apply(this, arguments) || this;
  43413. }
  43414. SineEase.prototype.easeInCore = function (gradient) {
  43415. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  43416. };
  43417. return SineEase;
  43418. }(EasingFunction));
  43419. BABYLON.SineEase = SineEase;
  43420. var BezierCurveEase = /** @class */ (function (_super) {
  43421. __extends(BezierCurveEase, _super);
  43422. function BezierCurveEase(x1, y1, x2, y2) {
  43423. if (x1 === void 0) { x1 = 0; }
  43424. if (y1 === void 0) { y1 = 0; }
  43425. if (x2 === void 0) { x2 = 1; }
  43426. if (y2 === void 0) { y2 = 1; }
  43427. var _this = _super.call(this) || this;
  43428. _this.x1 = x1;
  43429. _this.y1 = y1;
  43430. _this.x2 = x2;
  43431. _this.y2 = y2;
  43432. return _this;
  43433. }
  43434. BezierCurveEase.prototype.easeInCore = function (gradient) {
  43435. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  43436. };
  43437. return BezierCurveEase;
  43438. }(EasingFunction));
  43439. BABYLON.BezierCurveEase = BezierCurveEase;
  43440. })(BABYLON || (BABYLON = {}));
  43441. //# sourceMappingURL=babylon.easing.js.map
  43442. var BABYLON;
  43443. (function (BABYLON) {
  43444. var Condition = /** @class */ (function () {
  43445. function Condition(actionManager) {
  43446. this._actionManager = actionManager;
  43447. }
  43448. Condition.prototype.isValid = function () {
  43449. return true;
  43450. };
  43451. Condition.prototype._getProperty = function (propertyPath) {
  43452. return this._actionManager._getProperty(propertyPath);
  43453. };
  43454. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  43455. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43456. };
  43457. Condition.prototype.serialize = function () {
  43458. };
  43459. Condition.prototype._serialize = function (serializedCondition) {
  43460. return {
  43461. type: 2,
  43462. children: [],
  43463. name: serializedCondition.name,
  43464. properties: serializedCondition.properties
  43465. };
  43466. };
  43467. return Condition;
  43468. }());
  43469. BABYLON.Condition = Condition;
  43470. var ValueCondition = /** @class */ (function (_super) {
  43471. __extends(ValueCondition, _super);
  43472. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  43473. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  43474. var _this = _super.call(this, actionManager) || this;
  43475. _this.propertyPath = propertyPath;
  43476. _this.value = value;
  43477. _this.operator = operator;
  43478. _this._target = target;
  43479. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  43480. _this._property = _this._getProperty(_this.propertyPath);
  43481. return _this;
  43482. }
  43483. Object.defineProperty(ValueCondition, "IsEqual", {
  43484. get: function () {
  43485. return ValueCondition._IsEqual;
  43486. },
  43487. enumerable: true,
  43488. configurable: true
  43489. });
  43490. Object.defineProperty(ValueCondition, "IsDifferent", {
  43491. get: function () {
  43492. return ValueCondition._IsDifferent;
  43493. },
  43494. enumerable: true,
  43495. configurable: true
  43496. });
  43497. Object.defineProperty(ValueCondition, "IsGreater", {
  43498. get: function () {
  43499. return ValueCondition._IsGreater;
  43500. },
  43501. enumerable: true,
  43502. configurable: true
  43503. });
  43504. Object.defineProperty(ValueCondition, "IsLesser", {
  43505. get: function () {
  43506. return ValueCondition._IsLesser;
  43507. },
  43508. enumerable: true,
  43509. configurable: true
  43510. });
  43511. // Methods
  43512. ValueCondition.prototype.isValid = function () {
  43513. switch (this.operator) {
  43514. case ValueCondition.IsGreater:
  43515. return this._effectiveTarget[this._property] > this.value;
  43516. case ValueCondition.IsLesser:
  43517. return this._effectiveTarget[this._property] < this.value;
  43518. case ValueCondition.IsEqual:
  43519. case ValueCondition.IsDifferent:
  43520. var check;
  43521. if (this.value.equals) {
  43522. check = this.value.equals(this._effectiveTarget[this._property]);
  43523. }
  43524. else {
  43525. check = this.value === this._effectiveTarget[this._property];
  43526. }
  43527. return this.operator === ValueCondition.IsEqual ? check : !check;
  43528. }
  43529. return false;
  43530. };
  43531. ValueCondition.prototype.serialize = function () {
  43532. return this._serialize({
  43533. name: "ValueCondition",
  43534. properties: [
  43535. BABYLON.Action._GetTargetProperty(this._target),
  43536. { name: "propertyPath", value: this.propertyPath },
  43537. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43538. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43539. ]
  43540. });
  43541. };
  43542. ValueCondition.GetOperatorName = function (operator) {
  43543. switch (operator) {
  43544. case ValueCondition._IsEqual: return "IsEqual";
  43545. case ValueCondition._IsDifferent: return "IsDifferent";
  43546. case ValueCondition._IsGreater: return "IsGreater";
  43547. case ValueCondition._IsLesser: return "IsLesser";
  43548. default: return "";
  43549. }
  43550. };
  43551. // Statics
  43552. ValueCondition._IsEqual = 0;
  43553. ValueCondition._IsDifferent = 1;
  43554. ValueCondition._IsGreater = 2;
  43555. ValueCondition._IsLesser = 3;
  43556. return ValueCondition;
  43557. }(Condition));
  43558. BABYLON.ValueCondition = ValueCondition;
  43559. var PredicateCondition = /** @class */ (function (_super) {
  43560. __extends(PredicateCondition, _super);
  43561. function PredicateCondition(actionManager, predicate) {
  43562. var _this = _super.call(this, actionManager) || this;
  43563. _this.predicate = predicate;
  43564. return _this;
  43565. }
  43566. PredicateCondition.prototype.isValid = function () {
  43567. return this.predicate();
  43568. };
  43569. return PredicateCondition;
  43570. }(Condition));
  43571. BABYLON.PredicateCondition = PredicateCondition;
  43572. var StateCondition = /** @class */ (function (_super) {
  43573. __extends(StateCondition, _super);
  43574. function StateCondition(actionManager, target, value) {
  43575. var _this = _super.call(this, actionManager) || this;
  43576. _this.value = value;
  43577. _this._target = target;
  43578. return _this;
  43579. }
  43580. // Methods
  43581. StateCondition.prototype.isValid = function () {
  43582. return this._target.state === this.value;
  43583. };
  43584. StateCondition.prototype.serialize = function () {
  43585. return this._serialize({
  43586. name: "StateCondition",
  43587. properties: [
  43588. BABYLON.Action._GetTargetProperty(this._target),
  43589. { name: "value", value: this.value }
  43590. ]
  43591. });
  43592. };
  43593. return StateCondition;
  43594. }(Condition));
  43595. BABYLON.StateCondition = StateCondition;
  43596. })(BABYLON || (BABYLON = {}));
  43597. //# sourceMappingURL=babylon.condition.js.map
  43598. var BABYLON;
  43599. (function (BABYLON) {
  43600. var Action = /** @class */ (function () {
  43601. function Action(triggerOptions, condition) {
  43602. this.triggerOptions = triggerOptions;
  43603. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43604. if (triggerOptions.parameter) {
  43605. this.trigger = triggerOptions.trigger;
  43606. this._triggerParameter = triggerOptions.parameter;
  43607. }
  43608. else {
  43609. this.trigger = triggerOptions;
  43610. }
  43611. this._nextActiveAction = this;
  43612. this._condition = condition;
  43613. }
  43614. // Methods
  43615. Action.prototype._prepare = function () {
  43616. };
  43617. Action.prototype.getTriggerParameter = function () {
  43618. return this._triggerParameter;
  43619. };
  43620. Action.prototype._executeCurrent = function (evt) {
  43621. if (this._nextActiveAction._condition) {
  43622. var condition = this._nextActiveAction._condition;
  43623. var currentRenderId = this._actionManager.getScene().getRenderId();
  43624. // We cache the current evaluation for the current frame
  43625. if (condition._evaluationId === currentRenderId) {
  43626. if (!condition._currentResult) {
  43627. return;
  43628. }
  43629. }
  43630. else {
  43631. condition._evaluationId = currentRenderId;
  43632. if (!condition.isValid()) {
  43633. condition._currentResult = false;
  43634. return;
  43635. }
  43636. condition._currentResult = true;
  43637. }
  43638. }
  43639. this.onBeforeExecuteObservable.notifyObservers(this);
  43640. this._nextActiveAction.execute(evt);
  43641. this.skipToNextActiveAction();
  43642. };
  43643. Action.prototype.execute = function (evt) {
  43644. };
  43645. Action.prototype.skipToNextActiveAction = function () {
  43646. if (this._nextActiveAction._child) {
  43647. if (!this._nextActiveAction._child._actionManager) {
  43648. this._nextActiveAction._child._actionManager = this._actionManager;
  43649. }
  43650. this._nextActiveAction = this._nextActiveAction._child;
  43651. }
  43652. else {
  43653. this._nextActiveAction = this;
  43654. }
  43655. };
  43656. Action.prototype.then = function (action) {
  43657. this._child = action;
  43658. action._actionManager = this._actionManager;
  43659. action._prepare();
  43660. return action;
  43661. };
  43662. Action.prototype._getProperty = function (propertyPath) {
  43663. return this._actionManager._getProperty(propertyPath);
  43664. };
  43665. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43666. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43667. };
  43668. Action.prototype.serialize = function (parent) {
  43669. };
  43670. // Called by BABYLON.Action objects in serialize(...). Internal use
  43671. Action.prototype._serialize = function (serializedAction, parent) {
  43672. var serializationObject = {
  43673. type: 1,
  43674. children: [],
  43675. name: serializedAction.name,
  43676. properties: serializedAction.properties || []
  43677. };
  43678. // Serialize child
  43679. if (this._child) {
  43680. this._child.serialize(serializationObject);
  43681. }
  43682. // Check if "this" has a condition
  43683. if (this._condition) {
  43684. var serializedCondition = this._condition.serialize();
  43685. serializedCondition.children.push(serializationObject);
  43686. if (parent) {
  43687. parent.children.push(serializedCondition);
  43688. }
  43689. return serializedCondition;
  43690. }
  43691. if (parent) {
  43692. parent.children.push(serializationObject);
  43693. }
  43694. return serializationObject;
  43695. };
  43696. Action._SerializeValueAsString = function (value) {
  43697. if (typeof value === "number") {
  43698. return value.toString();
  43699. }
  43700. if (typeof value === "boolean") {
  43701. return value ? "true" : "false";
  43702. }
  43703. if (value instanceof BABYLON.Vector2) {
  43704. return value.x + ", " + value.y;
  43705. }
  43706. if (value instanceof BABYLON.Vector3) {
  43707. return value.x + ", " + value.y + ", " + value.z;
  43708. }
  43709. if (value instanceof BABYLON.Color3) {
  43710. return value.r + ", " + value.g + ", " + value.b;
  43711. }
  43712. if (value instanceof BABYLON.Color4) {
  43713. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43714. }
  43715. return value; // string
  43716. };
  43717. Action._GetTargetProperty = function (target) {
  43718. return {
  43719. name: "target",
  43720. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43721. : target instanceof BABYLON.Light ? "LightProperties"
  43722. : target instanceof BABYLON.Camera ? "CameraProperties"
  43723. : "SceneProperties",
  43724. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43725. };
  43726. };
  43727. return Action;
  43728. }());
  43729. BABYLON.Action = Action;
  43730. })(BABYLON || (BABYLON = {}));
  43731. //# sourceMappingURL=babylon.action.js.map
  43732. var BABYLON;
  43733. (function (BABYLON) {
  43734. /**
  43735. * ActionEvent is the event beint sent when an action is triggered.
  43736. */
  43737. var ActionEvent = /** @class */ (function () {
  43738. /**
  43739. * @param source The mesh or sprite that triggered the action.
  43740. * @param pointerX The X mouse cursor position at the time of the event
  43741. * @param pointerY The Y mouse cursor position at the time of the event
  43742. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43743. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43744. */
  43745. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43746. this.source = source;
  43747. this.pointerX = pointerX;
  43748. this.pointerY = pointerY;
  43749. this.meshUnderPointer = meshUnderPointer;
  43750. this.sourceEvent = sourceEvent;
  43751. this.additionalData = additionalData;
  43752. }
  43753. /**
  43754. * Helper function to auto-create an ActionEvent from a source mesh.
  43755. * @param source The source mesh that triggered the event
  43756. * @param evt {Event} The original (browser) event
  43757. */
  43758. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43759. var scene = source.getScene();
  43760. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43761. };
  43762. /**
  43763. * Helper function to auto-create an ActionEvent from a source mesh.
  43764. * @param source The source sprite that triggered the event
  43765. * @param scene Scene associated with the sprite
  43766. * @param evt {Event} The original (browser) event
  43767. */
  43768. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43769. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43770. };
  43771. /**
  43772. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43773. * @param scene the scene where the event occurred
  43774. * @param evt {Event} The original (browser) event
  43775. */
  43776. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43777. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43778. };
  43779. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43780. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43781. };
  43782. return ActionEvent;
  43783. }());
  43784. BABYLON.ActionEvent = ActionEvent;
  43785. /**
  43786. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43787. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43788. */
  43789. var ActionManager = /** @class */ (function () {
  43790. function ActionManager(scene) {
  43791. // Members
  43792. this.actions = new Array();
  43793. this.hoverCursor = '';
  43794. this._scene = scene;
  43795. scene._actionManagers.push(this);
  43796. }
  43797. Object.defineProperty(ActionManager, "NothingTrigger", {
  43798. get: function () {
  43799. return ActionManager._NothingTrigger;
  43800. },
  43801. enumerable: true,
  43802. configurable: true
  43803. });
  43804. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43805. get: function () {
  43806. return ActionManager._OnPickTrigger;
  43807. },
  43808. enumerable: true,
  43809. configurable: true
  43810. });
  43811. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43812. get: function () {
  43813. return ActionManager._OnLeftPickTrigger;
  43814. },
  43815. enumerable: true,
  43816. configurable: true
  43817. });
  43818. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43819. get: function () {
  43820. return ActionManager._OnRightPickTrigger;
  43821. },
  43822. enumerable: true,
  43823. configurable: true
  43824. });
  43825. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43826. get: function () {
  43827. return ActionManager._OnCenterPickTrigger;
  43828. },
  43829. enumerable: true,
  43830. configurable: true
  43831. });
  43832. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43833. get: function () {
  43834. return ActionManager._OnPickDownTrigger;
  43835. },
  43836. enumerable: true,
  43837. configurable: true
  43838. });
  43839. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43840. get: function () {
  43841. return ActionManager._OnDoublePickTrigger;
  43842. },
  43843. enumerable: true,
  43844. configurable: true
  43845. });
  43846. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43847. get: function () {
  43848. return ActionManager._OnPickUpTrigger;
  43849. },
  43850. enumerable: true,
  43851. configurable: true
  43852. });
  43853. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43854. /// This trigger will only be raised if you also declared a OnPickDown
  43855. get: function () {
  43856. return ActionManager._OnPickOutTrigger;
  43857. },
  43858. enumerable: true,
  43859. configurable: true
  43860. });
  43861. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43862. get: function () {
  43863. return ActionManager._OnLongPressTrigger;
  43864. },
  43865. enumerable: true,
  43866. configurable: true
  43867. });
  43868. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43869. get: function () {
  43870. return ActionManager._OnPointerOverTrigger;
  43871. },
  43872. enumerable: true,
  43873. configurable: true
  43874. });
  43875. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43876. get: function () {
  43877. return ActionManager._OnPointerOutTrigger;
  43878. },
  43879. enumerable: true,
  43880. configurable: true
  43881. });
  43882. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43883. get: function () {
  43884. return ActionManager._OnEveryFrameTrigger;
  43885. },
  43886. enumerable: true,
  43887. configurable: true
  43888. });
  43889. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43890. get: function () {
  43891. return ActionManager._OnIntersectionEnterTrigger;
  43892. },
  43893. enumerable: true,
  43894. configurable: true
  43895. });
  43896. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43897. get: function () {
  43898. return ActionManager._OnIntersectionExitTrigger;
  43899. },
  43900. enumerable: true,
  43901. configurable: true
  43902. });
  43903. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43904. get: function () {
  43905. return ActionManager._OnKeyDownTrigger;
  43906. },
  43907. enumerable: true,
  43908. configurable: true
  43909. });
  43910. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43911. get: function () {
  43912. return ActionManager._OnKeyUpTrigger;
  43913. },
  43914. enumerable: true,
  43915. configurable: true
  43916. });
  43917. // Methods
  43918. ActionManager.prototype.dispose = function () {
  43919. var index = this._scene._actionManagers.indexOf(this);
  43920. for (var i = 0; i < this.actions.length; i++) {
  43921. var action = this.actions[i];
  43922. ActionManager.Triggers[action.trigger]--;
  43923. if (ActionManager.Triggers[action.trigger] === 0) {
  43924. delete ActionManager.Triggers[action.trigger];
  43925. }
  43926. }
  43927. if (index > -1) {
  43928. this._scene._actionManagers.splice(index, 1);
  43929. }
  43930. };
  43931. ActionManager.prototype.getScene = function () {
  43932. return this._scene;
  43933. };
  43934. /**
  43935. * Does this action manager handles actions of any of the given triggers
  43936. * @param {number[]} triggers - the triggers to be tested
  43937. * @return {boolean} whether one (or more) of the triggers is handeled
  43938. */
  43939. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43940. for (var index = 0; index < this.actions.length; index++) {
  43941. var action = this.actions[index];
  43942. if (triggers.indexOf(action.trigger) > -1) {
  43943. return true;
  43944. }
  43945. }
  43946. return false;
  43947. };
  43948. /**
  43949. * Does this action manager handles actions of a given trigger
  43950. * @param {number} trigger - the trigger to be tested
  43951. * @return {boolean} whether the trigger is handeled
  43952. */
  43953. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43954. for (var index = 0; index < this.actions.length; index++) {
  43955. var action = this.actions[index];
  43956. if (action.trigger === trigger) {
  43957. return true;
  43958. }
  43959. }
  43960. return false;
  43961. };
  43962. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43963. /**
  43964. * Does this action manager has pointer triggers
  43965. * @return {boolean} whether or not it has pointer triggers
  43966. */
  43967. get: function () {
  43968. for (var index = 0; index < this.actions.length; index++) {
  43969. var action = this.actions[index];
  43970. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43971. return true;
  43972. }
  43973. }
  43974. return false;
  43975. },
  43976. enumerable: true,
  43977. configurable: true
  43978. });
  43979. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43980. /**
  43981. * Does this action manager has pick triggers
  43982. * @return {boolean} whether or not it has pick triggers
  43983. */
  43984. get: function () {
  43985. for (var index = 0; index < this.actions.length; index++) {
  43986. var action = this.actions[index];
  43987. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43988. return true;
  43989. }
  43990. }
  43991. return false;
  43992. },
  43993. enumerable: true,
  43994. configurable: true
  43995. });
  43996. Object.defineProperty(ActionManager, "HasTriggers", {
  43997. /**
  43998. * Does exist one action manager with at least one trigger
  43999. * @return {boolean} whether or not it exists one action manager with one trigger
  44000. **/
  44001. get: function () {
  44002. for (var t in ActionManager.Triggers) {
  44003. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44004. return true;
  44005. }
  44006. }
  44007. return false;
  44008. },
  44009. enumerable: true,
  44010. configurable: true
  44011. });
  44012. Object.defineProperty(ActionManager, "HasPickTriggers", {
  44013. /**
  44014. * Does exist one action manager with at least one pick trigger
  44015. * @return {boolean} whether or not it exists one action manager with one pick trigger
  44016. **/
  44017. get: function () {
  44018. for (var t in ActionManager.Triggers) {
  44019. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44020. var t_int = parseInt(t);
  44021. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  44022. return true;
  44023. }
  44024. }
  44025. }
  44026. return false;
  44027. },
  44028. enumerable: true,
  44029. configurable: true
  44030. });
  44031. /**
  44032. * Does exist one action manager that handles actions of a given trigger
  44033. * @param {number} trigger - the trigger to be tested
  44034. * @return {boolean} whether the trigger is handeled by at least one action manager
  44035. **/
  44036. ActionManager.HasSpecificTrigger = function (trigger) {
  44037. for (var t in ActionManager.Triggers) {
  44038. if (ActionManager.Triggers.hasOwnProperty(t)) {
  44039. var t_int = parseInt(t);
  44040. if (t_int === trigger) {
  44041. return true;
  44042. }
  44043. }
  44044. }
  44045. return false;
  44046. };
  44047. /**
  44048. * Registers an action to this action manager
  44049. * @param {BABYLON.Action} action - the action to be registered
  44050. * @return {BABYLON.Action} the action amended (prepared) after registration
  44051. */
  44052. ActionManager.prototype.registerAction = function (action) {
  44053. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  44054. if (this.getScene().actionManager !== this) {
  44055. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  44056. return null;
  44057. }
  44058. }
  44059. this.actions.push(action);
  44060. if (ActionManager.Triggers[action.trigger]) {
  44061. ActionManager.Triggers[action.trigger]++;
  44062. }
  44063. else {
  44064. ActionManager.Triggers[action.trigger] = 1;
  44065. }
  44066. action._actionManager = this;
  44067. action._prepare();
  44068. return action;
  44069. };
  44070. /**
  44071. * Process a specific trigger
  44072. * @param {number} trigger - the trigger to process
  44073. * @param evt {BABYLON.ActionEvent} the event details to be processed
  44074. */
  44075. ActionManager.prototype.processTrigger = function (trigger, evt) {
  44076. for (var index = 0; index < this.actions.length; index++) {
  44077. var action = this.actions[index];
  44078. if (action.trigger === trigger) {
  44079. if (evt) {
  44080. if (trigger === ActionManager.OnKeyUpTrigger
  44081. || trigger === ActionManager.OnKeyDownTrigger) {
  44082. var parameter = action.getTriggerParameter();
  44083. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  44084. if (!parameter.toLowerCase) {
  44085. continue;
  44086. }
  44087. var lowerCase = parameter.toLowerCase();
  44088. if (lowerCase !== evt.sourceEvent.key) {
  44089. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  44090. var actualkey = String.fromCharCode(unicode).toLowerCase();
  44091. if (actualkey !== lowerCase) {
  44092. continue;
  44093. }
  44094. }
  44095. }
  44096. }
  44097. }
  44098. action._executeCurrent(evt);
  44099. }
  44100. }
  44101. };
  44102. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  44103. var properties = propertyPath.split(".");
  44104. for (var index = 0; index < properties.length - 1; index++) {
  44105. target = target[properties[index]];
  44106. }
  44107. return target;
  44108. };
  44109. ActionManager.prototype._getProperty = function (propertyPath) {
  44110. var properties = propertyPath.split(".");
  44111. return properties[properties.length - 1];
  44112. };
  44113. ActionManager.prototype.serialize = function (name) {
  44114. var root = {
  44115. children: new Array(),
  44116. name: name,
  44117. type: 3,
  44118. properties: new Array() // Empty for root but required
  44119. };
  44120. for (var i = 0; i < this.actions.length; i++) {
  44121. var triggerObject = {
  44122. type: 0,
  44123. children: new Array(),
  44124. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  44125. properties: new Array()
  44126. };
  44127. var triggerOptions = this.actions[i].triggerOptions;
  44128. if (triggerOptions && typeof triggerOptions !== "number") {
  44129. if (triggerOptions.parameter instanceof BABYLON.Node) {
  44130. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  44131. }
  44132. else {
  44133. var parameter = {};
  44134. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  44135. if (triggerOptions.parameter.mesh) {
  44136. parameter._meshId = triggerOptions.parameter.mesh.id;
  44137. }
  44138. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  44139. }
  44140. }
  44141. // Serialize child action, recursively
  44142. this.actions[i].serialize(triggerObject);
  44143. // Add serialized trigger
  44144. root.children.push(triggerObject);
  44145. }
  44146. return root;
  44147. };
  44148. ActionManager.Parse = function (parsedActions, object, scene) {
  44149. var actionManager = new ActionManager(scene);
  44150. if (object === null)
  44151. scene.actionManager = actionManager;
  44152. else
  44153. object.actionManager = actionManager;
  44154. // instanciate a new object
  44155. var instanciate = function (name, params) {
  44156. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  44157. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  44158. newInstance.constructor.apply(newInstance, params);
  44159. return newInstance;
  44160. };
  44161. var parseParameter = function (name, value, target, propertyPath) {
  44162. if (propertyPath === null) {
  44163. // String, boolean or float
  44164. var floatValue = parseFloat(value);
  44165. if (value === "true" || value === "false")
  44166. return value === "true";
  44167. else
  44168. return isNaN(floatValue) ? value : floatValue;
  44169. }
  44170. var effectiveTarget = propertyPath.split(".");
  44171. var values = value.split(",");
  44172. // Get effective Target
  44173. for (var i = 0; i < effectiveTarget.length; i++) {
  44174. target = target[effectiveTarget[i]];
  44175. }
  44176. // Return appropriate value with its type
  44177. if (typeof (target) === "boolean")
  44178. return values[0] === "true";
  44179. if (typeof (target) === "string")
  44180. return values[0];
  44181. // Parameters with multiple values such as Vector3 etc.
  44182. var split = new Array();
  44183. for (var i = 0; i < values.length; i++)
  44184. split.push(parseFloat(values[i]));
  44185. if (target instanceof BABYLON.Vector3)
  44186. return BABYLON.Vector3.FromArray(split);
  44187. if (target instanceof BABYLON.Vector4)
  44188. return BABYLON.Vector4.FromArray(split);
  44189. if (target instanceof BABYLON.Color3)
  44190. return BABYLON.Color3.FromArray(split);
  44191. if (target instanceof BABYLON.Color4)
  44192. return BABYLON.Color4.FromArray(split);
  44193. return parseFloat(values[0]);
  44194. };
  44195. // traverse graph per trigger
  44196. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  44197. if (combineArray === void 0) { combineArray = null; }
  44198. if (parsedAction.detached)
  44199. return;
  44200. var parameters = new Array();
  44201. var target = null;
  44202. var propertyPath = null;
  44203. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  44204. // Parameters
  44205. if (parsedAction.type === 2)
  44206. parameters.push(actionManager);
  44207. else
  44208. parameters.push(trigger);
  44209. if (combine) {
  44210. var actions = new Array();
  44211. for (var j = 0; j < parsedAction.combine.length; j++) {
  44212. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  44213. }
  44214. parameters.push(actions);
  44215. }
  44216. else {
  44217. for (var i = 0; i < parsedAction.properties.length; i++) {
  44218. var value = parsedAction.properties[i].value;
  44219. var name = parsedAction.properties[i].name;
  44220. var targetType = parsedAction.properties[i].targetType;
  44221. if (name === "target")
  44222. if (targetType !== null && targetType === "SceneProperties")
  44223. value = target = scene;
  44224. else
  44225. value = target = scene.getNodeByName(value);
  44226. else if (name === "parent")
  44227. value = scene.getNodeByName(value);
  44228. else if (name === "sound")
  44229. value = scene.getSoundByName(value);
  44230. else if (name !== "propertyPath") {
  44231. if (parsedAction.type === 2 && name === "operator")
  44232. value = BABYLON.ValueCondition[value];
  44233. else
  44234. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  44235. }
  44236. else {
  44237. propertyPath = value;
  44238. }
  44239. parameters.push(value);
  44240. }
  44241. }
  44242. if (combineArray === null) {
  44243. parameters.push(condition);
  44244. }
  44245. else {
  44246. parameters.push(null);
  44247. }
  44248. // If interpolate value action
  44249. if (parsedAction.name === "InterpolateValueAction") {
  44250. var param = parameters[parameters.length - 2];
  44251. parameters[parameters.length - 1] = param;
  44252. parameters[parameters.length - 2] = condition;
  44253. }
  44254. // Action or condition(s) and not CombineAction
  44255. var newAction = instanciate(parsedAction.name, parameters);
  44256. if (newAction instanceof BABYLON.Condition && condition !== null) {
  44257. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  44258. if (action)
  44259. action.then(nothing);
  44260. else
  44261. actionManager.registerAction(nothing);
  44262. action = nothing;
  44263. }
  44264. if (combineArray === null) {
  44265. if (newAction instanceof BABYLON.Condition) {
  44266. condition = newAction;
  44267. newAction = action;
  44268. }
  44269. else {
  44270. condition = null;
  44271. if (action)
  44272. action.then(newAction);
  44273. else
  44274. actionManager.registerAction(newAction);
  44275. }
  44276. }
  44277. else {
  44278. combineArray.push(newAction);
  44279. }
  44280. for (var i = 0; i < parsedAction.children.length; i++)
  44281. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  44282. };
  44283. // triggers
  44284. for (var i = 0; i < parsedActions.children.length; i++) {
  44285. var triggerParams;
  44286. var trigger = parsedActions.children[i];
  44287. if (trigger.properties.length > 0) {
  44288. var param = trigger.properties[0].value;
  44289. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  44290. if (value._meshId) {
  44291. value.mesh = scene.getMeshByID(value._meshId);
  44292. }
  44293. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  44294. }
  44295. else
  44296. triggerParams = ActionManager[trigger.name];
  44297. for (var j = 0; j < trigger.children.length; j++) {
  44298. if (!trigger.detached)
  44299. traverse(trigger.children[j], triggerParams, null, null);
  44300. }
  44301. }
  44302. };
  44303. ActionManager.GetTriggerName = function (trigger) {
  44304. switch (trigger) {
  44305. case 0: return "NothingTrigger";
  44306. case 1: return "OnPickTrigger";
  44307. case 2: return "OnLeftPickTrigger";
  44308. case 3: return "OnRightPickTrigger";
  44309. case 4: return "OnCenterPickTrigger";
  44310. case 5: return "OnPickDownTrigger";
  44311. case 6: return "OnPickUpTrigger";
  44312. case 7: return "OnLongPressTrigger";
  44313. case 8: return "OnPointerOverTrigger";
  44314. case 9: return "OnPointerOutTrigger";
  44315. case 10: return "OnEveryFrameTrigger";
  44316. case 11: return "OnIntersectionEnterTrigger";
  44317. case 12: return "OnIntersectionExitTrigger";
  44318. case 13: return "OnKeyDownTrigger";
  44319. case 14: return "OnKeyUpTrigger";
  44320. case 15: return "OnPickOutTrigger";
  44321. default: return "";
  44322. }
  44323. };
  44324. // Statics
  44325. ActionManager._NothingTrigger = 0;
  44326. ActionManager._OnPickTrigger = 1;
  44327. ActionManager._OnLeftPickTrigger = 2;
  44328. ActionManager._OnRightPickTrigger = 3;
  44329. ActionManager._OnCenterPickTrigger = 4;
  44330. ActionManager._OnPickDownTrigger = 5;
  44331. ActionManager._OnDoublePickTrigger = 6;
  44332. ActionManager._OnPickUpTrigger = 7;
  44333. ActionManager._OnLongPressTrigger = 8;
  44334. ActionManager._OnPointerOverTrigger = 9;
  44335. ActionManager._OnPointerOutTrigger = 10;
  44336. ActionManager._OnEveryFrameTrigger = 11;
  44337. ActionManager._OnIntersectionEnterTrigger = 12;
  44338. ActionManager._OnIntersectionExitTrigger = 13;
  44339. ActionManager._OnKeyDownTrigger = 14;
  44340. ActionManager._OnKeyUpTrigger = 15;
  44341. ActionManager._OnPickOutTrigger = 16;
  44342. ActionManager.Triggers = {};
  44343. return ActionManager;
  44344. }());
  44345. BABYLON.ActionManager = ActionManager;
  44346. })(BABYLON || (BABYLON = {}));
  44347. //# sourceMappingURL=babylon.actionManager.js.map
  44348. var BABYLON;
  44349. (function (BABYLON) {
  44350. var InterpolateValueAction = /** @class */ (function (_super) {
  44351. __extends(InterpolateValueAction, _super);
  44352. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  44353. if (duration === void 0) { duration = 1000; }
  44354. var _this = _super.call(this, triggerOptions, condition) || this;
  44355. _this.propertyPath = propertyPath;
  44356. _this.value = value;
  44357. _this.duration = duration;
  44358. _this.stopOtherAnimations = stopOtherAnimations;
  44359. _this.onInterpolationDone = onInterpolationDone;
  44360. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  44361. _this._target = _this._effectiveTarget = target;
  44362. return _this;
  44363. }
  44364. InterpolateValueAction.prototype._prepare = function () {
  44365. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44366. this._property = this._getProperty(this.propertyPath);
  44367. };
  44368. InterpolateValueAction.prototype.execute = function () {
  44369. var _this = this;
  44370. var scene = this._actionManager.getScene();
  44371. var keys = [
  44372. {
  44373. frame: 0,
  44374. value: this._effectiveTarget[this._property]
  44375. }, {
  44376. frame: 100,
  44377. value: this.value
  44378. }
  44379. ];
  44380. var dataType;
  44381. if (typeof this.value === "number") {
  44382. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  44383. }
  44384. else if (this.value instanceof BABYLON.Color3) {
  44385. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  44386. }
  44387. else if (this.value instanceof BABYLON.Vector3) {
  44388. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  44389. }
  44390. else if (this.value instanceof BABYLON.Matrix) {
  44391. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  44392. }
  44393. else if (this.value instanceof BABYLON.Quaternion) {
  44394. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  44395. }
  44396. else {
  44397. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  44398. return;
  44399. }
  44400. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  44401. animation.setKeys(keys);
  44402. if (this.stopOtherAnimations) {
  44403. scene.stopAnimation(this._effectiveTarget);
  44404. }
  44405. var wrapper = function () {
  44406. _this.onInterpolationDoneObservable.notifyObservers(_this);
  44407. if (_this.onInterpolationDone) {
  44408. _this.onInterpolationDone();
  44409. }
  44410. };
  44411. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  44412. };
  44413. InterpolateValueAction.prototype.serialize = function (parent) {
  44414. return _super.prototype._serialize.call(this, {
  44415. name: "InterpolateValueAction",
  44416. properties: [
  44417. BABYLON.Action._GetTargetProperty(this._target),
  44418. { name: "propertyPath", value: this.propertyPath },
  44419. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  44420. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  44421. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  44422. ]
  44423. }, parent);
  44424. };
  44425. return InterpolateValueAction;
  44426. }(BABYLON.Action));
  44427. BABYLON.InterpolateValueAction = InterpolateValueAction;
  44428. })(BABYLON || (BABYLON = {}));
  44429. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  44430. var BABYLON;
  44431. (function (BABYLON) {
  44432. var SwitchBooleanAction = /** @class */ (function (_super) {
  44433. __extends(SwitchBooleanAction, _super);
  44434. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  44435. var _this = _super.call(this, triggerOptions, condition) || this;
  44436. _this.propertyPath = propertyPath;
  44437. _this._target = _this._effectiveTarget = target;
  44438. return _this;
  44439. }
  44440. SwitchBooleanAction.prototype._prepare = function () {
  44441. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44442. this._property = this._getProperty(this.propertyPath);
  44443. };
  44444. SwitchBooleanAction.prototype.execute = function () {
  44445. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  44446. };
  44447. SwitchBooleanAction.prototype.serialize = function (parent) {
  44448. return _super.prototype._serialize.call(this, {
  44449. name: "SwitchBooleanAction",
  44450. properties: [
  44451. BABYLON.Action._GetTargetProperty(this._target),
  44452. { name: "propertyPath", value: this.propertyPath }
  44453. ]
  44454. }, parent);
  44455. };
  44456. return SwitchBooleanAction;
  44457. }(BABYLON.Action));
  44458. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  44459. var SetStateAction = /** @class */ (function (_super) {
  44460. __extends(SetStateAction, _super);
  44461. function SetStateAction(triggerOptions, target, value, condition) {
  44462. var _this = _super.call(this, triggerOptions, condition) || this;
  44463. _this.value = value;
  44464. _this._target = target;
  44465. return _this;
  44466. }
  44467. SetStateAction.prototype.execute = function () {
  44468. this._target.state = this.value;
  44469. };
  44470. SetStateAction.prototype.serialize = function (parent) {
  44471. return _super.prototype._serialize.call(this, {
  44472. name: "SetStateAction",
  44473. properties: [
  44474. BABYLON.Action._GetTargetProperty(this._target),
  44475. { name: "value", value: this.value }
  44476. ]
  44477. }, parent);
  44478. };
  44479. return SetStateAction;
  44480. }(BABYLON.Action));
  44481. BABYLON.SetStateAction = SetStateAction;
  44482. var SetValueAction = /** @class */ (function (_super) {
  44483. __extends(SetValueAction, _super);
  44484. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  44485. var _this = _super.call(this, triggerOptions, condition) || this;
  44486. _this.propertyPath = propertyPath;
  44487. _this.value = value;
  44488. _this._target = _this._effectiveTarget = target;
  44489. return _this;
  44490. }
  44491. SetValueAction.prototype._prepare = function () {
  44492. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44493. this._property = this._getProperty(this.propertyPath);
  44494. };
  44495. SetValueAction.prototype.execute = function () {
  44496. this._effectiveTarget[this._property] = this.value;
  44497. if (this._target.markAsDirty) {
  44498. this._target.markAsDirty(this._property);
  44499. }
  44500. };
  44501. SetValueAction.prototype.serialize = function (parent) {
  44502. return _super.prototype._serialize.call(this, {
  44503. name: "SetValueAction",
  44504. properties: [
  44505. BABYLON.Action._GetTargetProperty(this._target),
  44506. { name: "propertyPath", value: this.propertyPath },
  44507. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44508. ]
  44509. }, parent);
  44510. };
  44511. return SetValueAction;
  44512. }(BABYLON.Action));
  44513. BABYLON.SetValueAction = SetValueAction;
  44514. var IncrementValueAction = /** @class */ (function (_super) {
  44515. __extends(IncrementValueAction, _super);
  44516. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44517. var _this = _super.call(this, triggerOptions, condition) || this;
  44518. _this.propertyPath = propertyPath;
  44519. _this.value = value;
  44520. _this._target = _this._effectiveTarget = target;
  44521. return _this;
  44522. }
  44523. IncrementValueAction.prototype._prepare = function () {
  44524. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44525. this._property = this._getProperty(this.propertyPath);
  44526. if (typeof this._effectiveTarget[this._property] !== "number") {
  44527. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44528. }
  44529. };
  44530. IncrementValueAction.prototype.execute = function () {
  44531. this._effectiveTarget[this._property] += this.value;
  44532. if (this._target.markAsDirty) {
  44533. this._target.markAsDirty(this._property);
  44534. }
  44535. };
  44536. IncrementValueAction.prototype.serialize = function (parent) {
  44537. return _super.prototype._serialize.call(this, {
  44538. name: "IncrementValueAction",
  44539. properties: [
  44540. BABYLON.Action._GetTargetProperty(this._target),
  44541. { name: "propertyPath", value: this.propertyPath },
  44542. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44543. ]
  44544. }, parent);
  44545. };
  44546. return IncrementValueAction;
  44547. }(BABYLON.Action));
  44548. BABYLON.IncrementValueAction = IncrementValueAction;
  44549. var PlayAnimationAction = /** @class */ (function (_super) {
  44550. __extends(PlayAnimationAction, _super);
  44551. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44552. var _this = _super.call(this, triggerOptions, condition) || this;
  44553. _this.from = from;
  44554. _this.to = to;
  44555. _this.loop = loop;
  44556. _this._target = target;
  44557. return _this;
  44558. }
  44559. PlayAnimationAction.prototype._prepare = function () {
  44560. };
  44561. PlayAnimationAction.prototype.execute = function () {
  44562. var scene = this._actionManager.getScene();
  44563. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44564. };
  44565. PlayAnimationAction.prototype.serialize = function (parent) {
  44566. return _super.prototype._serialize.call(this, {
  44567. name: "PlayAnimationAction",
  44568. properties: [
  44569. BABYLON.Action._GetTargetProperty(this._target),
  44570. { name: "from", value: String(this.from) },
  44571. { name: "to", value: String(this.to) },
  44572. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44573. ]
  44574. }, parent);
  44575. };
  44576. return PlayAnimationAction;
  44577. }(BABYLON.Action));
  44578. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44579. var StopAnimationAction = /** @class */ (function (_super) {
  44580. __extends(StopAnimationAction, _super);
  44581. function StopAnimationAction(triggerOptions, target, condition) {
  44582. var _this = _super.call(this, triggerOptions, condition) || this;
  44583. _this._target = target;
  44584. return _this;
  44585. }
  44586. StopAnimationAction.prototype._prepare = function () {
  44587. };
  44588. StopAnimationAction.prototype.execute = function () {
  44589. var scene = this._actionManager.getScene();
  44590. scene.stopAnimation(this._target);
  44591. };
  44592. StopAnimationAction.prototype.serialize = function (parent) {
  44593. return _super.prototype._serialize.call(this, {
  44594. name: "StopAnimationAction",
  44595. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44596. }, parent);
  44597. };
  44598. return StopAnimationAction;
  44599. }(BABYLON.Action));
  44600. BABYLON.StopAnimationAction = StopAnimationAction;
  44601. var DoNothingAction = /** @class */ (function (_super) {
  44602. __extends(DoNothingAction, _super);
  44603. function DoNothingAction(triggerOptions, condition) {
  44604. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44605. return _super.call(this, triggerOptions, condition) || this;
  44606. }
  44607. DoNothingAction.prototype.execute = function () {
  44608. };
  44609. DoNothingAction.prototype.serialize = function (parent) {
  44610. return _super.prototype._serialize.call(this, {
  44611. name: "DoNothingAction",
  44612. properties: []
  44613. }, parent);
  44614. };
  44615. return DoNothingAction;
  44616. }(BABYLON.Action));
  44617. BABYLON.DoNothingAction = DoNothingAction;
  44618. var CombineAction = /** @class */ (function (_super) {
  44619. __extends(CombineAction, _super);
  44620. function CombineAction(triggerOptions, children, condition) {
  44621. var _this = _super.call(this, triggerOptions, condition) || this;
  44622. _this.children = children;
  44623. return _this;
  44624. }
  44625. CombineAction.prototype._prepare = function () {
  44626. for (var index = 0; index < this.children.length; index++) {
  44627. this.children[index]._actionManager = this._actionManager;
  44628. this.children[index]._prepare();
  44629. }
  44630. };
  44631. CombineAction.prototype.execute = function (evt) {
  44632. for (var index = 0; index < this.children.length; index++) {
  44633. this.children[index].execute(evt);
  44634. }
  44635. };
  44636. CombineAction.prototype.serialize = function (parent) {
  44637. var serializationObject = _super.prototype._serialize.call(this, {
  44638. name: "CombineAction",
  44639. properties: [],
  44640. combine: []
  44641. }, parent);
  44642. for (var i = 0; i < this.children.length; i++) {
  44643. serializationObject.combine.push(this.children[i].serialize(null));
  44644. }
  44645. return serializationObject;
  44646. };
  44647. return CombineAction;
  44648. }(BABYLON.Action));
  44649. BABYLON.CombineAction = CombineAction;
  44650. var ExecuteCodeAction = /** @class */ (function (_super) {
  44651. __extends(ExecuteCodeAction, _super);
  44652. function ExecuteCodeAction(triggerOptions, func, condition) {
  44653. var _this = _super.call(this, triggerOptions, condition) || this;
  44654. _this.func = func;
  44655. return _this;
  44656. }
  44657. ExecuteCodeAction.prototype.execute = function (evt) {
  44658. this.func(evt);
  44659. };
  44660. return ExecuteCodeAction;
  44661. }(BABYLON.Action));
  44662. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44663. var SetParentAction = /** @class */ (function (_super) {
  44664. __extends(SetParentAction, _super);
  44665. function SetParentAction(triggerOptions, target, parent, condition) {
  44666. var _this = _super.call(this, triggerOptions, condition) || this;
  44667. _this._target = target;
  44668. _this._parent = parent;
  44669. return _this;
  44670. }
  44671. SetParentAction.prototype._prepare = function () {
  44672. };
  44673. SetParentAction.prototype.execute = function () {
  44674. if (this._target.parent === this._parent) {
  44675. return;
  44676. }
  44677. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44678. invertParentWorldMatrix.invert();
  44679. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44680. this._target.parent = this._parent;
  44681. };
  44682. SetParentAction.prototype.serialize = function (parent) {
  44683. return _super.prototype._serialize.call(this, {
  44684. name: "SetParentAction",
  44685. properties: [
  44686. BABYLON.Action._GetTargetProperty(this._target),
  44687. BABYLON.Action._GetTargetProperty(this._parent),
  44688. ]
  44689. }, parent);
  44690. };
  44691. return SetParentAction;
  44692. }(BABYLON.Action));
  44693. BABYLON.SetParentAction = SetParentAction;
  44694. var PlaySoundAction = /** @class */ (function (_super) {
  44695. __extends(PlaySoundAction, _super);
  44696. function PlaySoundAction(triggerOptions, sound, condition) {
  44697. var _this = _super.call(this, triggerOptions, condition) || this;
  44698. _this._sound = sound;
  44699. return _this;
  44700. }
  44701. PlaySoundAction.prototype._prepare = function () {
  44702. };
  44703. PlaySoundAction.prototype.execute = function () {
  44704. if (this._sound !== undefined)
  44705. this._sound.play();
  44706. };
  44707. PlaySoundAction.prototype.serialize = function (parent) {
  44708. return _super.prototype._serialize.call(this, {
  44709. name: "PlaySoundAction",
  44710. properties: [{ name: "sound", value: this._sound.name }]
  44711. }, parent);
  44712. };
  44713. return PlaySoundAction;
  44714. }(BABYLON.Action));
  44715. BABYLON.PlaySoundAction = PlaySoundAction;
  44716. var StopSoundAction = /** @class */ (function (_super) {
  44717. __extends(StopSoundAction, _super);
  44718. function StopSoundAction(triggerOptions, sound, condition) {
  44719. var _this = _super.call(this, triggerOptions, condition) || this;
  44720. _this._sound = sound;
  44721. return _this;
  44722. }
  44723. StopSoundAction.prototype._prepare = function () {
  44724. };
  44725. StopSoundAction.prototype.execute = function () {
  44726. if (this._sound !== undefined)
  44727. this._sound.stop();
  44728. };
  44729. StopSoundAction.prototype.serialize = function (parent) {
  44730. return _super.prototype._serialize.call(this, {
  44731. name: "StopSoundAction",
  44732. properties: [{ name: "sound", value: this._sound.name }]
  44733. }, parent);
  44734. };
  44735. return StopSoundAction;
  44736. }(BABYLON.Action));
  44737. BABYLON.StopSoundAction = StopSoundAction;
  44738. })(BABYLON || (BABYLON = {}));
  44739. //# sourceMappingURL=babylon.directActions.js.map
  44740. var BABYLON;
  44741. (function (BABYLON) {
  44742. var SpriteManager = /** @class */ (function () {
  44743. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44744. if (epsilon === void 0) { epsilon = 0.01; }
  44745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44746. this.name = name;
  44747. this.sprites = new Array();
  44748. this.renderingGroupId = 0;
  44749. this.layerMask = 0x0FFFFFFF;
  44750. this.fogEnabled = true;
  44751. this.isPickable = false;
  44752. /**
  44753. * An event triggered when the manager is disposed.
  44754. * @type {BABYLON.Observable}
  44755. */
  44756. this.onDisposeObservable = new BABYLON.Observable();
  44757. this._vertexBuffers = {};
  44758. this._capacity = capacity;
  44759. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44760. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44761. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44762. if (cellSize.width && cellSize.height) {
  44763. this.cellWidth = cellSize.width;
  44764. this.cellHeight = cellSize.height;
  44765. }
  44766. else if (cellSize !== undefined) {
  44767. this.cellWidth = cellSize;
  44768. this.cellHeight = cellSize;
  44769. }
  44770. else {
  44771. return;
  44772. }
  44773. this._epsilon = epsilon;
  44774. this._scene = scene;
  44775. this._scene.spriteManagers.push(this);
  44776. var indices = [];
  44777. var index = 0;
  44778. for (var count = 0; count < capacity; count++) {
  44779. indices.push(index);
  44780. indices.push(index + 1);
  44781. indices.push(index + 2);
  44782. indices.push(index);
  44783. indices.push(index + 2);
  44784. indices.push(index + 3);
  44785. index += 4;
  44786. }
  44787. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44788. // VBO
  44789. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44790. this._vertexData = new Float32Array(capacity * 16 * 4);
  44791. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44792. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44793. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44794. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44795. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44796. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44797. this._vertexBuffers["options"] = options;
  44798. this._vertexBuffers["cellInfo"] = cellInfo;
  44799. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44800. // Effects
  44801. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44802. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44803. }
  44804. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44805. set: function (callback) {
  44806. if (this._onDisposeObserver) {
  44807. this.onDisposeObservable.remove(this._onDisposeObserver);
  44808. }
  44809. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44810. },
  44811. enumerable: true,
  44812. configurable: true
  44813. });
  44814. Object.defineProperty(SpriteManager.prototype, "texture", {
  44815. get: function () {
  44816. return this._spriteTexture;
  44817. },
  44818. set: function (value) {
  44819. this._spriteTexture = value;
  44820. },
  44821. enumerable: true,
  44822. configurable: true
  44823. });
  44824. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44825. var arrayOffset = index * 16;
  44826. if (offsetX === 0)
  44827. offsetX = this._epsilon;
  44828. else if (offsetX === 1)
  44829. offsetX = 1 - this._epsilon;
  44830. if (offsetY === 0)
  44831. offsetY = this._epsilon;
  44832. else if (offsetY === 1)
  44833. offsetY = 1 - this._epsilon;
  44834. this._vertexData[arrayOffset] = sprite.position.x;
  44835. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44836. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44837. this._vertexData[arrayOffset + 3] = sprite.angle;
  44838. this._vertexData[arrayOffset + 4] = sprite.width;
  44839. this._vertexData[arrayOffset + 5] = sprite.height;
  44840. this._vertexData[arrayOffset + 6] = offsetX;
  44841. this._vertexData[arrayOffset + 7] = offsetY;
  44842. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44843. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44844. var offset = (sprite.cellIndex / rowSize) >> 0;
  44845. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44846. this._vertexData[arrayOffset + 11] = offset;
  44847. // Color
  44848. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44849. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44850. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44851. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44852. };
  44853. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44854. var count = Math.min(this._capacity, this.sprites.length);
  44855. var min = BABYLON.Vector3.Zero();
  44856. var max = BABYLON.Vector3.Zero();
  44857. var distance = Number.MAX_VALUE;
  44858. var currentSprite = null;
  44859. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44860. var cameraView = camera.getViewMatrix();
  44861. for (var index = 0; index < count; index++) {
  44862. var sprite = this.sprites[index];
  44863. if (!sprite) {
  44864. continue;
  44865. }
  44866. if (predicate) {
  44867. if (!predicate(sprite)) {
  44868. continue;
  44869. }
  44870. }
  44871. else if (!sprite.isPickable) {
  44872. continue;
  44873. }
  44874. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44875. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44876. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44877. if (ray.intersectsBoxMinMax(min, max)) {
  44878. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44879. if (distance > currentDistance) {
  44880. distance = currentDistance;
  44881. currentSprite = sprite;
  44882. if (fastCheck) {
  44883. break;
  44884. }
  44885. }
  44886. }
  44887. }
  44888. if (currentSprite) {
  44889. var result = new BABYLON.PickingInfo();
  44890. result.hit = true;
  44891. result.pickedSprite = currentSprite;
  44892. result.distance = distance;
  44893. return result;
  44894. }
  44895. return null;
  44896. };
  44897. SpriteManager.prototype.render = function () {
  44898. // Check
  44899. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44900. return;
  44901. var engine = this._scene.getEngine();
  44902. var baseSize = this._spriteTexture.getBaseSize();
  44903. // Sprites
  44904. var deltaTime = engine.getDeltaTime();
  44905. var max = Math.min(this._capacity, this.sprites.length);
  44906. var rowSize = baseSize.width / this.cellWidth;
  44907. var offset = 0;
  44908. for (var index = 0; index < max; index++) {
  44909. var sprite = this.sprites[index];
  44910. if (!sprite) {
  44911. continue;
  44912. }
  44913. sprite._animate(deltaTime);
  44914. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44915. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44916. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44917. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44918. }
  44919. this._buffer.update(this._vertexData);
  44920. // Render
  44921. var effect = this._effectBase;
  44922. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44923. effect = this._effectFog;
  44924. }
  44925. engine.enableEffect(effect);
  44926. var viewMatrix = this._scene.getViewMatrix();
  44927. effect.setTexture("diffuseSampler", this._spriteTexture);
  44928. effect.setMatrix("view", viewMatrix);
  44929. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44930. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44931. // Fog
  44932. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44933. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44934. effect.setColor3("vFogColor", this._scene.fogColor);
  44935. }
  44936. // VBOs
  44937. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44938. // Draw order
  44939. engine.setDepthFunctionToLessOrEqual();
  44940. effect.setBool("alphaTest", true);
  44941. engine.setColorWrite(false);
  44942. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44943. engine.setColorWrite(true);
  44944. effect.setBool("alphaTest", false);
  44945. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44946. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44947. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44948. };
  44949. SpriteManager.prototype.dispose = function () {
  44950. if (this._buffer) {
  44951. this._buffer.dispose();
  44952. this._buffer = null;
  44953. }
  44954. if (this._indexBuffer) {
  44955. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44956. this._indexBuffer = null;
  44957. }
  44958. if (this._spriteTexture) {
  44959. this._spriteTexture.dispose();
  44960. this._spriteTexture = null;
  44961. }
  44962. // Remove from scene
  44963. var index = this._scene.spriteManagers.indexOf(this);
  44964. this._scene.spriteManagers.splice(index, 1);
  44965. // Callback
  44966. this.onDisposeObservable.notifyObservers(this);
  44967. this.onDisposeObservable.clear();
  44968. };
  44969. return SpriteManager;
  44970. }());
  44971. BABYLON.SpriteManager = SpriteManager;
  44972. })(BABYLON || (BABYLON = {}));
  44973. //# sourceMappingURL=babylon.spriteManager.js.map
  44974. var BABYLON;
  44975. (function (BABYLON) {
  44976. var Sprite = /** @class */ (function () {
  44977. function Sprite(name, manager) {
  44978. this.name = name;
  44979. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44980. this.width = 1.0;
  44981. this.height = 1.0;
  44982. this.angle = 0;
  44983. this.cellIndex = 0;
  44984. this.invertU = 0;
  44985. this.invertV = 0;
  44986. this.animations = new Array();
  44987. this.isPickable = false;
  44988. this._animationStarted = false;
  44989. this._loopAnimation = false;
  44990. this._fromIndex = 0;
  44991. this._toIndex = 0;
  44992. this._delay = 0;
  44993. this._direction = 1;
  44994. this._time = 0;
  44995. this._manager = manager;
  44996. this._manager.sprites.push(this);
  44997. this.position = BABYLON.Vector3.Zero();
  44998. }
  44999. Object.defineProperty(Sprite.prototype, "size", {
  45000. get: function () {
  45001. return this.width;
  45002. },
  45003. set: function (value) {
  45004. this.width = value;
  45005. this.height = value;
  45006. },
  45007. enumerable: true,
  45008. configurable: true
  45009. });
  45010. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  45011. this._fromIndex = from;
  45012. this._toIndex = to;
  45013. this._loopAnimation = loop;
  45014. this._delay = delay;
  45015. this._animationStarted = true;
  45016. this._direction = from < to ? 1 : -1;
  45017. this.cellIndex = from;
  45018. this._time = 0;
  45019. this._onAnimationEnd = onAnimationEnd;
  45020. };
  45021. Sprite.prototype.stopAnimation = function () {
  45022. this._animationStarted = false;
  45023. };
  45024. Sprite.prototype._animate = function (deltaTime) {
  45025. if (!this._animationStarted)
  45026. return;
  45027. this._time += deltaTime;
  45028. if (this._time > this._delay) {
  45029. this._time = this._time % this._delay;
  45030. this.cellIndex += this._direction;
  45031. if (this.cellIndex > this._toIndex) {
  45032. if (this._loopAnimation) {
  45033. this.cellIndex = this._fromIndex;
  45034. }
  45035. else {
  45036. this.cellIndex = this._toIndex;
  45037. this._animationStarted = false;
  45038. if (this._onAnimationEnd) {
  45039. this._onAnimationEnd();
  45040. }
  45041. if (this.disposeWhenFinishedAnimating) {
  45042. this.dispose();
  45043. }
  45044. }
  45045. }
  45046. }
  45047. };
  45048. Sprite.prototype.dispose = function () {
  45049. for (var i = 0; i < this._manager.sprites.length; i++) {
  45050. if (this._manager.sprites[i] == this) {
  45051. this._manager.sprites.splice(i, 1);
  45052. }
  45053. }
  45054. };
  45055. return Sprite;
  45056. }());
  45057. BABYLON.Sprite = Sprite;
  45058. })(BABYLON || (BABYLON = {}));
  45059. //# sourceMappingURL=babylon.sprite.js.map
  45060. var BABYLON;
  45061. (function (BABYLON) {
  45062. var IntersectionInfo = /** @class */ (function () {
  45063. function IntersectionInfo(bu, bv, distance) {
  45064. this.bu = bu;
  45065. this.bv = bv;
  45066. this.distance = distance;
  45067. this.faceId = 0;
  45068. this.subMeshId = 0;
  45069. }
  45070. return IntersectionInfo;
  45071. }());
  45072. BABYLON.IntersectionInfo = IntersectionInfo;
  45073. var PickingInfo = /** @class */ (function () {
  45074. function PickingInfo() {
  45075. this.hit = false;
  45076. this.distance = 0;
  45077. this.pickedPoint = null;
  45078. this.pickedMesh = null;
  45079. this.bu = 0;
  45080. this.bv = 0;
  45081. this.faceId = -1;
  45082. this.subMeshId = 0;
  45083. this.pickedSprite = null;
  45084. }
  45085. // Methods
  45086. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  45087. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  45088. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  45089. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45090. return null;
  45091. }
  45092. var indices = this.pickedMesh.getIndices();
  45093. if (!indices) {
  45094. return null;
  45095. }
  45096. var result;
  45097. if (useVerticesNormals) {
  45098. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  45099. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  45100. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  45101. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  45102. normal0 = normal0.scale(this.bu);
  45103. normal1 = normal1.scale(this.bv);
  45104. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  45105. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  45106. }
  45107. else {
  45108. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  45109. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  45110. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  45111. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  45112. var p1p2 = vertex1.subtract(vertex2);
  45113. var p3p2 = vertex3.subtract(vertex2);
  45114. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  45115. }
  45116. if (useWorldCoordinates) {
  45117. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  45118. }
  45119. return BABYLON.Vector3.Normalize(result);
  45120. };
  45121. PickingInfo.prototype.getTextureCoordinates = function () {
  45122. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45123. return null;
  45124. }
  45125. var indices = this.pickedMesh.getIndices();
  45126. if (!indices) {
  45127. return null;
  45128. }
  45129. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  45130. if (!uvs) {
  45131. return null;
  45132. }
  45133. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  45134. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  45135. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  45136. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  45137. uv1 = uv1.scale(this.bu);
  45138. uv2 = uv2.scale(this.bv);
  45139. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  45140. };
  45141. return PickingInfo;
  45142. }());
  45143. BABYLON.PickingInfo = PickingInfo;
  45144. })(BABYLON || (BABYLON = {}));
  45145. //# sourceMappingURL=babylon.pickingInfo.js.map
  45146. var BABYLON;
  45147. (function (BABYLON) {
  45148. var Ray = /** @class */ (function () {
  45149. function Ray(origin, direction, length) {
  45150. if (length === void 0) { length = Number.MAX_VALUE; }
  45151. this.origin = origin;
  45152. this.direction = direction;
  45153. this.length = length;
  45154. }
  45155. // Methods
  45156. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  45157. var d = 0.0;
  45158. var maxValue = Number.MAX_VALUE;
  45159. var inv;
  45160. var min;
  45161. var max;
  45162. var temp;
  45163. if (Math.abs(this.direction.x) < 0.0000001) {
  45164. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  45165. return false;
  45166. }
  45167. }
  45168. else {
  45169. inv = 1.0 / this.direction.x;
  45170. min = (minimum.x - this.origin.x) * inv;
  45171. max = (maximum.x - this.origin.x) * inv;
  45172. if (max === -Infinity) {
  45173. max = Infinity;
  45174. }
  45175. if (min > max) {
  45176. temp = min;
  45177. min = max;
  45178. max = temp;
  45179. }
  45180. d = Math.max(min, d);
  45181. maxValue = Math.min(max, maxValue);
  45182. if (d > maxValue) {
  45183. return false;
  45184. }
  45185. }
  45186. if (Math.abs(this.direction.y) < 0.0000001) {
  45187. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  45188. return false;
  45189. }
  45190. }
  45191. else {
  45192. inv = 1.0 / this.direction.y;
  45193. min = (minimum.y - this.origin.y) * inv;
  45194. max = (maximum.y - this.origin.y) * inv;
  45195. if (max === -Infinity) {
  45196. max = Infinity;
  45197. }
  45198. if (min > max) {
  45199. temp = min;
  45200. min = max;
  45201. max = temp;
  45202. }
  45203. d = Math.max(min, d);
  45204. maxValue = Math.min(max, maxValue);
  45205. if (d > maxValue) {
  45206. return false;
  45207. }
  45208. }
  45209. if (Math.abs(this.direction.z) < 0.0000001) {
  45210. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  45211. return false;
  45212. }
  45213. }
  45214. else {
  45215. inv = 1.0 / this.direction.z;
  45216. min = (minimum.z - this.origin.z) * inv;
  45217. max = (maximum.z - this.origin.z) * inv;
  45218. if (max === -Infinity) {
  45219. max = Infinity;
  45220. }
  45221. if (min > max) {
  45222. temp = min;
  45223. min = max;
  45224. max = temp;
  45225. }
  45226. d = Math.max(min, d);
  45227. maxValue = Math.min(max, maxValue);
  45228. if (d > maxValue) {
  45229. return false;
  45230. }
  45231. }
  45232. return true;
  45233. };
  45234. Ray.prototype.intersectsBox = function (box) {
  45235. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  45236. };
  45237. Ray.prototype.intersectsSphere = function (sphere) {
  45238. var x = sphere.center.x - this.origin.x;
  45239. var y = sphere.center.y - this.origin.y;
  45240. var z = sphere.center.z - this.origin.z;
  45241. var pyth = (x * x) + (y * y) + (z * z);
  45242. var rr = sphere.radius * sphere.radius;
  45243. if (pyth <= rr) {
  45244. return true;
  45245. }
  45246. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  45247. if (dot < 0.0) {
  45248. return false;
  45249. }
  45250. var temp = pyth - (dot * dot);
  45251. return temp <= rr;
  45252. };
  45253. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  45254. if (!this._edge1) {
  45255. this._edge1 = BABYLON.Vector3.Zero();
  45256. this._edge2 = BABYLON.Vector3.Zero();
  45257. this._pvec = BABYLON.Vector3.Zero();
  45258. this._tvec = BABYLON.Vector3.Zero();
  45259. this._qvec = BABYLON.Vector3.Zero();
  45260. }
  45261. vertex1.subtractToRef(vertex0, this._edge1);
  45262. vertex2.subtractToRef(vertex0, this._edge2);
  45263. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  45264. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  45265. if (det === 0) {
  45266. return null;
  45267. }
  45268. var invdet = 1 / det;
  45269. this.origin.subtractToRef(vertex0, this._tvec);
  45270. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  45271. if (bu < 0 || bu > 1.0) {
  45272. return null;
  45273. }
  45274. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  45275. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  45276. if (bv < 0 || bu + bv > 1.0) {
  45277. return null;
  45278. }
  45279. //check if the distance is longer than the predefined length.
  45280. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  45281. if (distance > this.length) {
  45282. return null;
  45283. }
  45284. return new BABYLON.IntersectionInfo(bu, bv, distance);
  45285. };
  45286. Ray.prototype.intersectsPlane = function (plane) {
  45287. var distance;
  45288. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  45289. if (Math.abs(result1) < 9.99999997475243E-07) {
  45290. return null;
  45291. }
  45292. else {
  45293. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  45294. distance = (-plane.d - result2) / result1;
  45295. if (distance < 0.0) {
  45296. if (distance < -9.99999997475243E-07) {
  45297. return null;
  45298. }
  45299. else {
  45300. return 0;
  45301. }
  45302. }
  45303. return distance;
  45304. }
  45305. };
  45306. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  45307. var tm = BABYLON.Tmp.Matrix[0];
  45308. mesh.getWorldMatrix().invertToRef(tm);
  45309. if (this._tmpRay) {
  45310. Ray.TransformToRef(this, tm, this._tmpRay);
  45311. }
  45312. else {
  45313. this._tmpRay = Ray.Transform(this, tm);
  45314. }
  45315. return mesh.intersects(this._tmpRay, fastCheck);
  45316. };
  45317. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  45318. if (results) {
  45319. results.length = 0;
  45320. }
  45321. else {
  45322. results = [];
  45323. }
  45324. for (var i = 0; i < meshes.length; i++) {
  45325. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  45326. if (pickInfo.hit) {
  45327. results.push(pickInfo);
  45328. }
  45329. }
  45330. results.sort(this._comparePickingInfo);
  45331. return results;
  45332. };
  45333. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  45334. if (pickingInfoA.distance < pickingInfoB.distance) {
  45335. return -1;
  45336. }
  45337. else if (pickingInfoA.distance > pickingInfoB.distance) {
  45338. return 1;
  45339. }
  45340. else {
  45341. return 0;
  45342. }
  45343. };
  45344. /**
  45345. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  45346. * @param sega the first point of the segment to test the intersection against
  45347. * @param segb the second point of the segment to test the intersection against
  45348. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  45349. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  45350. */
  45351. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  45352. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  45353. var u = segb.subtract(sega);
  45354. var v = rsegb.subtract(this.origin);
  45355. var w = sega.subtract(this.origin);
  45356. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  45357. var b = BABYLON.Vector3.Dot(u, v);
  45358. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  45359. var d = BABYLON.Vector3.Dot(u, w);
  45360. var e = BABYLON.Vector3.Dot(v, w);
  45361. var D = a * c - b * b; // always >= 0
  45362. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  45363. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  45364. // compute the line parameters of the two closest points
  45365. if (D < Ray.smallnum) {
  45366. sN = 0.0; // force using point P0 on segment S1
  45367. sD = 1.0; // to prevent possible division by 0.0 later
  45368. tN = e;
  45369. tD = c;
  45370. }
  45371. else {
  45372. sN = (b * e - c * d);
  45373. tN = (a * e - b * d);
  45374. if (sN < 0.0) {
  45375. sN = 0.0;
  45376. tN = e;
  45377. tD = c;
  45378. }
  45379. else if (sN > sD) {
  45380. sN = sD;
  45381. tN = e + b;
  45382. tD = c;
  45383. }
  45384. }
  45385. if (tN < 0.0) {
  45386. tN = 0.0;
  45387. // recompute sc for this edge
  45388. if (-d < 0.0) {
  45389. sN = 0.0;
  45390. }
  45391. else if (-d > a)
  45392. sN = sD;
  45393. else {
  45394. sN = -d;
  45395. sD = a;
  45396. }
  45397. }
  45398. else if (tN > tD) {
  45399. tN = tD;
  45400. // recompute sc for this edge
  45401. if ((-d + b) < 0.0) {
  45402. sN = 0;
  45403. }
  45404. else if ((-d + b) > a) {
  45405. sN = sD;
  45406. }
  45407. else {
  45408. sN = (-d + b);
  45409. sD = a;
  45410. }
  45411. }
  45412. // finally do the division to get sc and tc
  45413. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  45414. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  45415. // get the difference of the two closest points
  45416. var qtc = v.multiplyByFloats(tc, tc, tc);
  45417. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  45418. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  45419. if (isIntersected) {
  45420. return qtc.length();
  45421. }
  45422. return -1;
  45423. };
  45424. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45425. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  45426. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  45427. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  45428. this.direction.normalize();
  45429. return this;
  45430. };
  45431. // Statics
  45432. Ray.Zero = function () {
  45433. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  45434. };
  45435. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  45436. var result = Ray.Zero();
  45437. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  45438. };
  45439. /**
  45440. * 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
  45441. * transformed to the given world matrix.
  45442. * @param origin The origin point
  45443. * @param end The end point
  45444. * @param world a matrix to transform the ray to. Default is the identity matrix.
  45445. */
  45446. Ray.CreateNewFromTo = function (origin, end, world) {
  45447. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  45448. var direction = end.subtract(origin);
  45449. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  45450. direction.normalize();
  45451. return Ray.Transform(new Ray(origin, direction, length), world);
  45452. };
  45453. Ray.Transform = function (ray, matrix) {
  45454. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  45455. Ray.TransformToRef(ray, matrix, result);
  45456. return result;
  45457. };
  45458. Ray.TransformToRef = function (ray, matrix, result) {
  45459. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  45460. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  45461. result.length = ray.length;
  45462. var dir = result.direction;
  45463. var len = dir.length();
  45464. if (!(len === 0 || len === 1)) {
  45465. var num = 1.0 / len;
  45466. dir.x *= num;
  45467. dir.y *= num;
  45468. dir.z *= num;
  45469. result.length *= len;
  45470. }
  45471. };
  45472. Ray.smallnum = 0.00000001;
  45473. Ray.rayl = 10e8;
  45474. return Ray;
  45475. }());
  45476. BABYLON.Ray = Ray;
  45477. })(BABYLON || (BABYLON = {}));
  45478. //# sourceMappingURL=babylon.ray.js.map
  45479. var BABYLON;
  45480. (function (BABYLON) {
  45481. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  45482. if (boxMin.x > sphereCenter.x + sphereRadius)
  45483. return false;
  45484. if (sphereCenter.x - sphereRadius > boxMax.x)
  45485. return false;
  45486. if (boxMin.y > sphereCenter.y + sphereRadius)
  45487. return false;
  45488. if (sphereCenter.y - sphereRadius > boxMax.y)
  45489. return false;
  45490. if (boxMin.z > sphereCenter.z + sphereRadius)
  45491. return false;
  45492. if (sphereCenter.z - sphereRadius > boxMax.z)
  45493. return false;
  45494. return true;
  45495. };
  45496. var getLowestRoot = (function () {
  45497. var result = { root: 0, found: false };
  45498. return function (a, b, c, maxR) {
  45499. result.root = 0;
  45500. result.found = false;
  45501. var determinant = b * b - 4.0 * a * c;
  45502. if (determinant < 0)
  45503. return result;
  45504. var sqrtD = Math.sqrt(determinant);
  45505. var r1 = (-b - sqrtD) / (2.0 * a);
  45506. var r2 = (-b + sqrtD) / (2.0 * a);
  45507. if (r1 > r2) {
  45508. var temp = r2;
  45509. r2 = r1;
  45510. r1 = temp;
  45511. }
  45512. if (r1 > 0 && r1 < maxR) {
  45513. result.root = r1;
  45514. result.found = true;
  45515. return result;
  45516. }
  45517. if (r2 > 0 && r2 < maxR) {
  45518. result.root = r2;
  45519. result.found = true;
  45520. return result;
  45521. }
  45522. return result;
  45523. };
  45524. })();
  45525. var Collider = /** @class */ (function () {
  45526. function Collider() {
  45527. this._collisionPoint = BABYLON.Vector3.Zero();
  45528. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45529. this._tempVector = BABYLON.Vector3.Zero();
  45530. this._tempVector2 = BABYLON.Vector3.Zero();
  45531. this._tempVector3 = BABYLON.Vector3.Zero();
  45532. this._tempVector4 = BABYLON.Vector3.Zero();
  45533. this._edge = BABYLON.Vector3.Zero();
  45534. this._baseToVertex = BABYLON.Vector3.Zero();
  45535. this._destinationPoint = BABYLON.Vector3.Zero();
  45536. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45537. this._displacementVector = BABYLON.Vector3.Zero();
  45538. this._radius = BABYLON.Vector3.One();
  45539. this._retry = 0;
  45540. this._basePointWorld = BABYLON.Vector3.Zero();
  45541. this._velocityWorld = BABYLON.Vector3.Zero();
  45542. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45543. this._collisionMask = -1;
  45544. }
  45545. Object.defineProperty(Collider.prototype, "collisionMask", {
  45546. get: function () {
  45547. return this._collisionMask;
  45548. },
  45549. set: function (mask) {
  45550. this._collisionMask = !isNaN(mask) ? mask : -1;
  45551. },
  45552. enumerable: true,
  45553. configurable: true
  45554. });
  45555. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45556. /**
  45557. * Gets the plane normal used to compute the sliding response (in local space)
  45558. */
  45559. get: function () {
  45560. return this._slidePlaneNormal;
  45561. },
  45562. enumerable: true,
  45563. configurable: true
  45564. });
  45565. // Methods
  45566. Collider.prototype._initialize = function (source, dir, e) {
  45567. this._velocity = dir;
  45568. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45569. this._basePoint = source;
  45570. source.multiplyToRef(this._radius, this._basePointWorld);
  45571. dir.multiplyToRef(this._radius, this._velocityWorld);
  45572. this._velocityWorldLength = this._velocityWorld.length();
  45573. this._epsilon = e;
  45574. this.collisionFound = false;
  45575. };
  45576. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45577. pa.subtractToRef(point, this._tempVector);
  45578. pb.subtractToRef(point, this._tempVector2);
  45579. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45580. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45581. if (d < 0)
  45582. return false;
  45583. pc.subtractToRef(point, this._tempVector3);
  45584. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45585. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45586. if (d < 0)
  45587. return false;
  45588. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45589. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45590. return d >= 0;
  45591. };
  45592. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45593. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45594. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45595. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45596. return false;
  45597. }
  45598. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45599. return false;
  45600. return true;
  45601. };
  45602. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45603. var t0;
  45604. var embeddedInPlane = false;
  45605. //defensive programming, actually not needed.
  45606. if (!trianglePlaneArray) {
  45607. trianglePlaneArray = [];
  45608. }
  45609. if (!trianglePlaneArray[faceIndex]) {
  45610. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45611. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45612. }
  45613. var trianglePlane = trianglePlaneArray[faceIndex];
  45614. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45615. return;
  45616. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45617. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45618. if (normalDotVelocity == 0) {
  45619. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45620. return;
  45621. embeddedInPlane = true;
  45622. t0 = 0;
  45623. }
  45624. else {
  45625. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45626. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45627. if (t0 > t1) {
  45628. var temp = t1;
  45629. t1 = t0;
  45630. t0 = temp;
  45631. }
  45632. if (t0 > 1.0 || t1 < 0.0)
  45633. return;
  45634. if (t0 < 0)
  45635. t0 = 0;
  45636. if (t0 > 1.0)
  45637. t0 = 1.0;
  45638. }
  45639. this._collisionPoint.copyFromFloats(0, 0, 0);
  45640. var found = false;
  45641. var t = 1.0;
  45642. if (!embeddedInPlane) {
  45643. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45644. this._velocity.scaleToRef(t0, this._tempVector);
  45645. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45646. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45647. found = true;
  45648. t = t0;
  45649. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45650. }
  45651. }
  45652. if (!found) {
  45653. var velocitySquaredLength = this._velocity.lengthSquared();
  45654. var a = velocitySquaredLength;
  45655. this._basePoint.subtractToRef(p1, this._tempVector);
  45656. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45657. var c = this._tempVector.lengthSquared() - 1.0;
  45658. var lowestRoot = getLowestRoot(a, b, c, t);
  45659. if (lowestRoot.found) {
  45660. t = lowestRoot.root;
  45661. found = true;
  45662. this._collisionPoint.copyFrom(p1);
  45663. }
  45664. this._basePoint.subtractToRef(p2, this._tempVector);
  45665. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45666. c = this._tempVector.lengthSquared() - 1.0;
  45667. lowestRoot = getLowestRoot(a, b, c, t);
  45668. if (lowestRoot.found) {
  45669. t = lowestRoot.root;
  45670. found = true;
  45671. this._collisionPoint.copyFrom(p2);
  45672. }
  45673. this._basePoint.subtractToRef(p3, this._tempVector);
  45674. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45675. c = this._tempVector.lengthSquared() - 1.0;
  45676. lowestRoot = getLowestRoot(a, b, c, t);
  45677. if (lowestRoot.found) {
  45678. t = lowestRoot.root;
  45679. found = true;
  45680. this._collisionPoint.copyFrom(p3);
  45681. }
  45682. p2.subtractToRef(p1, this._edge);
  45683. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45684. var edgeSquaredLength = this._edge.lengthSquared();
  45685. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45686. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45687. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45688. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45689. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45690. lowestRoot = getLowestRoot(a, b, c, t);
  45691. if (lowestRoot.found) {
  45692. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45693. if (f >= 0.0 && f <= 1.0) {
  45694. t = lowestRoot.root;
  45695. found = true;
  45696. this._edge.scaleInPlace(f);
  45697. p1.addToRef(this._edge, this._collisionPoint);
  45698. }
  45699. }
  45700. p3.subtractToRef(p2, this._edge);
  45701. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45702. edgeSquaredLength = this._edge.lengthSquared();
  45703. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45704. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45705. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45706. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45707. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45708. lowestRoot = getLowestRoot(a, b, c, t);
  45709. if (lowestRoot.found) {
  45710. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45711. if (f >= 0.0 && f <= 1.0) {
  45712. t = lowestRoot.root;
  45713. found = true;
  45714. this._edge.scaleInPlace(f);
  45715. p2.addToRef(this._edge, this._collisionPoint);
  45716. }
  45717. }
  45718. p1.subtractToRef(p3, this._edge);
  45719. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45720. edgeSquaredLength = this._edge.lengthSquared();
  45721. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45722. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45723. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45724. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45725. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45726. lowestRoot = getLowestRoot(a, b, c, t);
  45727. if (lowestRoot.found) {
  45728. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45729. if (f >= 0.0 && f <= 1.0) {
  45730. t = lowestRoot.root;
  45731. found = true;
  45732. this._edge.scaleInPlace(f);
  45733. p3.addToRef(this._edge, this._collisionPoint);
  45734. }
  45735. }
  45736. }
  45737. if (found) {
  45738. var distToCollision = t * this._velocity.length();
  45739. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45740. if (!this.intersectionPoint) {
  45741. this.intersectionPoint = this._collisionPoint.clone();
  45742. }
  45743. else {
  45744. this.intersectionPoint.copyFrom(this._collisionPoint);
  45745. }
  45746. this._nearestDistance = distToCollision;
  45747. this.collisionFound = true;
  45748. }
  45749. }
  45750. };
  45751. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45752. for (var i = indexStart; i < indexEnd; i += 3) {
  45753. var p1 = pts[indices[i] - decal];
  45754. var p2 = pts[indices[i + 1] - decal];
  45755. var p3 = pts[indices[i + 2] - decal];
  45756. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45757. }
  45758. };
  45759. Collider.prototype._getResponse = function (pos, vel) {
  45760. pos.addToRef(vel, this._destinationPoint);
  45761. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45762. this._basePoint.addToRef(vel, pos);
  45763. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45764. this._slidePlaneNormal.normalize();
  45765. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45766. pos.addInPlace(this._displacementVector);
  45767. this.intersectionPoint.addInPlace(this._displacementVector);
  45768. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45769. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45770. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45771. };
  45772. return Collider;
  45773. }());
  45774. BABYLON.Collider = Collider;
  45775. })(BABYLON || (BABYLON = {}));
  45776. //# sourceMappingURL=babylon.collider.js.map
  45777. var BABYLON;
  45778. (function (BABYLON) {
  45779. //WebWorker code will be inserted to this variable.
  45780. BABYLON.CollisionWorker = "";
  45781. var WorkerTaskType;
  45782. (function (WorkerTaskType) {
  45783. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45784. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45785. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45786. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45787. var WorkerReplyType;
  45788. (function (WorkerReplyType) {
  45789. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45790. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45791. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45792. var CollisionCoordinatorWorker = /** @class */ (function () {
  45793. function CollisionCoordinatorWorker() {
  45794. var _this = this;
  45795. this._scaledPosition = BABYLON.Vector3.Zero();
  45796. this._scaledVelocity = BABYLON.Vector3.Zero();
  45797. this.onMeshUpdated = function (transformNode) {
  45798. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45799. };
  45800. this.onGeometryUpdated = function (geometry) {
  45801. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45802. };
  45803. this._afterRender = function () {
  45804. if (!_this._init)
  45805. return;
  45806. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45807. return;
  45808. }
  45809. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45810. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45811. if (_this._runningUpdated > 4) {
  45812. return;
  45813. }
  45814. ++_this._runningUpdated;
  45815. var payload = {
  45816. updatedMeshes: _this._addUpdateMeshesList,
  45817. updatedGeometries: _this._addUpdateGeometriesList,
  45818. removedGeometries: _this._toRemoveGeometryArray,
  45819. removedMeshes: _this._toRemoveMeshesArray
  45820. };
  45821. var message = {
  45822. payload: payload,
  45823. taskType: WorkerTaskType.UPDATE
  45824. };
  45825. var serializable = [];
  45826. for (var id in payload.updatedGeometries) {
  45827. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45828. //prepare transferables
  45829. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45830. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45831. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45832. }
  45833. }
  45834. _this._worker.postMessage(message, serializable);
  45835. _this._addUpdateMeshesList = {};
  45836. _this._addUpdateGeometriesList = {};
  45837. _this._toRemoveGeometryArray = [];
  45838. _this._toRemoveMeshesArray = [];
  45839. };
  45840. this._onMessageFromWorker = function (e) {
  45841. var returnData = e.data;
  45842. if (returnData.error != WorkerReplyType.SUCCESS) {
  45843. //TODO what errors can be returned from the worker?
  45844. BABYLON.Tools.Warn("error returned from worker!");
  45845. return;
  45846. }
  45847. switch (returnData.taskType) {
  45848. case WorkerTaskType.INIT:
  45849. _this._init = true;
  45850. //Update the worked with ALL of the scene's current state
  45851. _this._scene.meshes.forEach(function (mesh) {
  45852. _this.onMeshAdded(mesh);
  45853. });
  45854. _this._scene.getGeometries().forEach(function (geometry) {
  45855. _this.onGeometryAdded(geometry);
  45856. });
  45857. break;
  45858. case WorkerTaskType.UPDATE:
  45859. _this._runningUpdated--;
  45860. break;
  45861. case WorkerTaskType.COLLIDE:
  45862. var returnPayload = returnData.payload;
  45863. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45864. return;
  45865. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45866. if (callback) {
  45867. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45868. if (mesh) {
  45869. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45870. }
  45871. }
  45872. //cleanup
  45873. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45874. break;
  45875. }
  45876. };
  45877. this._collisionsCallbackArray = [];
  45878. this._init = false;
  45879. this._runningUpdated = 0;
  45880. this._addUpdateMeshesList = {};
  45881. this._addUpdateGeometriesList = {};
  45882. this._toRemoveGeometryArray = [];
  45883. this._toRemoveMeshesArray = [];
  45884. }
  45885. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45886. if (!this._init)
  45887. return;
  45888. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45889. return;
  45890. position.divideToRef(collider._radius, this._scaledPosition);
  45891. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45892. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45893. var payload = {
  45894. collider: {
  45895. position: this._scaledPosition.asArray(),
  45896. velocity: this._scaledVelocity.asArray(),
  45897. radius: collider._radius.asArray()
  45898. },
  45899. collisionId: collisionIndex,
  45900. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45901. maximumRetry: maximumRetry
  45902. };
  45903. var message = {
  45904. payload: payload,
  45905. taskType: WorkerTaskType.COLLIDE
  45906. };
  45907. this._worker.postMessage(message);
  45908. };
  45909. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45910. this._scene = scene;
  45911. this._scene.registerAfterRender(this._afterRender);
  45912. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45913. this._worker = new Worker(workerUrl);
  45914. this._worker.onmessage = this._onMessageFromWorker;
  45915. var message = {
  45916. payload: {},
  45917. taskType: WorkerTaskType.INIT
  45918. };
  45919. this._worker.postMessage(message);
  45920. };
  45921. CollisionCoordinatorWorker.prototype.destroy = function () {
  45922. this._scene.unregisterAfterRender(this._afterRender);
  45923. this._worker.terminate();
  45924. };
  45925. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45926. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45927. this.onMeshUpdated(mesh);
  45928. };
  45929. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45930. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45931. };
  45932. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45933. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45934. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45935. this.onGeometryUpdated(geometry);
  45936. };
  45937. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45938. this._toRemoveGeometryArray.push(geometry.id);
  45939. };
  45940. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45941. var submeshes = [];
  45942. if (mesh.subMeshes) {
  45943. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45944. var boundingInfo = sm.getBoundingInfo();
  45945. return {
  45946. position: idx,
  45947. verticesStart: sm.verticesStart,
  45948. verticesCount: sm.verticesCount,
  45949. indexStart: sm.indexStart,
  45950. indexCount: sm.indexCount,
  45951. hasMaterial: !!sm.getMaterial(),
  45952. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45953. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45954. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45955. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45956. };
  45957. });
  45958. }
  45959. var geometryId = null;
  45960. if (mesh instanceof BABYLON.Mesh) {
  45961. var geometry = mesh.geometry;
  45962. geometryId = geometry ? geometry.id : null;
  45963. }
  45964. else if (mesh instanceof BABYLON.InstancedMesh) {
  45965. var geometry = mesh.sourceMesh.geometry;
  45966. geometryId = geometry ? geometry.id : null;
  45967. }
  45968. var boundingInfo = mesh.getBoundingInfo();
  45969. return {
  45970. uniqueId: mesh.uniqueId,
  45971. id: mesh.id,
  45972. name: mesh.name,
  45973. geometryId: geometryId,
  45974. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45975. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45976. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45977. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45978. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45979. subMeshes: submeshes,
  45980. checkCollisions: mesh.checkCollisions
  45981. };
  45982. };
  45983. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45984. return {
  45985. id: geometry.id,
  45986. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45987. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  45988. indices: new Uint32Array(geometry.getIndices() || []),
  45989. };
  45990. };
  45991. return CollisionCoordinatorWorker;
  45992. }());
  45993. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  45994. var CollisionCoordinatorLegacy = /** @class */ (function () {
  45995. function CollisionCoordinatorLegacy() {
  45996. this._scaledPosition = BABYLON.Vector3.Zero();
  45997. this._scaledVelocity = BABYLON.Vector3.Zero();
  45998. this._finalPosition = BABYLON.Vector3.Zero();
  45999. }
  46000. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  46001. position.divideToRef(collider._radius, this._scaledPosition);
  46002. displacement.divideToRef(collider._radius, this._scaledVelocity);
  46003. collider.collidedMesh = null;
  46004. collider._retry = 0;
  46005. collider._initialVelocity = this._scaledVelocity;
  46006. collider._initialPosition = this._scaledPosition;
  46007. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  46008. this._finalPosition.multiplyInPlace(collider._radius);
  46009. //run the callback
  46010. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  46011. };
  46012. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  46013. this._scene = scene;
  46014. };
  46015. CollisionCoordinatorLegacy.prototype.destroy = function () {
  46016. //Legacy need no destruction method.
  46017. };
  46018. //No update in legacy mode
  46019. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  46020. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  46021. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  46022. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  46023. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  46024. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  46025. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  46026. if (excludedMesh === void 0) { excludedMesh = null; }
  46027. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  46028. if (collider._retry >= maximumRetry) {
  46029. finalPosition.copyFrom(position);
  46030. return;
  46031. }
  46032. // Check if this is a mesh else camera or -1
  46033. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  46034. collider._initialize(position, velocity, closeDistance);
  46035. // Check all meshes
  46036. for (var index = 0; index < this._scene.meshes.length; index++) {
  46037. var mesh = this._scene.meshes[index];
  46038. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  46039. mesh._checkCollision(collider);
  46040. }
  46041. }
  46042. if (!collider.collisionFound) {
  46043. position.addToRef(velocity, finalPosition);
  46044. return;
  46045. }
  46046. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  46047. collider._getResponse(position, velocity);
  46048. }
  46049. if (velocity.length() <= closeDistance) {
  46050. finalPosition.copyFrom(position);
  46051. return;
  46052. }
  46053. collider._retry++;
  46054. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  46055. };
  46056. return CollisionCoordinatorLegacy;
  46057. }());
  46058. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  46059. })(BABYLON || (BABYLON = {}));
  46060. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  46061. var BABYLON;
  46062. (function (BABYLON) {
  46063. var Particle = /** @class */ (function () {
  46064. function Particle(particleSystem) {
  46065. this.particleSystem = particleSystem;
  46066. this.position = BABYLON.Vector3.Zero();
  46067. this.direction = BABYLON.Vector3.Zero();
  46068. this.color = new BABYLON.Color4(0, 0, 0, 0);
  46069. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  46070. this.lifeTime = 1.0;
  46071. this.age = 0;
  46072. this.size = 0;
  46073. this.angle = 0;
  46074. this.angularSpeed = 0;
  46075. this._currentFrameCounter = 0;
  46076. this.cellIndex = 0;
  46077. if (!this.particleSystem.isAnimationSheetEnabled) {
  46078. return;
  46079. }
  46080. this.cellIndex = this.particleSystem.startSpriteCellID;
  46081. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  46082. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  46083. }
  46084. else {
  46085. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  46086. }
  46087. }
  46088. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  46089. // (ageOffset / scaledUpdateSpeed) / available cells
  46090. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  46091. this._currentFrameCounter += scaledUpdateSpeed;
  46092. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  46093. this._currentFrameCounter = 0;
  46094. this.cellIndex++;
  46095. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46096. this.cellIndex = this.particleSystem.endSpriteCellID;
  46097. }
  46098. }
  46099. };
  46100. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  46101. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  46102. this.cellIndex++;
  46103. this._currentFrameCounter = 0;
  46104. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  46105. if (this.particleSystem.spriteCellLoop) {
  46106. this.cellIndex = this.particleSystem.startSpriteCellID;
  46107. }
  46108. else {
  46109. this.cellIndex = this.particleSystem.endSpriteCellID;
  46110. }
  46111. }
  46112. }
  46113. else {
  46114. this._currentFrameCounter++;
  46115. }
  46116. };
  46117. Particle.prototype.copyTo = function (other) {
  46118. other.position.copyFrom(this.position);
  46119. other.direction.copyFrom(this.direction);
  46120. other.color.copyFrom(this.color);
  46121. other.colorStep.copyFrom(this.colorStep);
  46122. other.lifeTime = this.lifeTime;
  46123. other.age = this.age;
  46124. other.size = this.size;
  46125. other.angle = this.angle;
  46126. other.angularSpeed = this.angularSpeed;
  46127. other.particleSystem = this.particleSystem;
  46128. other.cellIndex = this.cellIndex;
  46129. };
  46130. return Particle;
  46131. }());
  46132. BABYLON.Particle = Particle;
  46133. })(BABYLON || (BABYLON = {}));
  46134. //# sourceMappingURL=babylon.particle.js.map
  46135. var BABYLON;
  46136. (function (BABYLON) {
  46137. var ParticleSystem = /** @class */ (function () {
  46138. // end of sheet animation
  46139. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  46140. if (customEffect === void 0) { customEffect = null; }
  46141. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  46142. if (epsilon === void 0) { epsilon = 0.01; }
  46143. var _this = this;
  46144. this.name = name;
  46145. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  46146. // Members
  46147. this.animations = [];
  46148. this.renderingGroupId = 0;
  46149. this.emitter = null;
  46150. this.emitRate = 10;
  46151. this.manualEmitCount = -1;
  46152. this.updateSpeed = 0.01;
  46153. this.targetStopDuration = 0;
  46154. this.disposeOnStop = false;
  46155. this.minEmitPower = 1;
  46156. this.maxEmitPower = 1;
  46157. this.minLifeTime = 1;
  46158. this.maxLifeTime = 1;
  46159. this.minSize = 1;
  46160. this.maxSize = 1;
  46161. this.minAngularSpeed = 0;
  46162. this.maxAngularSpeed = 0;
  46163. this.layerMask = 0x0FFFFFFF;
  46164. this.customShader = null;
  46165. this.preventAutoStart = false;
  46166. /**
  46167. * An event triggered when the system is disposed.
  46168. * @type {BABYLON.Observable}
  46169. */
  46170. this.onDisposeObservable = new BABYLON.Observable();
  46171. this.onAnimationEnd = null;
  46172. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  46173. this.forceDepthWrite = false;
  46174. this.gravity = BABYLON.Vector3.Zero();
  46175. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  46176. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  46177. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  46178. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  46179. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46180. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46181. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  46182. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  46183. this.particles = new Array();
  46184. this._stockParticles = new Array();
  46185. this._newPartsExcess = 0;
  46186. this._vertexBuffers = {};
  46187. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  46188. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  46189. this._scaledDirection = BABYLON.Vector3.Zero();
  46190. this._scaledGravity = BABYLON.Vector3.Zero();
  46191. this._currentRenderId = -1;
  46192. this._started = false;
  46193. this._stopped = false;
  46194. this._actualFrame = 0;
  46195. // sheet animation
  46196. this.startSpriteCellID = 0;
  46197. this.endSpriteCellID = 0;
  46198. this.spriteCellLoop = true;
  46199. this.spriteCellChangeSpeed = 0;
  46200. this.spriteCellWidth = 0;
  46201. this.spriteCellHeight = 0;
  46202. this._vertexBufferSize = 11;
  46203. this.appendParticleVertexes = null;
  46204. this.id = name;
  46205. this._capacity = capacity;
  46206. this._epsilon = epsilon;
  46207. if (_isAnimationSheetEnabled) {
  46208. this._vertexBufferSize = 12;
  46209. }
  46210. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46211. this._customEffect = customEffect;
  46212. scene.particleSystems.push(this);
  46213. this._createIndexBuffer();
  46214. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  46215. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  46216. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  46217. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  46218. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  46219. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  46220. if (this._isAnimationSheetEnabled) {
  46221. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  46222. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  46223. }
  46224. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  46225. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  46226. this._vertexBuffers["options"] = options;
  46227. // Default behaviors
  46228. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  46229. this.updateFunction = function (particles) {
  46230. for (var index = 0; index < particles.length; index++) {
  46231. var particle = particles[index];
  46232. particle.age += _this._scaledUpdateSpeed;
  46233. if (particle.age >= particle.lifeTime) {
  46234. _this.recycleParticle(particle);
  46235. index--;
  46236. continue;
  46237. }
  46238. else {
  46239. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  46240. particle.color.addInPlace(_this._scaledColorStep);
  46241. if (particle.color.a < 0)
  46242. particle.color.a = 0;
  46243. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  46244. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  46245. particle.position.addInPlace(_this._scaledDirection);
  46246. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  46247. particle.direction.addInPlace(_this._scaledGravity);
  46248. if (_this._isAnimationSheetEnabled) {
  46249. particle.updateCellIndex(_this._scaledUpdateSpeed);
  46250. }
  46251. }
  46252. }
  46253. };
  46254. }
  46255. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  46256. set: function (callback) {
  46257. if (this._onDisposeObserver) {
  46258. this.onDisposeObservable.remove(this._onDisposeObserver);
  46259. }
  46260. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  46261. },
  46262. enumerable: true,
  46263. configurable: true
  46264. });
  46265. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  46266. get: function () {
  46267. return this._isAnimationSheetEnabled;
  46268. },
  46269. enumerable: true,
  46270. configurable: true
  46271. });
  46272. ParticleSystem.prototype._createIndexBuffer = function () {
  46273. var indices = [];
  46274. var index = 0;
  46275. for (var count = 0; count < this._capacity; count++) {
  46276. indices.push(index);
  46277. indices.push(index + 1);
  46278. indices.push(index + 2);
  46279. indices.push(index);
  46280. indices.push(index + 2);
  46281. indices.push(index + 3);
  46282. index += 4;
  46283. }
  46284. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  46285. };
  46286. ParticleSystem.prototype.recycleParticle = function (particle) {
  46287. var lastParticle = this.particles.pop();
  46288. if (lastParticle !== particle) {
  46289. lastParticle.copyTo(particle);
  46290. this._stockParticles.push(lastParticle);
  46291. }
  46292. };
  46293. ParticleSystem.prototype.getCapacity = function () {
  46294. return this._capacity;
  46295. };
  46296. ParticleSystem.prototype.isAlive = function () {
  46297. return this._alive;
  46298. };
  46299. ParticleSystem.prototype.isStarted = function () {
  46300. return this._started;
  46301. };
  46302. ParticleSystem.prototype.start = function () {
  46303. this._started = true;
  46304. this._stopped = false;
  46305. this._actualFrame = 0;
  46306. };
  46307. ParticleSystem.prototype.stop = function () {
  46308. this._stopped = true;
  46309. };
  46310. // animation sheet
  46311. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  46312. var offset = index * this._vertexBufferSize;
  46313. this._vertexData[offset] = particle.position.x;
  46314. this._vertexData[offset + 1] = particle.position.y;
  46315. this._vertexData[offset + 2] = particle.position.z;
  46316. this._vertexData[offset + 3] = particle.color.r;
  46317. this._vertexData[offset + 4] = particle.color.g;
  46318. this._vertexData[offset + 5] = particle.color.b;
  46319. this._vertexData[offset + 6] = particle.color.a;
  46320. this._vertexData[offset + 7] = particle.angle;
  46321. this._vertexData[offset + 8] = particle.size;
  46322. this._vertexData[offset + 9] = offsetX;
  46323. this._vertexData[offset + 10] = offsetY;
  46324. };
  46325. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  46326. if (offsetX === 0)
  46327. offsetX = this._epsilon;
  46328. else if (offsetX === 1)
  46329. offsetX = 1 - this._epsilon;
  46330. if (offsetY === 0)
  46331. offsetY = this._epsilon;
  46332. else if (offsetY === 1)
  46333. offsetY = 1 - this._epsilon;
  46334. var offset = index * this._vertexBufferSize;
  46335. this._vertexData[offset] = particle.position.x;
  46336. this._vertexData[offset + 1] = particle.position.y;
  46337. this._vertexData[offset + 2] = particle.position.z;
  46338. this._vertexData[offset + 3] = particle.color.r;
  46339. this._vertexData[offset + 4] = particle.color.g;
  46340. this._vertexData[offset + 5] = particle.color.b;
  46341. this._vertexData[offset + 6] = particle.color.a;
  46342. this._vertexData[offset + 7] = particle.angle;
  46343. this._vertexData[offset + 8] = particle.size;
  46344. this._vertexData[offset + 9] = offsetX;
  46345. this._vertexData[offset + 10] = offsetY;
  46346. this._vertexData[offset + 11] = particle.cellIndex;
  46347. };
  46348. ParticleSystem.prototype._update = function (newParticles) {
  46349. // Update current
  46350. this._alive = this.particles.length > 0;
  46351. this.updateFunction(this.particles);
  46352. // Add new ones
  46353. var worldMatrix;
  46354. if (this.emitter.position) {
  46355. var emitterMesh = this.emitter;
  46356. worldMatrix = emitterMesh.getWorldMatrix();
  46357. }
  46358. else {
  46359. var emitterPosition = this.emitter;
  46360. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  46361. }
  46362. var particle;
  46363. for (var index = 0; index < newParticles; index++) {
  46364. if (this.particles.length === this._capacity) {
  46365. break;
  46366. }
  46367. if (this._stockParticles.length !== 0) {
  46368. particle = this._stockParticles.pop();
  46369. particle.age = 0;
  46370. particle.cellIndex = this.startSpriteCellID;
  46371. }
  46372. else {
  46373. particle = new BABYLON.Particle(this);
  46374. }
  46375. this.particles.push(particle);
  46376. var emitPower = ParticleSystem.randomNumber(this.minEmitPower, this.maxEmitPower);
  46377. if (this.startDirectionFunction) {
  46378. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46379. }
  46380. else {
  46381. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  46382. }
  46383. if (this.startPositionFunction) {
  46384. this.startPositionFunction(worldMatrix, particle.position, particle);
  46385. }
  46386. else {
  46387. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  46388. }
  46389. particle.lifeTime = ParticleSystem.randomNumber(this.minLifeTime, this.maxLifeTime);
  46390. particle.size = ParticleSystem.randomNumber(this.minSize, this.maxSize);
  46391. particle.angularSpeed = ParticleSystem.randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  46392. var step = ParticleSystem.randomNumber(0, 1.0);
  46393. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  46394. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  46395. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  46396. }
  46397. };
  46398. ParticleSystem.prototype._getEffect = function () {
  46399. if (this._customEffect) {
  46400. return this._customEffect;
  46401. }
  46402. ;
  46403. var defines = [];
  46404. if (this._scene.clipPlane) {
  46405. defines.push("#define CLIPPLANE");
  46406. }
  46407. if (this._isAnimationSheetEnabled) {
  46408. defines.push("#define ANIMATESHEET");
  46409. }
  46410. // Effect
  46411. var join = defines.join("\n");
  46412. if (this._cachedDefines !== join) {
  46413. this._cachedDefines = join;
  46414. var attributesNamesOrOptions;
  46415. var effectCreationOption;
  46416. if (this._isAnimationSheetEnabled) {
  46417. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  46418. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  46419. }
  46420. else {
  46421. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  46422. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  46423. }
  46424. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  46425. }
  46426. return this._effect;
  46427. };
  46428. ParticleSystem.prototype.animate = function () {
  46429. if (!this._started)
  46430. return;
  46431. var effect = this._getEffect();
  46432. // Check
  46433. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  46434. return;
  46435. if (this._currentRenderId === this._scene.getRenderId()) {
  46436. return;
  46437. }
  46438. this._currentRenderId = this._scene.getRenderId();
  46439. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  46440. // determine the number of particles we need to create
  46441. var newParticles;
  46442. if (this.manualEmitCount > -1) {
  46443. newParticles = this.manualEmitCount;
  46444. this._newPartsExcess = 0;
  46445. this.manualEmitCount = 0;
  46446. }
  46447. else {
  46448. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  46449. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  46450. }
  46451. if (this._newPartsExcess > 1.0) {
  46452. newParticles += this._newPartsExcess >> 0;
  46453. this._newPartsExcess -= this._newPartsExcess >> 0;
  46454. }
  46455. this._alive = false;
  46456. if (!this._stopped) {
  46457. this._actualFrame += this._scaledUpdateSpeed;
  46458. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  46459. this.stop();
  46460. }
  46461. else {
  46462. newParticles = 0;
  46463. }
  46464. this._update(newParticles);
  46465. // Stopped?
  46466. if (this._stopped) {
  46467. if (!this._alive) {
  46468. this._started = false;
  46469. if (this.onAnimationEnd) {
  46470. this.onAnimationEnd();
  46471. }
  46472. if (this.disposeOnStop) {
  46473. this._scene._toBeDisposed.push(this);
  46474. }
  46475. }
  46476. }
  46477. // Animation sheet
  46478. if (this._isAnimationSheetEnabled) {
  46479. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  46480. }
  46481. else {
  46482. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  46483. }
  46484. // Update VBO
  46485. var offset = 0;
  46486. for (var index = 0; index < this.particles.length; index++) {
  46487. var particle = this.particles[index];
  46488. this.appendParticleVertexes(offset, particle);
  46489. offset += 4;
  46490. }
  46491. if (this._vertexBuffer) {
  46492. this._vertexBuffer.update(this._vertexData);
  46493. }
  46494. };
  46495. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46496. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46497. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46498. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46499. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46500. };
  46501. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46502. this._appendParticleVertex(offset++, particle, 0, 0);
  46503. this._appendParticleVertex(offset++, particle, 1, 0);
  46504. this._appendParticleVertex(offset++, particle, 1, 1);
  46505. this._appendParticleVertex(offset++, particle, 0, 1);
  46506. };
  46507. ParticleSystem.prototype.rebuild = function () {
  46508. this._createIndexBuffer();
  46509. if (this._vertexBuffer) {
  46510. this._vertexBuffer._rebuild();
  46511. }
  46512. };
  46513. ParticleSystem.prototype.render = function () {
  46514. var effect = this._getEffect();
  46515. // Check
  46516. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46517. return 0;
  46518. var engine = this._scene.getEngine();
  46519. // Render
  46520. engine.enableEffect(effect);
  46521. engine.setState(false);
  46522. var viewMatrix = this._scene.getViewMatrix();
  46523. effect.setTexture("diffuseSampler", this.particleTexture);
  46524. effect.setMatrix("view", viewMatrix);
  46525. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46526. if (this._isAnimationSheetEnabled) {
  46527. var baseSize = this.particleTexture.getBaseSize();
  46528. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46529. }
  46530. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46531. if (this._scene.clipPlane) {
  46532. var clipPlane = this._scene.clipPlane;
  46533. var invView = viewMatrix.clone();
  46534. invView.invert();
  46535. effect.setMatrix("invView", invView);
  46536. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46537. }
  46538. // VBOs
  46539. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46540. // Draw order
  46541. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46542. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46543. }
  46544. else {
  46545. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46546. }
  46547. if (this.forceDepthWrite) {
  46548. engine.setDepthWrite(true);
  46549. }
  46550. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46551. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46552. return this.particles.length;
  46553. };
  46554. ParticleSystem.prototype.dispose = function () {
  46555. if (this._vertexBuffer) {
  46556. this._vertexBuffer.dispose();
  46557. this._vertexBuffer = null;
  46558. }
  46559. if (this._indexBuffer) {
  46560. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46561. this._indexBuffer = null;
  46562. }
  46563. if (this.particleTexture) {
  46564. this.particleTexture.dispose();
  46565. this.particleTexture = null;
  46566. }
  46567. // Remove from scene
  46568. var index = this._scene.particleSystems.indexOf(this);
  46569. if (index > -1) {
  46570. this._scene.particleSystems.splice(index, 1);
  46571. }
  46572. // Callback
  46573. this.onDisposeObservable.notifyObservers(this);
  46574. this.onDisposeObservable.clear();
  46575. };
  46576. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  46577. if (radius === void 0) { radius = 1; }
  46578. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  46579. this.particleEmitterType = particleEmitter;
  46580. return particleEmitter;
  46581. };
  46582. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  46583. if (radius === void 0) { radius = 1; }
  46584. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  46585. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  46586. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  46587. this.particleEmitterType = particleEmitter;
  46588. return particleEmitter;
  46589. };
  46590. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  46591. if (radius === void 0) { radius = 1; }
  46592. if (angle === void 0) { angle = Math.PI / 4; }
  46593. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  46594. this.particleEmitterType = particleEmitter;
  46595. return particleEmitter;
  46596. };
  46597. // 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.
  46598. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  46599. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  46600. this.direction1 = direction1;
  46601. this.direction2 = direction2;
  46602. this.minEmitBox = minEmitBox;
  46603. this.maxEmitBox = maxEmitBox;
  46604. this.particleEmitterType = particleEmitter;
  46605. return particleEmitter;
  46606. };
  46607. ParticleSystem.randomNumber = function (min, max) {
  46608. if (min === max) {
  46609. return (min);
  46610. }
  46611. var random = Math.random();
  46612. return ((random * (max - min)) + min);
  46613. };
  46614. // Clone
  46615. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46616. var custom = null;
  46617. var program = null;
  46618. if (this.customShader != null) {
  46619. program = this.customShader;
  46620. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46621. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46622. }
  46623. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46624. result.customShader = program;
  46625. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46626. if (newEmitter === undefined) {
  46627. newEmitter = this.emitter;
  46628. }
  46629. result.emitter = newEmitter;
  46630. if (this.particleTexture) {
  46631. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46632. }
  46633. if (!this.preventAutoStart) {
  46634. result.start();
  46635. }
  46636. return result;
  46637. };
  46638. ParticleSystem.prototype.serialize = function () {
  46639. var serializationObject = {};
  46640. serializationObject.name = this.name;
  46641. serializationObject.id = this.id;
  46642. // Emitter
  46643. if (this.emitter.position) {
  46644. var emitterMesh = this.emitter;
  46645. serializationObject.emitterId = emitterMesh.id;
  46646. }
  46647. else {
  46648. var emitterPosition = this.emitter;
  46649. serializationObject.emitter = emitterPosition.asArray();
  46650. }
  46651. serializationObject.capacity = this.getCapacity();
  46652. if (this.particleTexture) {
  46653. serializationObject.textureName = this.particleTexture.name;
  46654. }
  46655. // Animations
  46656. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46657. // Particle system
  46658. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46659. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46660. serializationObject.minSize = this.minSize;
  46661. serializationObject.maxSize = this.maxSize;
  46662. serializationObject.minEmitPower = this.minEmitPower;
  46663. serializationObject.maxEmitPower = this.maxEmitPower;
  46664. serializationObject.minLifeTime = this.minLifeTime;
  46665. serializationObject.maxLifeTime = this.maxLifeTime;
  46666. serializationObject.emitRate = this.emitRate;
  46667. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46668. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46669. serializationObject.gravity = this.gravity.asArray();
  46670. serializationObject.direction1 = this.direction1.asArray();
  46671. serializationObject.direction2 = this.direction2.asArray();
  46672. serializationObject.color1 = this.color1.asArray();
  46673. serializationObject.color2 = this.color2.asArray();
  46674. serializationObject.colorDead = this.colorDead.asArray();
  46675. serializationObject.updateSpeed = this.updateSpeed;
  46676. serializationObject.targetStopDuration = this.targetStopDuration;
  46677. serializationObject.textureMask = this.textureMask.asArray();
  46678. serializationObject.blendMode = this.blendMode;
  46679. serializationObject.customShader = this.customShader;
  46680. serializationObject.preventAutoStart = this.preventAutoStart;
  46681. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46682. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46683. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46684. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46685. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46686. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46687. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46688. return serializationObject;
  46689. };
  46690. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46691. var name = parsedParticleSystem.name;
  46692. var custom = null;
  46693. var program = null;
  46694. if (parsedParticleSystem.customShader) {
  46695. program = parsedParticleSystem.customShader;
  46696. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46697. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46698. }
  46699. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46700. particleSystem.customShader = program;
  46701. if (parsedParticleSystem.id) {
  46702. particleSystem.id = parsedParticleSystem.id;
  46703. }
  46704. // Auto start
  46705. if (parsedParticleSystem.preventAutoStart) {
  46706. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46707. }
  46708. // Texture
  46709. if (parsedParticleSystem.textureName) {
  46710. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46711. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46712. }
  46713. // Emitter
  46714. if (parsedParticleSystem.emitterId) {
  46715. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46716. }
  46717. else {
  46718. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46719. }
  46720. // Animations
  46721. if (parsedParticleSystem.animations) {
  46722. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46723. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46724. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46725. }
  46726. }
  46727. if (parsedParticleSystem.autoAnimate) {
  46728. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46729. }
  46730. // Particle system
  46731. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46732. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46733. particleSystem.minSize = parsedParticleSystem.minSize;
  46734. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46735. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46736. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46737. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46738. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46739. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46740. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46741. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46742. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46743. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46744. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46745. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46746. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46747. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46748. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46749. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46750. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46751. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46752. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46753. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46754. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46755. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46756. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46757. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46758. if (!particleSystem.preventAutoStart) {
  46759. particleSystem.start();
  46760. }
  46761. return particleSystem;
  46762. };
  46763. // Statics
  46764. ParticleSystem.BLENDMODE_ONEONE = 0;
  46765. ParticleSystem.BLENDMODE_STANDARD = 1;
  46766. return ParticleSystem;
  46767. }());
  46768. BABYLON.ParticleSystem = ParticleSystem;
  46769. })(BABYLON || (BABYLON = {}));
  46770. //# sourceMappingURL=babylon.particleSystem.js.map
  46771. var BABYLON;
  46772. (function (BABYLON) {
  46773. var BoxParticleEmitter = /** @class */ (function () {
  46774. // to be updated like the rest of emitters when breaking changes.
  46775. // all property should be come public variables and passed through constructor.
  46776. function BoxParticleEmitter(_particleSystem) {
  46777. this._particleSystem = _particleSystem;
  46778. }
  46779. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  46780. get: function () {
  46781. return this._particleSystem.direction1;
  46782. },
  46783. set: function (value) {
  46784. this._particleSystem.direction1 = value;
  46785. },
  46786. enumerable: true,
  46787. configurable: true
  46788. });
  46789. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  46790. get: function () {
  46791. return this._particleSystem.direction2;
  46792. },
  46793. set: function (value) {
  46794. this._particleSystem.direction2 = value;
  46795. },
  46796. enumerable: true,
  46797. configurable: true
  46798. });
  46799. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  46800. get: function () {
  46801. return this._particleSystem.minEmitBox;
  46802. },
  46803. set: function (value) {
  46804. this._particleSystem.minEmitBox = value;
  46805. },
  46806. enumerable: true,
  46807. configurable: true
  46808. });
  46809. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  46810. get: function () {
  46811. return this._particleSystem.maxEmitBox;
  46812. },
  46813. set: function (value) {
  46814. this._particleSystem.maxEmitBox = value;
  46815. },
  46816. enumerable: true,
  46817. configurable: true
  46818. });
  46819. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46820. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46821. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46822. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46823. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46824. };
  46825. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46826. var randX = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.x, this.maxEmitBox.x);
  46827. var randY = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.y, this.maxEmitBox.y);
  46828. var randZ = BABYLON.ParticleSystem.randomNumber(this.minEmitBox.z, this.maxEmitBox.z);
  46829. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46830. };
  46831. return BoxParticleEmitter;
  46832. }());
  46833. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  46834. })(BABYLON || (BABYLON = {}));
  46835. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  46836. var BABYLON;
  46837. (function (BABYLON) {
  46838. var ConeParticleEmitter = /** @class */ (function () {
  46839. function ConeParticleEmitter(radius, angle) {
  46840. this.radius = radius;
  46841. this.angle = angle;
  46842. }
  46843. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46844. if (this.angle === 0) {
  46845. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  46846. }
  46847. else {
  46848. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46849. var theta = BABYLON.ParticleSystem.randomNumber(0, this.angle);
  46850. var randX = Math.cos(phi) * Math.sin(theta);
  46851. var randY = Math.cos(theta);
  46852. var randZ = Math.sin(phi) * Math.sin(theta);
  46853. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46854. }
  46855. };
  46856. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46857. var s = BABYLON.ParticleSystem.randomNumber(0, Math.PI * 2);
  46858. var radius = BABYLON.ParticleSystem.randomNumber(0, this.radius);
  46859. var randX = radius * Math.sin(s);
  46860. var randZ = radius * Math.cos(s);
  46861. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, 0, randZ, worldMatrix, positionToUpdate);
  46862. };
  46863. return ConeParticleEmitter;
  46864. }());
  46865. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  46866. })(BABYLON || (BABYLON = {}));
  46867. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  46868. var BABYLON;
  46869. (function (BABYLON) {
  46870. var SphereParticleEmitter = /** @class */ (function () {
  46871. function SphereParticleEmitter(radius) {
  46872. this.radius = radius;
  46873. }
  46874. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46875. // measure the direction Vector from the emitter to the particle.
  46876. var direction = particle.position.subtract(worldMatrix.getTranslation());
  46877. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  46878. };
  46879. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  46880. var phi = BABYLON.ParticleSystem.randomNumber(0, 2 * Math.PI);
  46881. var theta = BABYLON.ParticleSystem.randomNumber(0, Math.PI);
  46882. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  46883. var randY = this.radius * Math.cos(theta);
  46884. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  46885. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  46886. };
  46887. return SphereParticleEmitter;
  46888. }());
  46889. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  46890. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  46891. __extends(SphereDirectedParticleEmitter, _super);
  46892. function SphereDirectedParticleEmitter(radius, direction1, direction2) {
  46893. var _this = _super.call(this, radius) || this;
  46894. _this.direction1 = direction1;
  46895. _this.direction2 = direction2;
  46896. return _this;
  46897. }
  46898. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  46899. var randX = BABYLON.ParticleSystem.randomNumber(this.direction1.x, this.direction2.x);
  46900. var randY = BABYLON.ParticleSystem.randomNumber(this.direction1.y, this.direction2.y);
  46901. var randZ = BABYLON.ParticleSystem.randomNumber(this.direction1.z, this.direction2.z);
  46902. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  46903. };
  46904. return SphereDirectedParticleEmitter;
  46905. }(SphereParticleEmitter));
  46906. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  46907. })(BABYLON || (BABYLON = {}));
  46908. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  46909. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  46910. var BABYLON;
  46911. (function (BABYLON) {
  46912. var SolidParticle = /** @class */ (function () {
  46913. /**
  46914. * Creates a Solid Particle object.
  46915. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  46916. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  46917. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  46918. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  46919. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  46920. * `shapeId` (integer) is the model shape identifier in the SPS.
  46921. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  46922. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  46923. */
  46924. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  46925. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  46926. this.idx = 0; // particle global index
  46927. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46928. this.position = BABYLON.Vector3.Zero(); // position
  46929. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46930. this.scaling = BABYLON.Vector3.One(); // scaling
  46931. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46932. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46933. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  46934. this.alive = true; // alive
  46935. this.isVisible = true; // visibility
  46936. this._pos = 0; // index of this particle in the global "positions" array
  46937. this._ind = 0; // index of this particle in the global "indices" array
  46938. this.shapeId = 0; // model shape id
  46939. this.idxInShape = 0; // index of the particle in its shape id
  46940. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  46941. this.idx = particleIndex;
  46942. this._pos = positionIndex;
  46943. this._ind = indiceIndex;
  46944. this._model = model;
  46945. this.shapeId = shapeId;
  46946. this.idxInShape = idxInShape;
  46947. this._sps = sps;
  46948. if (modelBoundingInfo) {
  46949. this._modelBoundingInfo = modelBoundingInfo;
  46950. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46951. }
  46952. }
  46953. Object.defineProperty(SolidParticle.prototype, "scale", {
  46954. /**
  46955. * legacy support, changed scale to scaling
  46956. */
  46957. get: function () {
  46958. return this.scaling;
  46959. },
  46960. set: function (scale) {
  46961. this.scaling = scale;
  46962. },
  46963. enumerable: true,
  46964. configurable: true
  46965. });
  46966. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46967. /**
  46968. * legacy support, changed quaternion to rotationQuaternion
  46969. */
  46970. get: function () {
  46971. return this.rotationQuaternion;
  46972. },
  46973. set: function (q) {
  46974. this.rotationQuaternion = q;
  46975. },
  46976. enumerable: true,
  46977. configurable: true
  46978. });
  46979. /**
  46980. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46981. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46982. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46983. */
  46984. SolidParticle.prototype.intersectsMesh = function (target) {
  46985. if (!this._boundingInfo || !target._boundingInfo) {
  46986. return false;
  46987. }
  46988. if (this._sps._bSphereOnly) {
  46989. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  46990. }
  46991. return this._boundingInfo.intersects(target._boundingInfo, false);
  46992. };
  46993. return SolidParticle;
  46994. }());
  46995. BABYLON.SolidParticle = SolidParticle;
  46996. var ModelShape = /** @class */ (function () {
  46997. /**
  46998. * 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.
  46999. * SPS internal tool, don't use it manually.
  47000. */
  47001. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  47002. this._indicesLength = 0; // length of the shape in the model indices array
  47003. this.shapeID = id;
  47004. this._shape = shape;
  47005. this._indicesLength = indicesLength;
  47006. this._shapeUV = shapeUV;
  47007. this._positionFunction = posFunction;
  47008. this._vertexFunction = vtxFunction;
  47009. }
  47010. return ModelShape;
  47011. }());
  47012. BABYLON.ModelShape = ModelShape;
  47013. var DepthSortedParticle = /** @class */ (function () {
  47014. function DepthSortedParticle() {
  47015. this.ind = 0; // index of the particle in the "indices" array
  47016. this.indicesLength = 0; // length of the particle shape in the "indices" array
  47017. this.sqDistance = 0.0; // squared distance from the particle to the camera
  47018. }
  47019. return DepthSortedParticle;
  47020. }());
  47021. BABYLON.DepthSortedParticle = DepthSortedParticle;
  47022. })(BABYLON || (BABYLON = {}));
  47023. //# sourceMappingURL=babylon.solidParticle.js.map
  47024. var BABYLON;
  47025. (function (BABYLON) {
  47026. /**
  47027. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47028. */
  47029. var SolidParticleSystem = /** @class */ (function () {
  47030. /**
  47031. * Creates a SPS (Solid Particle System) object.
  47032. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47033. * `scene` (Scene) is the scene in which the SPS is added.
  47034. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47035. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47036. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  47037. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47038. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47039. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47040. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47041. */
  47042. function SolidParticleSystem(name, scene, options) {
  47043. // public members
  47044. /**
  47045. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47046. * Example : var p = SPS.particles[i];
  47047. */
  47048. this.particles = new Array();
  47049. /**
  47050. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47051. */
  47052. this.nbParticles = 0;
  47053. /**
  47054. * If the particles must ever face the camera (default false). Useful for planar particles.
  47055. */
  47056. this.billboard = false;
  47057. /**
  47058. * Recompute normals when adding a shape
  47059. */
  47060. this.recomputeNormals = true;
  47061. /**
  47062. * This a counter ofr your own usage. It's not set by any SPS functions.
  47063. */
  47064. this.counter = 0;
  47065. /**
  47066. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47067. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47068. */
  47069. this.vars = {};
  47070. this._positions = new Array();
  47071. this._indices = new Array();
  47072. this._normals = new Array();
  47073. this._colors = new Array();
  47074. this._uvs = new Array();
  47075. this._index = 0; // indices index
  47076. this._updatable = true;
  47077. this._pickable = false;
  47078. this._isVisibilityBoxLocked = false;
  47079. this._alwaysVisible = false;
  47080. this._depthSort = false;
  47081. this._shapeCounter = 0;
  47082. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  47083. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47084. this._computeParticleColor = true;
  47085. this._computeParticleTexture = true;
  47086. this._computeParticleRotation = true;
  47087. this._computeParticleVertex = false;
  47088. this._computeBoundingBox = false;
  47089. this._depthSortParticles = true;
  47090. this._cam_axisZ = BABYLON.Vector3.Zero();
  47091. this._cam_axisY = BABYLON.Vector3.Zero();
  47092. this._cam_axisX = BABYLON.Vector3.Zero();
  47093. this._axisZ = BABYLON.Axis.Z;
  47094. this._camDir = BABYLON.Vector3.Zero();
  47095. this._camInvertedPosition = BABYLON.Vector3.Zero();
  47096. this._rotMatrix = new BABYLON.Matrix();
  47097. this._invertMatrix = new BABYLON.Matrix();
  47098. this._rotated = BABYLON.Vector3.Zero();
  47099. this._quaternion = new BABYLON.Quaternion();
  47100. this._vertex = BABYLON.Vector3.Zero();
  47101. this._normal = BABYLON.Vector3.Zero();
  47102. this._yaw = 0.0;
  47103. this._pitch = 0.0;
  47104. this._roll = 0.0;
  47105. this._halfroll = 0.0;
  47106. this._halfpitch = 0.0;
  47107. this._halfyaw = 0.0;
  47108. this._sinRoll = 0.0;
  47109. this._cosRoll = 0.0;
  47110. this._sinPitch = 0.0;
  47111. this._cosPitch = 0.0;
  47112. this._sinYaw = 0.0;
  47113. this._cosYaw = 0.0;
  47114. this._mustUnrotateFixedNormals = false;
  47115. this._minimum = BABYLON.Tmp.Vector3[0];
  47116. this._maximum = BABYLON.Tmp.Vector3[1];
  47117. this._minBbox = BABYLON.Tmp.Vector3[4];
  47118. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47119. this._particlesIntersect = false;
  47120. this._depthSortFunction = function (p1, p2) {
  47121. return (p2.sqDistance - p1.sqDistance);
  47122. };
  47123. this._needs32Bits = false;
  47124. this._bSphereOnly = false;
  47125. this._bSphereRadiusFactor = 1.0;
  47126. this.name = name;
  47127. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47128. this._camera = scene.activeCamera;
  47129. this._pickable = options ? options.isPickable : false;
  47130. this._depthSort = options ? options.enableDepthSort : false;
  47131. this._particlesIntersect = options ? options.particleIntersection : false;
  47132. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47133. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47134. if (options && options.updatable) {
  47135. this._updatable = options.updatable;
  47136. }
  47137. else {
  47138. this._updatable = true;
  47139. }
  47140. if (this._pickable) {
  47141. this.pickedParticles = [];
  47142. }
  47143. if (this._depthSort) {
  47144. this.depthSortedParticles = [];
  47145. }
  47146. }
  47147. /**
  47148. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47149. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47150. */
  47151. SolidParticleSystem.prototype.buildMesh = function () {
  47152. if (this.nbParticles === 0) {
  47153. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47154. this.addShape(triangle, 1);
  47155. triangle.dispose();
  47156. }
  47157. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  47158. this._positions32 = new Float32Array(this._positions);
  47159. this._uvs32 = new Float32Array(this._uvs);
  47160. this._colors32 = new Float32Array(this._colors);
  47161. if (this.recomputeNormals) {
  47162. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  47163. }
  47164. this._normals32 = new Float32Array(this._normals);
  47165. this._fixedNormal32 = new Float32Array(this._normals);
  47166. if (this._mustUnrotateFixedNormals) {
  47167. this._unrotateFixedNormals();
  47168. }
  47169. var vertexData = new BABYLON.VertexData();
  47170. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  47171. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47172. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47173. if (this._uvs32) {
  47174. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47175. ;
  47176. }
  47177. if (this._colors32) {
  47178. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47179. }
  47180. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47181. vertexData.applyToMesh(mesh, this._updatable);
  47182. this.mesh = mesh;
  47183. this.mesh.isPickable = this._pickable;
  47184. // free memory
  47185. if (!this._depthSort) {
  47186. this._indices = null;
  47187. }
  47188. this._positions = null;
  47189. this._normals = null;
  47190. this._uvs = null;
  47191. this._colors = null;
  47192. if (!this._updatable) {
  47193. this.particles.length = 0;
  47194. }
  47195. return mesh;
  47196. };
  47197. /**
  47198. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47199. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47200. * Thus the particles generated from `digest()` have their property `position` set yet.
  47201. * `mesh` ( Mesh ) is the mesh to be digested
  47202. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47203. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47204. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47205. */
  47206. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47207. var size = (options && options.facetNb) || 1;
  47208. var number = (options && options.number) || 0;
  47209. var delta = (options && options.delta) || 0;
  47210. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47211. var meshInd = mesh.getIndices();
  47212. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47213. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47214. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47215. var f = 0; // facet counter
  47216. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47217. // compute size from number
  47218. if (number) {
  47219. number = (number > totalFacets) ? totalFacets : number;
  47220. size = Math.round(totalFacets / number);
  47221. delta = 0;
  47222. }
  47223. else {
  47224. size = (size > totalFacets) ? totalFacets : size;
  47225. }
  47226. var facetPos = []; // submesh positions
  47227. var facetInd = []; // submesh indices
  47228. var facetUV = []; // submesh UV
  47229. var facetCol = []; // submesh colors
  47230. var barycenter = BABYLON.Tmp.Vector3[0];
  47231. var sizeO = size;
  47232. while (f < totalFacets) {
  47233. size = sizeO + Math.floor((1 + delta) * Math.random());
  47234. if (f > totalFacets - size) {
  47235. size = totalFacets - f;
  47236. }
  47237. // reset temp arrays
  47238. facetPos.length = 0;
  47239. facetInd.length = 0;
  47240. facetUV.length = 0;
  47241. facetCol.length = 0;
  47242. // iterate over "size" facets
  47243. var fi = 0;
  47244. for (var j = f * 3; j < (f + size) * 3; j++) {
  47245. facetInd.push(fi);
  47246. var i = meshInd[j];
  47247. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47248. if (meshUV) {
  47249. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47250. }
  47251. if (meshCol) {
  47252. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47253. }
  47254. fi++;
  47255. }
  47256. // create a model shape for each single particle
  47257. var idx = this.nbParticles;
  47258. var shape = this._posToShape(facetPos);
  47259. var shapeUV = this._uvsToShapeUV(facetUV);
  47260. // compute the barycenter of the shape
  47261. var v;
  47262. for (v = 0; v < shape.length; v++) {
  47263. barycenter.addInPlace(shape[v]);
  47264. }
  47265. barycenter.scaleInPlace(1 / shape.length);
  47266. // shift the shape from its barycenter to the origin
  47267. for (v = 0; v < shape.length; v++) {
  47268. shape[v].subtractInPlace(barycenter);
  47269. }
  47270. var bInfo;
  47271. if (this._particlesIntersect) {
  47272. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47273. }
  47274. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  47275. // add the particle in the SPS
  47276. var currentPos = this._positions.length;
  47277. var currentInd = this._indices.length;
  47278. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47279. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  47280. // initialize the particle position
  47281. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47282. this._index += shape.length;
  47283. idx++;
  47284. this.nbParticles++;
  47285. this._shapeCounter++;
  47286. f += size;
  47287. }
  47288. return this;
  47289. };
  47290. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  47291. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  47292. var index = 0;
  47293. var idx = 0;
  47294. for (var p = 0; p < this.particles.length; p++) {
  47295. this._particle = this.particles[p];
  47296. this._shape = this._particle._model._shape;
  47297. if (this._particle.rotationQuaternion) {
  47298. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47299. }
  47300. else {
  47301. this._yaw = this._particle.rotation.y;
  47302. this._pitch = this._particle.rotation.x;
  47303. this._roll = this._particle.rotation.z;
  47304. this._quaternionRotationYPR();
  47305. }
  47306. this._quaternionToRotationMatrix();
  47307. this._rotMatrix.invertToRef(this._invertMatrix);
  47308. for (var pt = 0; pt < this._shape.length; pt++) {
  47309. idx = index + pt * 3;
  47310. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  47311. this._fixedNormal32[idx] = this._normal.x;
  47312. this._fixedNormal32[idx + 1] = this._normal.y;
  47313. this._fixedNormal32[idx + 2] = this._normal.z;
  47314. }
  47315. index = idx + 3;
  47316. }
  47317. };
  47318. //reset copy
  47319. SolidParticleSystem.prototype._resetCopy = function () {
  47320. this._copy.position.x = 0;
  47321. this._copy.position.y = 0;
  47322. this._copy.position.z = 0;
  47323. this._copy.rotation.x = 0;
  47324. this._copy.rotation.y = 0;
  47325. this._copy.rotation.z = 0;
  47326. this._copy.rotationQuaternion = null;
  47327. this._copy.scaling.x = 1.0;
  47328. this._copy.scaling.y = 1.0;
  47329. this._copy.scaling.z = 1.0;
  47330. this._copy.uvs.x = 0;
  47331. this._copy.uvs.y = 0;
  47332. this._copy.uvs.z = 1.0;
  47333. this._copy.uvs.w = 1.0;
  47334. this._copy.color = null;
  47335. };
  47336. // _meshBuilder : inserts the shape model in the global SPS mesh
  47337. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47338. var i;
  47339. var u = 0;
  47340. var c = 0;
  47341. var n = 0;
  47342. this._resetCopy();
  47343. if (options && options.positionFunction) {
  47344. options.positionFunction(this._copy, idx, idxInShape);
  47345. this._mustUnrotateFixedNormals = true;
  47346. }
  47347. if (this._copy.rotationQuaternion) {
  47348. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47349. }
  47350. else {
  47351. this._yaw = this._copy.rotation.y;
  47352. this._pitch = this._copy.rotation.x;
  47353. this._roll = this._copy.rotation.z;
  47354. this._quaternionRotationYPR();
  47355. }
  47356. this._quaternionToRotationMatrix();
  47357. for (i = 0; i < shape.length; i++) {
  47358. this._vertex.x = shape[i].x;
  47359. this._vertex.y = shape[i].y;
  47360. this._vertex.z = shape[i].z;
  47361. if (options && options.vertexFunction) {
  47362. options.vertexFunction(this._copy, this._vertex, i);
  47363. }
  47364. this._vertex.x *= this._copy.scaling.x;
  47365. this._vertex.y *= this._copy.scaling.y;
  47366. this._vertex.z *= this._copy.scaling.z;
  47367. this._vertex.x += this._copy.pivot.x;
  47368. this._vertex.y += this._copy.pivot.y;
  47369. this._vertex.z += this._copy.pivot.z;
  47370. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47371. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47372. if (meshUV) {
  47373. 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);
  47374. u += 2;
  47375. }
  47376. if (this._copy.color) {
  47377. this._color = this._copy.color;
  47378. }
  47379. else if (meshCol && meshCol[c] !== undefined) {
  47380. this._color.r = meshCol[c];
  47381. this._color.g = meshCol[c + 1];
  47382. this._color.b = meshCol[c + 2];
  47383. this._color.a = meshCol[c + 3];
  47384. }
  47385. else {
  47386. this._color.r = 1.0;
  47387. this._color.g = 1.0;
  47388. this._color.b = 1.0;
  47389. this._color.a = 1.0;
  47390. }
  47391. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47392. c += 4;
  47393. if (!this.recomputeNormals && meshNor) {
  47394. this._normal.x = meshNor[n];
  47395. this._normal.y = meshNor[n + 1];
  47396. this._normal.z = meshNor[n + 2];
  47397. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  47398. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47399. n += 3;
  47400. }
  47401. }
  47402. for (i = 0; i < meshInd.length; i++) {
  47403. var current_ind = p + meshInd[i];
  47404. indices.push(current_ind);
  47405. if (current_ind > 65535) {
  47406. this._needs32Bits = true;
  47407. }
  47408. }
  47409. if (this._pickable) {
  47410. var nbfaces = meshInd.length / 3;
  47411. for (i = 0; i < nbfaces; i++) {
  47412. this.pickedParticles.push({ idx: idx, faceId: i });
  47413. }
  47414. }
  47415. if (this._depthSort) {
  47416. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  47417. }
  47418. return this._copy;
  47419. };
  47420. // returns a shape array from positions array
  47421. SolidParticleSystem.prototype._posToShape = function (positions) {
  47422. var shape = [];
  47423. for (var i = 0; i < positions.length; i += 3) {
  47424. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47425. }
  47426. return shape;
  47427. };
  47428. // returns a shapeUV array from a Vector4 uvs
  47429. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47430. var shapeUV = [];
  47431. if (uvs) {
  47432. for (var i = 0; i < uvs.length; i++)
  47433. shapeUV.push(uvs[i]);
  47434. }
  47435. return shapeUV;
  47436. };
  47437. // adds a new particle object in the particles array
  47438. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  47439. if (bInfo === void 0) { bInfo = null; }
  47440. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  47441. this.particles.push(sp);
  47442. return sp;
  47443. };
  47444. /**
  47445. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47446. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47447. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47448. * `nb` (positive integer) the number of particles to be created from this model
  47449. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47450. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47451. */
  47452. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47453. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47454. var meshInd = mesh.getIndices();
  47455. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47456. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47457. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47458. var bbInfo;
  47459. if (this._particlesIntersect) {
  47460. bbInfo = mesh.getBoundingInfo();
  47461. }
  47462. var shape = this._posToShape(meshPos);
  47463. var shapeUV = this._uvsToShapeUV(meshUV);
  47464. var posfunc = options ? options.positionFunction : null;
  47465. var vtxfunc = options ? options.vertexFunction : null;
  47466. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  47467. // particles
  47468. var sp;
  47469. var currentCopy;
  47470. var idx = this.nbParticles;
  47471. for (var i = 0; i < nb; i++) {
  47472. var currentPos = this._positions.length;
  47473. var currentInd = this._indices.length;
  47474. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47475. if (this._updatable) {
  47476. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  47477. sp.position.copyFrom(currentCopy.position);
  47478. sp.rotation.copyFrom(currentCopy.rotation);
  47479. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  47480. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  47481. }
  47482. if (currentCopy.color && sp.color) {
  47483. sp.color.copyFrom(currentCopy.color);
  47484. }
  47485. sp.scaling.copyFrom(currentCopy.scaling);
  47486. sp.uvs.copyFrom(currentCopy.uvs);
  47487. }
  47488. this._index += shape.length;
  47489. idx++;
  47490. }
  47491. this.nbParticles += nb;
  47492. this._shapeCounter++;
  47493. return this._shapeCounter - 1;
  47494. };
  47495. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47496. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47497. this._resetCopy();
  47498. if (particle._model._positionFunction) {
  47499. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47500. }
  47501. if (this._copy.rotationQuaternion) {
  47502. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47503. }
  47504. else {
  47505. this._yaw = this._copy.rotation.y;
  47506. this._pitch = this._copy.rotation.x;
  47507. this._roll = this._copy.rotation.z;
  47508. this._quaternionRotationYPR();
  47509. }
  47510. this._quaternionToRotationMatrix();
  47511. this._shape = particle._model._shape;
  47512. for (var pt = 0; pt < this._shape.length; pt++) {
  47513. this._vertex.x = this._shape[pt].x;
  47514. this._vertex.y = this._shape[pt].y;
  47515. this._vertex.z = this._shape[pt].z;
  47516. if (particle._model._vertexFunction) {
  47517. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47518. }
  47519. this._vertex.x *= this._copy.scaling.x;
  47520. this._vertex.y *= this._copy.scaling.y;
  47521. this._vertex.z *= this._copy.scaling.z;
  47522. this._vertex.x += this._copy.pivot.x;
  47523. this._vertex.y += this._copy.pivot.y;
  47524. this._vertex.z += this._copy.pivot.z;
  47525. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47526. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47527. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47528. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47529. }
  47530. particle.position.x = 0.0;
  47531. particle.position.y = 0.0;
  47532. particle.position.z = 0.0;
  47533. particle.rotation.x = 0.0;
  47534. particle.rotation.y = 0.0;
  47535. particle.rotation.z = 0.0;
  47536. particle.rotationQuaternion = null;
  47537. particle.scaling.x = 1.0;
  47538. particle.scaling.y = 1.0;
  47539. particle.scaling.z = 1.0;
  47540. };
  47541. /**
  47542. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47543. * Returns the SPS.
  47544. */
  47545. SolidParticleSystem.prototype.rebuildMesh = function () {
  47546. for (var p = 0; p < this.particles.length; p++) {
  47547. this._rebuildParticle(this.particles[p]);
  47548. }
  47549. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47550. return this;
  47551. };
  47552. /**
  47553. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47554. * This method calls `updateParticle()` for each particle of the SPS.
  47555. * For an animated SPS, it is usually called within the render loop.
  47556. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47557. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47558. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47559. * Returns the SPS.
  47560. */
  47561. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47562. if (start === void 0) { start = 0; }
  47563. if (end === void 0) { end = this.nbParticles - 1; }
  47564. if (update === void 0) { update = true; }
  47565. if (!this._updatable) {
  47566. return this;
  47567. }
  47568. // custom beforeUpdate
  47569. this.beforeUpdateParticles(start, end, update);
  47570. this._cam_axisX.x = 1.0;
  47571. this._cam_axisX.y = 0.0;
  47572. this._cam_axisX.z = 0.0;
  47573. this._cam_axisY.x = 0.0;
  47574. this._cam_axisY.y = 1.0;
  47575. this._cam_axisY.z = 0.0;
  47576. this._cam_axisZ.x = 0.0;
  47577. this._cam_axisZ.y = 0.0;
  47578. this._cam_axisZ.z = 1.0;
  47579. // cases when the World Matrix is to be computed first
  47580. if (this.billboard || this._depthSort) {
  47581. this.mesh.computeWorldMatrix(true);
  47582. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47583. }
  47584. // if the particles will always face the camera
  47585. if (this.billboard) {
  47586. // compute the camera position and un-rotate it by the current mesh rotation
  47587. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47588. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47589. this._cam_axisZ.normalize();
  47590. // same for camera up vector extracted from the cam view matrix
  47591. var view = this._camera.getViewMatrix(true);
  47592. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47593. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47594. this._cam_axisY.normalize();
  47595. this._cam_axisX.normalize();
  47596. }
  47597. // if depthSort, compute the camera global position in the mesh local system
  47598. if (this._depthSort) {
  47599. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47600. }
  47601. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47602. var idx = 0; // current position index in the global array positions32
  47603. var index = 0; // position start index in the global array positions32 of the current particle
  47604. var colidx = 0; // current color index in the global array colors32
  47605. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47606. var uvidx = 0; // current uv index in the global array uvs32
  47607. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47608. var pt = 0; // current index in the particle model shape
  47609. if (this.mesh.isFacetDataEnabled) {
  47610. this._computeBoundingBox = true;
  47611. }
  47612. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47613. if (this._computeBoundingBox) {
  47614. if (start == 0 && end == this.nbParticles - 1) {
  47615. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47616. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47617. }
  47618. else {
  47619. if (this.mesh._boundingInfo) {
  47620. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47621. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47622. }
  47623. }
  47624. }
  47625. // particle loop
  47626. index = this.particles[start]._pos;
  47627. var vpos = (index / 3) | 0;
  47628. colorIndex = vpos * 4;
  47629. uvIndex = vpos * 2;
  47630. for (var p = start; p <= end; p++) {
  47631. this._particle = this.particles[p];
  47632. this._shape = this._particle._model._shape;
  47633. this._shapeUV = this._particle._model._shapeUV;
  47634. // call to custom user function to update the particle properties
  47635. this.updateParticle(this._particle);
  47636. // camera-particle distance for depth sorting
  47637. if (this._depthSort && this._depthSortParticles) {
  47638. var dsp = this.depthSortedParticles[p];
  47639. dsp.ind = this._particle._ind;
  47640. dsp.indicesLength = this._particle._model._indicesLength;
  47641. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47642. }
  47643. // skip the computations for inactive or already invisible particles
  47644. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47645. // increment indexes for the next particle
  47646. pt = this._shape.length;
  47647. index += pt * 3;
  47648. colorIndex += pt * 4;
  47649. uvIndex += pt * 2;
  47650. continue;
  47651. }
  47652. if (this._particle.isVisible) {
  47653. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47654. // particle rotation matrix
  47655. if (this.billboard) {
  47656. this._particle.rotation.x = 0.0;
  47657. this._particle.rotation.y = 0.0;
  47658. }
  47659. if (this._computeParticleRotation || this.billboard) {
  47660. if (this._particle.rotationQuaternion) {
  47661. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47662. }
  47663. else {
  47664. this._yaw = this._particle.rotation.y;
  47665. this._pitch = this._particle.rotation.x;
  47666. this._roll = this._particle.rotation.z;
  47667. this._quaternionRotationYPR();
  47668. }
  47669. this._quaternionToRotationMatrix();
  47670. }
  47671. // particle vertex loop
  47672. for (pt = 0; pt < this._shape.length; pt++) {
  47673. idx = index + pt * 3;
  47674. colidx = colorIndex + pt * 4;
  47675. uvidx = uvIndex + pt * 2;
  47676. this._vertex.x = this._shape[pt].x;
  47677. this._vertex.y = this._shape[pt].y;
  47678. this._vertex.z = this._shape[pt].z;
  47679. if (this._computeParticleVertex) {
  47680. this.updateParticleVertex(this._particle, this._vertex, pt);
  47681. }
  47682. // positions
  47683. this._vertex.x *= this._particle.scaling.x;
  47684. this._vertex.y *= this._particle.scaling.y;
  47685. this._vertex.z *= this._particle.scaling.z;
  47686. this._vertex.x += this._particle.pivot.x;
  47687. this._vertex.y += this._particle.pivot.y;
  47688. this._vertex.z += this._particle.pivot.z;
  47689. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47690. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47691. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47692. this._positions32[idx] = this._particle.position.x + this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47693. this._positions32[idx + 1] = this._particle.position.y + this._cam_axisX.y * this._rotated.x + this._cam_axisY.y * this._rotated.y + this._cam_axisZ.y * this._rotated.z;
  47694. this._positions32[idx + 2] = this._particle.position.z + this._cam_axisX.z * this._rotated.x + this._cam_axisY.z * this._rotated.y + this._cam_axisZ.z * this._rotated.z;
  47695. if (this._computeBoundingBox) {
  47696. if (this._positions32[idx] < this._minimum.x) {
  47697. this._minimum.x = this._positions32[idx];
  47698. }
  47699. if (this._positions32[idx] > this._maximum.x) {
  47700. this._maximum.x = this._positions32[idx];
  47701. }
  47702. if (this._positions32[idx + 1] < this._minimum.y) {
  47703. this._minimum.y = this._positions32[idx + 1];
  47704. }
  47705. if (this._positions32[idx + 1] > this._maximum.y) {
  47706. this._maximum.y = this._positions32[idx + 1];
  47707. }
  47708. if (this._positions32[idx + 2] < this._minimum.z) {
  47709. this._minimum.z = this._positions32[idx + 2];
  47710. }
  47711. if (this._positions32[idx + 2] > this._maximum.z) {
  47712. this._maximum.z = this._positions32[idx + 2];
  47713. }
  47714. }
  47715. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47716. if (!this._computeParticleVertex) {
  47717. this._normal.x = this._fixedNormal32[idx];
  47718. this._normal.y = this._fixedNormal32[idx + 1];
  47719. this._normal.z = this._fixedNormal32[idx + 2];
  47720. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47721. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47722. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47723. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47724. 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;
  47725. 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;
  47726. }
  47727. if (this._computeParticleColor && this._particle.color) {
  47728. this._colors32[colidx] = this._particle.color.r;
  47729. this._colors32[colidx + 1] = this._particle.color.g;
  47730. this._colors32[colidx + 2] = this._particle.color.b;
  47731. this._colors32[colidx + 3] = this._particle.color.a;
  47732. }
  47733. if (this._computeParticleTexture) {
  47734. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47735. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47736. }
  47737. }
  47738. }
  47739. else {
  47740. this._particle._stillInvisible = true; // mark the particle as invisible
  47741. for (pt = 0; pt < this._shape.length; pt++) {
  47742. idx = index + pt * 3;
  47743. colidx = colorIndex + pt * 4;
  47744. uvidx = uvIndex + pt * 2;
  47745. this._positions32[idx] = 0.0;
  47746. this._positions32[idx + 1] = 0.0;
  47747. this._positions32[idx + 2] = 0.0;
  47748. this._normals32[idx] = 0.0;
  47749. this._normals32[idx + 1] = 0.0;
  47750. this._normals32[idx + 2] = 0.0;
  47751. if (this._computeParticleColor && this._particle.color) {
  47752. this._colors32[colidx] = this._particle.color.r;
  47753. this._colors32[colidx + 1] = this._particle.color.g;
  47754. this._colors32[colidx + 2] = this._particle.color.b;
  47755. this._colors32[colidx + 3] = this._particle.color.a;
  47756. }
  47757. if (this._computeParticleTexture) {
  47758. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47759. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47760. }
  47761. }
  47762. }
  47763. // if the particle intersections must be computed : update the bbInfo
  47764. if (this._particlesIntersect) {
  47765. var bInfo = this._particle._boundingInfo;
  47766. var bBox = bInfo.boundingBox;
  47767. var bSphere = bInfo.boundingSphere;
  47768. if (!this._bSphereOnly) {
  47769. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47770. for (var b = 0; b < bBox.vectors.length; b++) {
  47771. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47772. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47773. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47774. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47775. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47776. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47777. 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;
  47778. 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;
  47779. 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;
  47780. }
  47781. bBox._update(this.mesh._worldMatrix);
  47782. }
  47783. // place and scale the particle bouding sphere in the SPS local system, then update it
  47784. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47785. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47786. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47787. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47788. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47789. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47790. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47791. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47792. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47793. 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));
  47794. bSphere._update(this.mesh._worldMatrix);
  47795. }
  47796. // increment indexes for the next particle
  47797. index = idx + 3;
  47798. colorIndex = colidx + 4;
  47799. uvIndex = uvidx + 2;
  47800. }
  47801. // if the VBO must be updated
  47802. if (update) {
  47803. if (this._computeParticleColor) {
  47804. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47805. }
  47806. if (this._computeParticleTexture) {
  47807. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47808. }
  47809. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47810. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47811. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47812. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47813. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47814. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  47815. for (var i = 0; i < this._normals32.length; i++) {
  47816. this._fixedNormal32[i] = this._normals32[i];
  47817. }
  47818. }
  47819. if (!this.mesh.areNormalsFrozen) {
  47820. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47821. }
  47822. }
  47823. if (this._depthSort && this._depthSortParticles) {
  47824. this.depthSortedParticles.sort(this._depthSortFunction);
  47825. var dspl = this.depthSortedParticles.length;
  47826. var sorted = 0;
  47827. var lind = 0;
  47828. var sind = 0;
  47829. var sid = 0;
  47830. for (sorted = 0; sorted < dspl; sorted++) {
  47831. lind = this.depthSortedParticles[sorted].indicesLength;
  47832. sind = this.depthSortedParticles[sorted].ind;
  47833. for (var i = 0; i < lind; i++) {
  47834. this._indices32[sid] = this._indices[sind + i];
  47835. sid++;
  47836. }
  47837. }
  47838. this.mesh.updateIndices(this._indices32);
  47839. }
  47840. }
  47841. if (this._computeBoundingBox) {
  47842. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47843. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47844. }
  47845. this.afterUpdateParticles(start, end, update);
  47846. return this;
  47847. };
  47848. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47849. this._halfroll = this._roll * 0.5;
  47850. this._halfpitch = this._pitch * 0.5;
  47851. this._halfyaw = this._yaw * 0.5;
  47852. this._sinRoll = Math.sin(this._halfroll);
  47853. this._cosRoll = Math.cos(this._halfroll);
  47854. this._sinPitch = Math.sin(this._halfpitch);
  47855. this._cosPitch = Math.cos(this._halfpitch);
  47856. this._sinYaw = Math.sin(this._halfyaw);
  47857. this._cosYaw = Math.cos(this._halfyaw);
  47858. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  47859. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  47860. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  47861. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  47862. };
  47863. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47864. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47865. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47866. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47867. this._rotMatrix.m[3] = 0;
  47868. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47869. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47870. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47871. this._rotMatrix.m[7] = 0;
  47872. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47873. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47874. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47875. this._rotMatrix.m[11] = 0;
  47876. this._rotMatrix.m[12] = 0;
  47877. this._rotMatrix.m[13] = 0;
  47878. this._rotMatrix.m[14] = 0;
  47879. this._rotMatrix.m[15] = 1.0;
  47880. };
  47881. /**
  47882. * Disposes the SPS.
  47883. * Returns nothing.
  47884. */
  47885. SolidParticleSystem.prototype.dispose = function () {
  47886. this.mesh.dispose();
  47887. this.vars = null;
  47888. // drop references to internal big arrays for the GC
  47889. this._positions = null;
  47890. this._indices = null;
  47891. this._normals = null;
  47892. this._uvs = null;
  47893. this._colors = null;
  47894. this._indices32 = null;
  47895. this._positions32 = null;
  47896. this._normals32 = null;
  47897. this._fixedNormal32 = null;
  47898. this._uvs32 = null;
  47899. this._colors32 = null;
  47900. this.pickedParticles = null;
  47901. };
  47902. /**
  47903. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47904. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47905. * Returns the SPS.
  47906. */
  47907. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47908. if (!this._isVisibilityBoxLocked) {
  47909. this.mesh.refreshBoundingInfo();
  47910. }
  47911. return this;
  47912. };
  47913. /**
  47914. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47915. * @param size the size (float) of the visibility box
  47916. * note : this doesn't lock the SPS mesh bounding box.
  47917. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47918. */
  47919. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47920. var vis = size / 2;
  47921. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47922. };
  47923. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47924. // getter and setter
  47925. get: function () {
  47926. return this._alwaysVisible;
  47927. },
  47928. /**
  47929. * Sets the SPS as always visible or not
  47930. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47931. */
  47932. set: function (val) {
  47933. this._alwaysVisible = val;
  47934. this.mesh.alwaysSelectAsActiveMesh = val;
  47935. },
  47936. enumerable: true,
  47937. configurable: true
  47938. });
  47939. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47940. get: function () {
  47941. return this._isVisibilityBoxLocked;
  47942. },
  47943. /**
  47944. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47945. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47946. */
  47947. set: function (val) {
  47948. this._isVisibilityBoxLocked = val;
  47949. var boundingInfo = this.mesh.getBoundingInfo();
  47950. boundingInfo.isLocked = val;
  47951. },
  47952. enumerable: true,
  47953. configurable: true
  47954. });
  47955. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47956. // getters
  47957. get: function () {
  47958. return this._computeParticleRotation;
  47959. },
  47960. // Optimizer setters
  47961. /**
  47962. * Tells to `setParticles()` to compute the particle rotations or not.
  47963. * Default value : true. The SPS is faster when it's set to false.
  47964. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47965. */
  47966. set: function (val) {
  47967. this._computeParticleRotation = val;
  47968. },
  47969. enumerable: true,
  47970. configurable: true
  47971. });
  47972. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47973. get: function () {
  47974. return this._computeParticleColor;
  47975. },
  47976. /**
  47977. * Tells to `setParticles()` to compute the particle colors or not.
  47978. * Default value : true. The SPS is faster when it's set to false.
  47979. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47980. */
  47981. set: function (val) {
  47982. this._computeParticleColor = val;
  47983. },
  47984. enumerable: true,
  47985. configurable: true
  47986. });
  47987. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47988. get: function () {
  47989. return this._computeParticleTexture;
  47990. },
  47991. /**
  47992. * Tells to `setParticles()` to compute the particle textures or not.
  47993. * Default value : true. The SPS is faster when it's set to false.
  47994. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47995. */
  47996. set: function (val) {
  47997. this._computeParticleTexture = val;
  47998. },
  47999. enumerable: true,
  48000. configurable: true
  48001. });
  48002. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  48003. get: function () {
  48004. return this._computeParticleVertex;
  48005. },
  48006. /**
  48007. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  48008. * Default value : false. The SPS is faster when it's set to false.
  48009. * Note : the particle custom vertex positions aren't stored values.
  48010. */
  48011. set: function (val) {
  48012. this._computeParticleVertex = val;
  48013. },
  48014. enumerable: true,
  48015. configurable: true
  48016. });
  48017. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48018. get: function () {
  48019. return this._computeBoundingBox;
  48020. },
  48021. /**
  48022. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48023. */
  48024. set: function (val) {
  48025. this._computeBoundingBox = val;
  48026. },
  48027. enumerable: true,
  48028. configurable: true
  48029. });
  48030. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  48031. get: function () {
  48032. return this._depthSortParticles;
  48033. },
  48034. /**
  48035. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  48036. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  48037. * Default : `true`
  48038. */
  48039. set: function (val) {
  48040. this._depthSortParticles = val;
  48041. },
  48042. enumerable: true,
  48043. configurable: true
  48044. });
  48045. // =======================================================================
  48046. // Particle behavior logic
  48047. // these following methods may be overwritten by the user to fit his needs
  48048. /**
  48049. * This function does nothing. It may be overwritten to set all the particle first values.
  48050. * The SPS doesn't call this function, you may have to call it by your own.
  48051. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48052. */
  48053. SolidParticleSystem.prototype.initParticles = function () {
  48054. };
  48055. /**
  48056. * This function does nothing. It may be overwritten to recycle a particle.
  48057. * The SPS doesn't call this function, you may have to call it by your own.
  48058. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48059. */
  48060. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48061. return particle;
  48062. };
  48063. /**
  48064. * Updates a particle : this function should be overwritten by the user.
  48065. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48066. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48067. * ex : just set a particle position or velocity and recycle conditions
  48068. */
  48069. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48070. return particle;
  48071. };
  48072. /**
  48073. * Updates a vertex of a particle : it can be overwritten by the user.
  48074. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48075. * @param particle the current particle
  48076. * @param vertex the current index of the current particle
  48077. * @param pt the index of the current vertex in the particle shape
  48078. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48079. * ex : just set a vertex particle position
  48080. */
  48081. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48082. return vertex;
  48083. };
  48084. /**
  48085. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48086. * This does nothing and may be overwritten by the user.
  48087. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48088. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48089. * @param update the boolean update value actually passed to setParticles()
  48090. */
  48091. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48092. };
  48093. /**
  48094. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48095. * This will be passed three parameters.
  48096. * This does nothing and may be overwritten by the user.
  48097. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48098. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48099. * @param update the boolean update value actually passed to setParticles()
  48100. */
  48101. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48102. };
  48103. return SolidParticleSystem;
  48104. }());
  48105. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48106. })(BABYLON || (BABYLON = {}));
  48107. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  48108. var BABYLON;
  48109. (function (BABYLON) {
  48110. var ShaderMaterial = /** @class */ (function (_super) {
  48111. __extends(ShaderMaterial, _super);
  48112. function ShaderMaterial(name, scene, shaderPath, options) {
  48113. var _this = _super.call(this, name, scene) || this;
  48114. _this._textures = {};
  48115. _this._textureArrays = {};
  48116. _this._floats = {};
  48117. _this._ints = {};
  48118. _this._floatsArrays = {};
  48119. _this._colors3 = {};
  48120. _this._colors3Arrays = {};
  48121. _this._colors4 = {};
  48122. _this._vectors2 = {};
  48123. _this._vectors3 = {};
  48124. _this._vectors4 = {};
  48125. _this._matrices = {};
  48126. _this._matrices3x3 = {};
  48127. _this._matrices2x2 = {};
  48128. _this._vectors2Arrays = {};
  48129. _this._vectors3Arrays = {};
  48130. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48131. _this._shaderPath = shaderPath;
  48132. options.needAlphaBlending = options.needAlphaBlending || false;
  48133. options.needAlphaTesting = options.needAlphaTesting || false;
  48134. options.attributes = options.attributes || ["position", "normal", "uv"];
  48135. options.uniforms = options.uniforms || ["worldViewProjection"];
  48136. options.uniformBuffers = options.uniformBuffers || [];
  48137. options.samplers = options.samplers || [];
  48138. options.defines = options.defines || [];
  48139. _this._options = options;
  48140. return _this;
  48141. }
  48142. ShaderMaterial.prototype.getClassName = function () {
  48143. return "ShaderMaterial";
  48144. };
  48145. ShaderMaterial.prototype.needAlphaBlending = function () {
  48146. return this._options.needAlphaBlending;
  48147. };
  48148. ShaderMaterial.prototype.needAlphaTesting = function () {
  48149. return this._options.needAlphaTesting;
  48150. };
  48151. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48152. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48153. this._options.uniforms.push(uniformName);
  48154. }
  48155. };
  48156. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48157. if (this._options.samplers.indexOf(name) === -1) {
  48158. this._options.samplers.push(name);
  48159. }
  48160. this._textures[name] = texture;
  48161. return this;
  48162. };
  48163. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48164. if (this._options.samplers.indexOf(name) === -1) {
  48165. this._options.samplers.push(name);
  48166. }
  48167. this._checkUniform(name);
  48168. this._textureArrays[name] = textures;
  48169. return this;
  48170. };
  48171. ShaderMaterial.prototype.setFloat = function (name, value) {
  48172. this._checkUniform(name);
  48173. this._floats[name] = value;
  48174. return this;
  48175. };
  48176. ShaderMaterial.prototype.setInt = function (name, value) {
  48177. this._checkUniform(name);
  48178. this._ints[name] = value;
  48179. return this;
  48180. };
  48181. ShaderMaterial.prototype.setFloats = function (name, value) {
  48182. this._checkUniform(name);
  48183. this._floatsArrays[name] = value;
  48184. return this;
  48185. };
  48186. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48187. this._checkUniform(name);
  48188. this._colors3[name] = value;
  48189. return this;
  48190. };
  48191. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48192. this._checkUniform(name);
  48193. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48194. color.toArray(arr, arr.length);
  48195. return arr;
  48196. }, []);
  48197. return this;
  48198. };
  48199. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48200. this._checkUniform(name);
  48201. this._colors4[name] = value;
  48202. return this;
  48203. };
  48204. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48205. this._checkUniform(name);
  48206. this._vectors2[name] = value;
  48207. return this;
  48208. };
  48209. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48210. this._checkUniform(name);
  48211. this._vectors3[name] = value;
  48212. return this;
  48213. };
  48214. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48215. this._checkUniform(name);
  48216. this._vectors4[name] = value;
  48217. return this;
  48218. };
  48219. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48220. this._checkUniform(name);
  48221. this._matrices[name] = value;
  48222. return this;
  48223. };
  48224. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48225. this._checkUniform(name);
  48226. this._matrices3x3[name] = value;
  48227. return this;
  48228. };
  48229. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48230. this._checkUniform(name);
  48231. this._matrices2x2[name] = value;
  48232. return this;
  48233. };
  48234. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48235. this._checkUniform(name);
  48236. this._vectors2Arrays[name] = value;
  48237. return this;
  48238. };
  48239. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48240. this._checkUniform(name);
  48241. this._vectors3Arrays[name] = value;
  48242. return this;
  48243. };
  48244. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48245. if (!mesh) {
  48246. return true;
  48247. }
  48248. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48249. return false;
  48250. }
  48251. return false;
  48252. };
  48253. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48254. var scene = this.getScene();
  48255. var engine = scene.getEngine();
  48256. if (!this.checkReadyOnEveryCall) {
  48257. if (this._renderId === scene.getRenderId()) {
  48258. if (this._checkCache(scene, mesh, useInstances)) {
  48259. return true;
  48260. }
  48261. }
  48262. }
  48263. // Instances
  48264. var defines = [];
  48265. var attribs = [];
  48266. var fallbacks = new BABYLON.EffectFallbacks();
  48267. if (useInstances) {
  48268. defines.push("#define INSTANCES");
  48269. }
  48270. for (var index = 0; index < this._options.defines.length; index++) {
  48271. defines.push(this._options.defines[index]);
  48272. }
  48273. for (var index = 0; index < this._options.attributes.length; index++) {
  48274. attribs.push(this._options.attributes[index]);
  48275. }
  48276. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48277. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48278. defines.push("#define VERTEXCOLOR");
  48279. }
  48280. // Bones
  48281. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48282. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48283. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48284. if (mesh.numBoneInfluencers > 4) {
  48285. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48286. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48287. }
  48288. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48289. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48290. fallbacks.addCPUSkinningFallback(0, mesh);
  48291. if (this._options.uniforms.indexOf("mBones") === -1) {
  48292. this._options.uniforms.push("mBones");
  48293. }
  48294. }
  48295. else {
  48296. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48297. }
  48298. // Textures
  48299. for (var name in this._textures) {
  48300. if (!this._textures[name].isReady()) {
  48301. return false;
  48302. }
  48303. }
  48304. // Alpha test
  48305. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  48306. defines.push("#define ALPHATEST");
  48307. }
  48308. var previousEffect = this._effect;
  48309. var join = defines.join("\n");
  48310. this._effect = engine.createEffect(this._shaderPath, {
  48311. attributes: attribs,
  48312. uniformsNames: this._options.uniforms,
  48313. uniformBuffersNames: this._options.uniformBuffers,
  48314. samplers: this._options.samplers,
  48315. defines: join,
  48316. fallbacks: fallbacks,
  48317. onCompiled: this.onCompiled,
  48318. onError: this.onError
  48319. }, engine);
  48320. if (!this._effect.isReady()) {
  48321. return false;
  48322. }
  48323. if (previousEffect !== this._effect) {
  48324. scene.resetCachedMaterial();
  48325. }
  48326. this._renderId = scene.getRenderId();
  48327. return true;
  48328. };
  48329. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48330. var scene = this.getScene();
  48331. if (!this._effect) {
  48332. return;
  48333. }
  48334. if (this._options.uniforms.indexOf("world") !== -1) {
  48335. this._effect.setMatrix("world", world);
  48336. }
  48337. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48338. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48339. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48340. }
  48341. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48342. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48343. }
  48344. };
  48345. ShaderMaterial.prototype.bind = function (world, mesh) {
  48346. // Std values
  48347. this.bindOnlyWorldMatrix(world);
  48348. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48349. if (this._options.uniforms.indexOf("view") !== -1) {
  48350. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48351. }
  48352. if (this._options.uniforms.indexOf("projection") !== -1) {
  48353. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48354. }
  48355. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48356. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48357. }
  48358. // Bones
  48359. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48360. var name;
  48361. // Texture
  48362. for (name in this._textures) {
  48363. this._effect.setTexture(name, this._textures[name]);
  48364. }
  48365. // Texture arrays
  48366. for (name in this._textureArrays) {
  48367. this._effect.setTextureArray(name, this._textureArrays[name]);
  48368. }
  48369. // Int
  48370. for (name in this._ints) {
  48371. this._effect.setInt(name, this._ints[name]);
  48372. }
  48373. // Float
  48374. for (name in this._floats) {
  48375. this._effect.setFloat(name, this._floats[name]);
  48376. }
  48377. // Floats
  48378. for (name in this._floatsArrays) {
  48379. this._effect.setArray(name, this._floatsArrays[name]);
  48380. }
  48381. // Color3
  48382. for (name in this._colors3) {
  48383. this._effect.setColor3(name, this._colors3[name]);
  48384. }
  48385. for (name in this._colors3Arrays) {
  48386. this._effect.setArray3(name, this._colors3Arrays[name]);
  48387. }
  48388. // Color4
  48389. for (name in this._colors4) {
  48390. var color = this._colors4[name];
  48391. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48392. }
  48393. // Vector2
  48394. for (name in this._vectors2) {
  48395. this._effect.setVector2(name, this._vectors2[name]);
  48396. }
  48397. // Vector3
  48398. for (name in this._vectors3) {
  48399. this._effect.setVector3(name, this._vectors3[name]);
  48400. }
  48401. // Vector4
  48402. for (name in this._vectors4) {
  48403. this._effect.setVector4(name, this._vectors4[name]);
  48404. }
  48405. // Matrix
  48406. for (name in this._matrices) {
  48407. this._effect.setMatrix(name, this._matrices[name]);
  48408. }
  48409. // Matrix 3x3
  48410. for (name in this._matrices3x3) {
  48411. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48412. }
  48413. // Matrix 2x2
  48414. for (name in this._matrices2x2) {
  48415. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48416. }
  48417. // Vector2Array
  48418. for (name in this._vectors2Arrays) {
  48419. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48420. }
  48421. // Vector3Array
  48422. for (name in this._vectors3Arrays) {
  48423. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48424. }
  48425. }
  48426. this._afterBind(mesh);
  48427. };
  48428. ShaderMaterial.prototype.getActiveTextures = function () {
  48429. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48430. for (var name in this._textures) {
  48431. activeTextures.push(this._textures[name]);
  48432. }
  48433. for (var name in this._textureArrays) {
  48434. var array = this._textureArrays[name];
  48435. for (var index = 0; index < array.length; index++) {
  48436. activeTextures.push(array[index]);
  48437. }
  48438. }
  48439. return activeTextures;
  48440. };
  48441. ShaderMaterial.prototype.hasTexture = function (texture) {
  48442. if (_super.prototype.hasTexture.call(this, texture)) {
  48443. return true;
  48444. }
  48445. for (var name in this._textures) {
  48446. if (this._textures[name] === texture) {
  48447. return true;
  48448. }
  48449. }
  48450. for (var name in this._textureArrays) {
  48451. var array = this._textureArrays[name];
  48452. for (var index = 0; index < array.length; index++) {
  48453. if (array[index] === texture) {
  48454. return true;
  48455. }
  48456. }
  48457. }
  48458. return false;
  48459. };
  48460. ShaderMaterial.prototype.clone = function (name) {
  48461. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48462. return newShaderMaterial;
  48463. };
  48464. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48465. if (forceDisposeTextures) {
  48466. var name;
  48467. for (name in this._textures) {
  48468. this._textures[name].dispose();
  48469. }
  48470. for (name in this._textureArrays) {
  48471. var array = this._textureArrays[name];
  48472. for (var index = 0; index < array.length; index++) {
  48473. array[index].dispose();
  48474. }
  48475. }
  48476. }
  48477. this._textures = {};
  48478. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48479. };
  48480. ShaderMaterial.prototype.serialize = function () {
  48481. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48482. serializationObject.customType = "BABYLON.ShaderMaterial";
  48483. serializationObject.options = this._options;
  48484. serializationObject.shaderPath = this._shaderPath;
  48485. var name;
  48486. // Texture
  48487. serializationObject.textures = {};
  48488. for (name in this._textures) {
  48489. serializationObject.textures[name] = this._textures[name].serialize();
  48490. }
  48491. // Texture arrays
  48492. serializationObject.textureArrays = {};
  48493. for (name in this._textureArrays) {
  48494. serializationObject.textureArrays[name] = [];
  48495. var array = this._textureArrays[name];
  48496. for (var index = 0; index < array.length; index++) {
  48497. serializationObject.textureArrays[name].push(array[index].serialize());
  48498. }
  48499. }
  48500. // Float
  48501. serializationObject.floats = {};
  48502. for (name in this._floats) {
  48503. serializationObject.floats[name] = this._floats[name];
  48504. }
  48505. // Float s
  48506. serializationObject.FloatArrays = {};
  48507. for (name in this._floatsArrays) {
  48508. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48509. }
  48510. // Color3
  48511. serializationObject.colors3 = {};
  48512. for (name in this._colors3) {
  48513. serializationObject.colors3[name] = this._colors3[name].asArray();
  48514. }
  48515. // Color3 array
  48516. serializationObject.colors3Arrays = {};
  48517. for (name in this._colors3Arrays) {
  48518. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48519. }
  48520. // Color4
  48521. serializationObject.colors4 = {};
  48522. for (name in this._colors4) {
  48523. serializationObject.colors4[name] = this._colors4[name].asArray();
  48524. }
  48525. // Vector2
  48526. serializationObject.vectors2 = {};
  48527. for (name in this._vectors2) {
  48528. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48529. }
  48530. // Vector3
  48531. serializationObject.vectors3 = {};
  48532. for (name in this._vectors3) {
  48533. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48534. }
  48535. // Vector4
  48536. serializationObject.vectors4 = {};
  48537. for (name in this._vectors4) {
  48538. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48539. }
  48540. // Matrix
  48541. serializationObject.matrices = {};
  48542. for (name in this._matrices) {
  48543. serializationObject.matrices[name] = this._matrices[name].asArray();
  48544. }
  48545. // Matrix 3x3
  48546. serializationObject.matrices3x3 = {};
  48547. for (name in this._matrices3x3) {
  48548. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48549. }
  48550. // Matrix 2x2
  48551. serializationObject.matrices2x2 = {};
  48552. for (name in this._matrices2x2) {
  48553. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48554. }
  48555. // Vector2Array
  48556. serializationObject.vectors2Arrays = {};
  48557. for (name in this._vectors2Arrays) {
  48558. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48559. }
  48560. // Vector3Array
  48561. serializationObject.vectors3Arrays = {};
  48562. for (name in this._vectors3Arrays) {
  48563. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48564. }
  48565. return serializationObject;
  48566. };
  48567. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48568. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48569. var name;
  48570. // Texture
  48571. for (name in source.textures) {
  48572. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48573. }
  48574. // Texture arrays
  48575. for (name in source.textureArrays) {
  48576. var array = source.textureArrays[name];
  48577. var textureArray = new Array();
  48578. for (var index = 0; index < array.length; index++) {
  48579. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48580. }
  48581. material.setTextureArray(name, textureArray);
  48582. }
  48583. // Float
  48584. for (name in source.floats) {
  48585. material.setFloat(name, source.floats[name]);
  48586. }
  48587. // Float s
  48588. for (name in source.floatsArrays) {
  48589. material.setFloats(name, source.floatsArrays[name]);
  48590. }
  48591. // Color3
  48592. for (name in source.colors3) {
  48593. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48594. }
  48595. // Color3 arrays
  48596. for (name in source.colors3Arrays) {
  48597. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48598. if (i % 3 === 0) {
  48599. arr.push([num]);
  48600. }
  48601. else {
  48602. arr[arr.length - 1].push(num);
  48603. }
  48604. return arr;
  48605. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48606. material.setColor3Array(name, colors);
  48607. }
  48608. // Color4
  48609. for (name in source.colors4) {
  48610. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48611. }
  48612. // Vector2
  48613. for (name in source.vectors2) {
  48614. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48615. }
  48616. // Vector3
  48617. for (name in source.vectors3) {
  48618. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48619. }
  48620. // Vector4
  48621. for (name in source.vectors4) {
  48622. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48623. }
  48624. // Matrix
  48625. for (name in source.matrices) {
  48626. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48627. }
  48628. // Matrix 3x3
  48629. for (name in source.matrices3x3) {
  48630. material.setMatrix3x3(name, source.matrices3x3[name]);
  48631. }
  48632. // Matrix 2x2
  48633. for (name in source.matrices2x2) {
  48634. material.setMatrix2x2(name, source.matrices2x2[name]);
  48635. }
  48636. // Vector2Array
  48637. for (name in source.vectors2Arrays) {
  48638. material.setArray2(name, source.vectors2Arrays[name]);
  48639. }
  48640. // Vector3Array
  48641. for (name in source.vectors3Arrays) {
  48642. material.setArray3(name, source.vectors3Arrays[name]);
  48643. }
  48644. return material;
  48645. };
  48646. return ShaderMaterial;
  48647. }(BABYLON.Material));
  48648. BABYLON.ShaderMaterial = ShaderMaterial;
  48649. })(BABYLON || (BABYLON = {}));
  48650. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48651. var BABYLON;
  48652. (function (BABYLON) {
  48653. var GroundMesh = /** @class */ (function (_super) {
  48654. __extends(GroundMesh, _super);
  48655. function GroundMesh(name, scene) {
  48656. var _this = _super.call(this, name, scene) || this;
  48657. _this.generateOctree = false;
  48658. return _this;
  48659. }
  48660. GroundMesh.prototype.getClassName = function () {
  48661. return "GroundMesh";
  48662. };
  48663. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  48664. get: function () {
  48665. return Math.min(this._subdivisionsX, this._subdivisionsY);
  48666. },
  48667. enumerable: true,
  48668. configurable: true
  48669. });
  48670. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  48671. get: function () {
  48672. return this._subdivisionsX;
  48673. },
  48674. enumerable: true,
  48675. configurable: true
  48676. });
  48677. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  48678. get: function () {
  48679. return this._subdivisionsY;
  48680. },
  48681. enumerable: true,
  48682. configurable: true
  48683. });
  48684. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  48685. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  48686. this._subdivisionsX = chunksCount;
  48687. this._subdivisionsY = chunksCount;
  48688. this.subdivide(chunksCount);
  48689. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  48690. };
  48691. /**
  48692. * Returns a height (y) value in the Worl system :
  48693. * the ground altitude at the coordinates (x, z) expressed in the World system.
  48694. * Returns the ground y position if (x, z) are outside the ground surface.
  48695. */
  48696. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  48697. var world = this.getWorldMatrix();
  48698. var invMat = BABYLON.Tmp.Matrix[5];
  48699. world.invertToRef(invMat);
  48700. var tmpVect = BABYLON.Tmp.Vector3[8];
  48701. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  48702. x = tmpVect.x;
  48703. z = tmpVect.z;
  48704. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48705. return this.position.y;
  48706. }
  48707. if (!this._heightQuads || this._heightQuads.length == 0) {
  48708. this._initHeightQuads();
  48709. this._computeHeightQuads();
  48710. }
  48711. var facet = this._getFacetAt(x, z);
  48712. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  48713. // return y in the World system
  48714. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  48715. return tmpVect.y;
  48716. };
  48717. /**
  48718. * Returns a normalized vector (Vector3) orthogonal to the ground
  48719. * at the ground coordinates (x, z) expressed in the World system.
  48720. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  48721. */
  48722. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  48723. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  48724. this.getNormalAtCoordinatesToRef(x, z, normal);
  48725. return normal;
  48726. };
  48727. /**
  48728. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  48729. * at the ground coordinates (x, z) expressed in the World system.
  48730. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  48731. * Returns the GroundMesh.
  48732. */
  48733. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  48734. var world = this.getWorldMatrix();
  48735. var tmpMat = BABYLON.Tmp.Matrix[5];
  48736. world.invertToRef(tmpMat);
  48737. var tmpVect = BABYLON.Tmp.Vector3[8];
  48738. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  48739. x = tmpVect.x;
  48740. z = tmpVect.z;
  48741. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  48742. return this;
  48743. }
  48744. if (!this._heightQuads || this._heightQuads.length == 0) {
  48745. this._initHeightQuads();
  48746. this._computeHeightQuads();
  48747. }
  48748. var facet = this._getFacetAt(x, z);
  48749. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  48750. return this;
  48751. };
  48752. /**
  48753. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  48754. * if the ground has been updated.
  48755. * This can be used in the render loop.
  48756. * Returns the GroundMesh.
  48757. */
  48758. GroundMesh.prototype.updateCoordinateHeights = function () {
  48759. if (!this._heightQuads || this._heightQuads.length == 0) {
  48760. this._initHeightQuads();
  48761. }
  48762. this._computeHeightQuads();
  48763. return this;
  48764. };
  48765. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  48766. GroundMesh.prototype._getFacetAt = function (x, z) {
  48767. // retrieve col and row from x, z coordinates in the ground local system
  48768. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  48769. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  48770. var quad = this._heightQuads[row * this._subdivisionsX + col];
  48771. var facet;
  48772. if (z < quad.slope.x * x + quad.slope.y) {
  48773. facet = quad.facet1;
  48774. }
  48775. else {
  48776. facet = quad.facet2;
  48777. }
  48778. return facet;
  48779. };
  48780. // Creates and populates the heightMap array with "facet" elements :
  48781. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  48782. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48783. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48784. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48785. // Returns the GroundMesh.
  48786. GroundMesh.prototype._initHeightQuads = function () {
  48787. var subdivisionsX = this._subdivisionsX;
  48788. var subdivisionsY = this._subdivisionsY;
  48789. this._heightQuads = new Array();
  48790. for (var row = 0; row < subdivisionsY; row++) {
  48791. for (var col = 0; col < subdivisionsX; col++) {
  48792. 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) };
  48793. this._heightQuads[row * subdivisionsX + col] = quad;
  48794. }
  48795. }
  48796. return this;
  48797. };
  48798. // Compute each quad element values and update the the heightMap array :
  48799. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  48800. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  48801. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  48802. // Returns the GroundMesh.
  48803. GroundMesh.prototype._computeHeightQuads = function () {
  48804. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48805. if (!positions) {
  48806. return this;
  48807. }
  48808. var v1 = BABYLON.Tmp.Vector3[3];
  48809. var v2 = BABYLON.Tmp.Vector3[2];
  48810. var v3 = BABYLON.Tmp.Vector3[1];
  48811. var v4 = BABYLON.Tmp.Vector3[0];
  48812. var v1v2 = BABYLON.Tmp.Vector3[4];
  48813. var v1v3 = BABYLON.Tmp.Vector3[5];
  48814. var v1v4 = BABYLON.Tmp.Vector3[6];
  48815. var norm1 = BABYLON.Tmp.Vector3[7];
  48816. var norm2 = BABYLON.Tmp.Vector3[8];
  48817. var i = 0;
  48818. var j = 0;
  48819. var k = 0;
  48820. var cd = 0; // 2D slope coefficient : z = cd * x + h
  48821. var h = 0;
  48822. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  48823. var d2 = 0;
  48824. var subdivisionsX = this._subdivisionsX;
  48825. var subdivisionsY = this._subdivisionsY;
  48826. for (var row = 0; row < subdivisionsY; row++) {
  48827. for (var col = 0; col < subdivisionsX; col++) {
  48828. i = col * 3;
  48829. j = row * (subdivisionsX + 1) * 3;
  48830. k = (row + 1) * (subdivisionsX + 1) * 3;
  48831. v1.x = positions[j + i];
  48832. v1.y = positions[j + i + 1];
  48833. v1.z = positions[j + i + 2];
  48834. v2.x = positions[j + i + 3];
  48835. v2.y = positions[j + i + 4];
  48836. v2.z = positions[j + i + 5];
  48837. v3.x = positions[k + i];
  48838. v3.y = positions[k + i + 1];
  48839. v3.z = positions[k + i + 2];
  48840. v4.x = positions[k + i + 3];
  48841. v4.y = positions[k + i + 4];
  48842. v4.z = positions[k + i + 5];
  48843. // 2D slope V1V4
  48844. cd = (v4.z - v1.z) / (v4.x - v1.x);
  48845. h = v1.z - cd * v1.x; // v1 belongs to the slope
  48846. // facet equations :
  48847. // we compute each facet normal vector
  48848. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  48849. // we compute the value d by applying the equation to v1 which belongs to the plane
  48850. // then we store the facet equation in a Vector4
  48851. v2.subtractToRef(v1, v1v2);
  48852. v3.subtractToRef(v1, v1v3);
  48853. v4.subtractToRef(v1, v1v4);
  48854. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  48855. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  48856. norm1.normalize();
  48857. norm2.normalize();
  48858. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  48859. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  48860. var quad = this._heightQuads[row * subdivisionsX + col];
  48861. quad.slope.copyFromFloats(cd, h);
  48862. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  48863. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  48864. }
  48865. }
  48866. return this;
  48867. };
  48868. GroundMesh.prototype.serialize = function (serializationObject) {
  48869. _super.prototype.serialize.call(this, serializationObject);
  48870. serializationObject.subdivisionsX = this._subdivisionsX;
  48871. serializationObject.subdivisionsY = this._subdivisionsY;
  48872. serializationObject.minX = this._minX;
  48873. serializationObject.maxX = this._maxX;
  48874. serializationObject.minZ = this._minZ;
  48875. serializationObject.maxZ = this._maxZ;
  48876. serializationObject.width = this._width;
  48877. serializationObject.height = this._height;
  48878. };
  48879. GroundMesh.Parse = function (parsedMesh, scene) {
  48880. var result = new GroundMesh(parsedMesh.name, scene);
  48881. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  48882. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  48883. result._minX = parsedMesh.minX;
  48884. result._maxX = parsedMesh.maxX;
  48885. result._minZ = parsedMesh.minZ;
  48886. result._maxZ = parsedMesh.maxZ;
  48887. result._width = parsedMesh.width;
  48888. result._height = parsedMesh.height;
  48889. return result;
  48890. };
  48891. return GroundMesh;
  48892. }(BABYLON.Mesh));
  48893. BABYLON.GroundMesh = GroundMesh;
  48894. })(BABYLON || (BABYLON = {}));
  48895. //# sourceMappingURL=babylon.groundMesh.js.map
  48896. var BABYLON;
  48897. (function (BABYLON) {
  48898. /**
  48899. * Creates an instance based on a source mesh.
  48900. */
  48901. var InstancedMesh = /** @class */ (function (_super) {
  48902. __extends(InstancedMesh, _super);
  48903. function InstancedMesh(name, source) {
  48904. var _this = _super.call(this, name, source.getScene()) || this;
  48905. source.instances.push(_this);
  48906. _this._sourceMesh = source;
  48907. _this.position.copyFrom(source.position);
  48908. _this.rotation.copyFrom(source.rotation);
  48909. _this.scaling.copyFrom(source.scaling);
  48910. if (source.rotationQuaternion) {
  48911. _this.rotationQuaternion = source.rotationQuaternion.clone();
  48912. }
  48913. _this.infiniteDistance = source.infiniteDistance;
  48914. _this.setPivotMatrix(source.getPivotMatrix());
  48915. _this.refreshBoundingInfo();
  48916. _this._syncSubMeshes();
  48917. return _this;
  48918. }
  48919. /**
  48920. * Returns the string "InstancedMesh".
  48921. */
  48922. InstancedMesh.prototype.getClassName = function () {
  48923. return "InstancedMesh";
  48924. };
  48925. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  48926. // Methods
  48927. get: function () {
  48928. return this._sourceMesh.receiveShadows;
  48929. },
  48930. enumerable: true,
  48931. configurable: true
  48932. });
  48933. Object.defineProperty(InstancedMesh.prototype, "material", {
  48934. get: function () {
  48935. return this._sourceMesh.material;
  48936. },
  48937. enumerable: true,
  48938. configurable: true
  48939. });
  48940. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  48941. get: function () {
  48942. return this._sourceMesh.visibility;
  48943. },
  48944. enumerable: true,
  48945. configurable: true
  48946. });
  48947. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  48948. get: function () {
  48949. return this._sourceMesh.skeleton;
  48950. },
  48951. enumerable: true,
  48952. configurable: true
  48953. });
  48954. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  48955. get: function () {
  48956. return this._sourceMesh.renderingGroupId;
  48957. },
  48958. enumerable: true,
  48959. configurable: true
  48960. });
  48961. /**
  48962. * Returns the total number of vertices (integer).
  48963. */
  48964. InstancedMesh.prototype.getTotalVertices = function () {
  48965. return this._sourceMesh.getTotalVertices();
  48966. };
  48967. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  48968. get: function () {
  48969. return this._sourceMesh;
  48970. },
  48971. enumerable: true,
  48972. configurable: true
  48973. });
  48974. /**
  48975. * Is this node ready to be used/rendered
  48976. * @return {boolean} is it ready
  48977. */
  48978. InstancedMesh.prototype.isReady = function () {
  48979. return this._sourceMesh.isReady(true);
  48980. };
  48981. /**
  48982. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  48983. */
  48984. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  48985. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  48986. };
  48987. /**
  48988. * Sets the vertex data of the mesh geometry for the requested `kind`.
  48989. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  48990. * The `data` are either a numeric array either a Float32Array.
  48991. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  48992. * 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).
  48993. * Note that a new underlying VertexBuffer object is created each call.
  48994. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  48995. *
  48996. * Possible `kind` values :
  48997. * - BABYLON.VertexBuffer.PositionKind
  48998. * - BABYLON.VertexBuffer.UVKind
  48999. * - BABYLON.VertexBuffer.UV2Kind
  49000. * - BABYLON.VertexBuffer.UV3Kind
  49001. * - BABYLON.VertexBuffer.UV4Kind
  49002. * - BABYLON.VertexBuffer.UV5Kind
  49003. * - BABYLON.VertexBuffer.UV6Kind
  49004. * - BABYLON.VertexBuffer.ColorKind
  49005. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49006. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49007. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49008. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49009. *
  49010. * Returns the Mesh.
  49011. */
  49012. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  49013. if (this.sourceMesh) {
  49014. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  49015. }
  49016. return this.sourceMesh;
  49017. };
  49018. /**
  49019. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  49020. * If the mesh has no geometry, it is simply returned as it is.
  49021. * The `data` are either a numeric array either a Float32Array.
  49022. * No new underlying VertexBuffer object is created.
  49023. * 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.
  49024. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  49025. *
  49026. * Possible `kind` values :
  49027. * - BABYLON.VertexBuffer.PositionKind
  49028. * - BABYLON.VertexBuffer.UVKind
  49029. * - BABYLON.VertexBuffer.UV2Kind
  49030. * - BABYLON.VertexBuffer.UV3Kind
  49031. * - BABYLON.VertexBuffer.UV4Kind
  49032. * - BABYLON.VertexBuffer.UV5Kind
  49033. * - BABYLON.VertexBuffer.UV6Kind
  49034. * - BABYLON.VertexBuffer.ColorKind
  49035. * - BABYLON.VertexBuffer.MatricesIndicesKind
  49036. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  49037. * - BABYLON.VertexBuffer.MatricesWeightsKind
  49038. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  49039. *
  49040. * Returns the Mesh.
  49041. */
  49042. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  49043. if (this.sourceMesh) {
  49044. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  49045. }
  49046. return this.sourceMesh;
  49047. };
  49048. /**
  49049. * Sets the mesh indices.
  49050. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  49051. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  49052. * This method creates a new index buffer each call.
  49053. * Returns the Mesh.
  49054. */
  49055. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  49056. if (totalVertices === void 0) { totalVertices = null; }
  49057. if (this.sourceMesh) {
  49058. this.sourceMesh.setIndices(indices, totalVertices);
  49059. }
  49060. return this.sourceMesh;
  49061. };
  49062. /**
  49063. * Boolean : True if the mesh owns the requested kind of data.
  49064. */
  49065. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  49066. return this._sourceMesh.isVerticesDataPresent(kind);
  49067. };
  49068. /**
  49069. * Returns an array of indices (IndicesArray).
  49070. */
  49071. InstancedMesh.prototype.getIndices = function () {
  49072. return this._sourceMesh.getIndices();
  49073. };
  49074. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  49075. get: function () {
  49076. return this._sourceMesh._positions;
  49077. },
  49078. enumerable: true,
  49079. configurable: true
  49080. });
  49081. /**
  49082. * Sets a new updated BoundingInfo to the mesh.
  49083. * Returns the mesh.
  49084. */
  49085. InstancedMesh.prototype.refreshBoundingInfo = function () {
  49086. var meshBB = this._sourceMesh.getBoundingInfo();
  49087. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  49088. this._updateBoundingInfo();
  49089. return this;
  49090. };
  49091. InstancedMesh.prototype._preActivate = function () {
  49092. if (this._currentLOD) {
  49093. this._currentLOD._preActivate();
  49094. }
  49095. return this;
  49096. };
  49097. InstancedMesh.prototype._activate = function (renderId) {
  49098. if (this._currentLOD) {
  49099. this._currentLOD._registerInstanceForRenderId(this, renderId);
  49100. }
  49101. return this;
  49102. };
  49103. /**
  49104. * Returns the current associated LOD AbstractMesh.
  49105. */
  49106. InstancedMesh.prototype.getLOD = function (camera) {
  49107. if (!camera) {
  49108. return this;
  49109. }
  49110. var boundingInfo = this.getBoundingInfo();
  49111. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  49112. if (this._currentLOD === this.sourceMesh) {
  49113. return this;
  49114. }
  49115. return this._currentLOD;
  49116. };
  49117. InstancedMesh.prototype._syncSubMeshes = function () {
  49118. this.releaseSubMeshes();
  49119. if (this._sourceMesh.subMeshes) {
  49120. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  49121. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  49122. }
  49123. }
  49124. return this;
  49125. };
  49126. InstancedMesh.prototype._generatePointsArray = function () {
  49127. return this._sourceMesh._generatePointsArray();
  49128. };
  49129. /**
  49130. * Creates a new InstancedMesh from the current mesh.
  49131. * - name (string) : the cloned mesh name
  49132. * - newParent (optional Node) : the optional Node to parent the clone to.
  49133. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  49134. *
  49135. * Returns the clone.
  49136. */
  49137. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49138. var result = this._sourceMesh.createInstance(name);
  49139. // Deep copy
  49140. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  49141. // Bounding info
  49142. this.refreshBoundingInfo();
  49143. // Parent
  49144. if (newParent) {
  49145. result.parent = newParent;
  49146. }
  49147. if (!doNotCloneChildren) {
  49148. // Children
  49149. for (var index = 0; index < this.getScene().meshes.length; index++) {
  49150. var mesh = this.getScene().meshes[index];
  49151. if (mesh.parent === this) {
  49152. mesh.clone(mesh.name, result);
  49153. }
  49154. }
  49155. }
  49156. result.computeWorldMatrix(true);
  49157. return result;
  49158. };
  49159. /**
  49160. * Disposes the InstancedMesh.
  49161. * Returns nothing.
  49162. */
  49163. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  49164. // Remove from mesh
  49165. var index = this._sourceMesh.instances.indexOf(this);
  49166. this._sourceMesh.instances.splice(index, 1);
  49167. _super.prototype.dispose.call(this, doNotRecurse);
  49168. };
  49169. return InstancedMesh;
  49170. }(BABYLON.AbstractMesh));
  49171. BABYLON.InstancedMesh = InstancedMesh;
  49172. })(BABYLON || (BABYLON = {}));
  49173. //# sourceMappingURL=babylon.instancedMesh.js.map
  49174. var BABYLON;
  49175. (function (BABYLON) {
  49176. var LinesMesh = /** @class */ (function (_super) {
  49177. __extends(LinesMesh, _super);
  49178. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  49179. if (scene === void 0) { scene = null; }
  49180. if (parent === void 0) { parent = null; }
  49181. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  49182. _this.useVertexColor = useVertexColor;
  49183. _this.useVertexAlpha = useVertexAlpha;
  49184. _this.color = new BABYLON.Color3(1, 1, 1);
  49185. _this.alpha = 1;
  49186. if (source) {
  49187. _this.color = source.color.clone();
  49188. _this.alpha = source.alpha;
  49189. _this.useVertexColor = source.useVertexColor;
  49190. _this.useVertexAlpha = source.useVertexAlpha;
  49191. }
  49192. _this._intersectionThreshold = 0.1;
  49193. var defines = [];
  49194. var options = {
  49195. attributes: [BABYLON.VertexBuffer.PositionKind],
  49196. uniforms: ["world", "viewProjection"],
  49197. needAlphaBlending: true,
  49198. defines: defines
  49199. };
  49200. if (useVertexAlpha === false) {
  49201. options.needAlphaBlending = false;
  49202. }
  49203. if (!useVertexColor) {
  49204. options.uniforms.push("color");
  49205. }
  49206. else {
  49207. options.defines.push("#define VERTEXCOLOR");
  49208. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  49209. }
  49210. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  49211. return _this;
  49212. }
  49213. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  49214. /**
  49215. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49216. * This margin is expressed in world space coordinates, so its value may vary.
  49217. * Default value is 0.1
  49218. * @returns the intersection Threshold value.
  49219. */
  49220. get: function () {
  49221. return this._intersectionThreshold;
  49222. },
  49223. /**
  49224. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  49225. * This margin is expressed in world space coordinates, so its value may vary.
  49226. * @param value the new threshold to apply
  49227. */
  49228. set: function (value) {
  49229. if (this._intersectionThreshold === value) {
  49230. return;
  49231. }
  49232. this._intersectionThreshold = value;
  49233. if (this.geometry) {
  49234. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  49235. }
  49236. },
  49237. enumerable: true,
  49238. configurable: true
  49239. });
  49240. /**
  49241. * Returns the string "LineMesh"
  49242. */
  49243. LinesMesh.prototype.getClassName = function () {
  49244. return "LinesMesh";
  49245. };
  49246. Object.defineProperty(LinesMesh.prototype, "material", {
  49247. get: function () {
  49248. return this._colorShader;
  49249. },
  49250. set: function (value) {
  49251. // Do nothing
  49252. },
  49253. enumerable: true,
  49254. configurable: true
  49255. });
  49256. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  49257. get: function () {
  49258. return false;
  49259. },
  49260. enumerable: true,
  49261. configurable: true
  49262. });
  49263. LinesMesh.prototype.createInstance = function (name) {
  49264. throw new Error("LinesMeshes do not support createInstance.");
  49265. };
  49266. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  49267. if (!this._geometry) {
  49268. return this;
  49269. }
  49270. // VBOs
  49271. this._geometry._bind(this._colorShader.getEffect());
  49272. // Color
  49273. if (!this.useVertexColor) {
  49274. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  49275. }
  49276. return this;
  49277. };
  49278. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  49279. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  49280. return this;
  49281. }
  49282. var engine = this.getScene().getEngine();
  49283. // Draw order
  49284. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  49285. return this;
  49286. };
  49287. LinesMesh.prototype.dispose = function (doNotRecurse) {
  49288. this._colorShader.dispose();
  49289. _super.prototype.dispose.call(this, doNotRecurse);
  49290. };
  49291. /**
  49292. * Returns a new LineMesh object cloned from the current one.
  49293. */
  49294. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  49295. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  49296. };
  49297. return LinesMesh;
  49298. }(BABYLON.Mesh));
  49299. BABYLON.LinesMesh = LinesMesh;
  49300. })(BABYLON || (BABYLON = {}));
  49301. //# sourceMappingURL=babylon.linesMesh.js.map
  49302. var BABYLON;
  49303. (function (BABYLON) {
  49304. var MeshBuilder = /** @class */ (function () {
  49305. function MeshBuilder() {
  49306. }
  49307. MeshBuilder.updateSideOrientation = function (orientation) {
  49308. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  49309. return BABYLON.Mesh.DOUBLESIDE;
  49310. }
  49311. if (orientation === undefined || orientation === null) {
  49312. return BABYLON.Mesh.FRONTSIDE;
  49313. }
  49314. return orientation;
  49315. };
  49316. /**
  49317. * Creates a box mesh.
  49318. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  49319. * The parameter `size` sets the size (float) of each box side (default 1).
  49320. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  49321. * 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).
  49322. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49324. * 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).
  49325. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49326. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49327. */
  49328. MeshBuilder.CreateBox = function (name, options, scene) {
  49329. if (scene === void 0) { scene = null; }
  49330. var box = new BABYLON.Mesh(name, scene);
  49331. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49332. box._originalBuilderSideOrientation = options.sideOrientation;
  49333. var vertexData = BABYLON.VertexData.CreateBox(options);
  49334. vertexData.applyToMesh(box, options.updatable);
  49335. return box;
  49336. };
  49337. /**
  49338. * Creates a sphere mesh.
  49339. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  49340. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  49341. * 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`).
  49342. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  49343. * 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
  49344. * 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).
  49345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49346. * 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).
  49347. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49349. */
  49350. MeshBuilder.CreateSphere = function (name, options, scene) {
  49351. var sphere = new BABYLON.Mesh(name, scene);
  49352. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49353. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49354. var vertexData = BABYLON.VertexData.CreateSphere(options);
  49355. vertexData.applyToMesh(sphere, options.updatable);
  49356. return sphere;
  49357. };
  49358. /**
  49359. * Creates a plane polygonal mesh. By default, this is a disc.
  49360. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  49361. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  49362. * 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.
  49363. * 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
  49364. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49365. * 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).
  49366. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49368. */
  49369. MeshBuilder.CreateDisc = function (name, options, scene) {
  49370. if (scene === void 0) { scene = null; }
  49371. var disc = new BABYLON.Mesh(name, scene);
  49372. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49373. disc._originalBuilderSideOrientation = options.sideOrientation;
  49374. var vertexData = BABYLON.VertexData.CreateDisc(options);
  49375. vertexData.applyToMesh(disc, options.updatable);
  49376. return disc;
  49377. };
  49378. /**
  49379. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  49380. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  49381. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  49382. * 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`).
  49383. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  49384. * 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.
  49385. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49386. * 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).
  49387. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49389. */
  49390. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  49391. var sphere = new BABYLON.Mesh(name, scene);
  49392. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49393. sphere._originalBuilderSideOrientation = options.sideOrientation;
  49394. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  49395. vertexData.applyToMesh(sphere, options.updatable);
  49396. return sphere;
  49397. };
  49398. ;
  49399. /**
  49400. * Creates a ribbon mesh.
  49401. * 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.
  49402. *
  49403. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  49404. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  49405. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  49406. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  49407. * 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.
  49408. * 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.
  49409. * 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
  49410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49411. * 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).
  49412. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49413. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49414. * 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.
  49415. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  49416. * 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
  49417. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  49418. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  49419. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49420. */
  49421. MeshBuilder.CreateRibbon = function (name, options, scene) {
  49422. if (scene === void 0) { scene = null; }
  49423. var pathArray = options.pathArray;
  49424. var closeArray = options.closeArray;
  49425. var closePath = options.closePath;
  49426. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49427. var instance = options.instance;
  49428. var updatable = options.updatable;
  49429. if (instance) {
  49430. // positionFunction : ribbon case
  49431. // only pathArray and sideOrientation parameters are taken into account for positions update
  49432. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  49433. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  49434. var positionFunction = function (positions) {
  49435. var minlg = pathArray[0].length;
  49436. var i = 0;
  49437. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  49438. for (var si = 1; si <= ns; si++) {
  49439. for (var p = 0; p < pathArray.length; p++) {
  49440. var path = pathArray[p];
  49441. var l = path.length;
  49442. minlg = (minlg < l) ? minlg : l;
  49443. var j = 0;
  49444. while (j < minlg) {
  49445. positions[i] = path[j].x;
  49446. positions[i + 1] = path[j].y;
  49447. positions[i + 2] = path[j].z;
  49448. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  49449. BABYLON.Tmp.Vector3[0].x = path[j].x;
  49450. }
  49451. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  49452. BABYLON.Tmp.Vector3[1].x = path[j].x;
  49453. }
  49454. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  49455. BABYLON.Tmp.Vector3[0].y = path[j].y;
  49456. }
  49457. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  49458. BABYLON.Tmp.Vector3[1].y = path[j].y;
  49459. }
  49460. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  49461. BABYLON.Tmp.Vector3[0].z = path[j].z;
  49462. }
  49463. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  49464. BABYLON.Tmp.Vector3[1].z = path[j].z;
  49465. }
  49466. j++;
  49467. i += 3;
  49468. }
  49469. if (instance._closePath) {
  49470. positions[i] = path[0].x;
  49471. positions[i + 1] = path[0].y;
  49472. positions[i + 2] = path[0].z;
  49473. i += 3;
  49474. }
  49475. }
  49476. }
  49477. };
  49478. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49479. positionFunction(positions);
  49480. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  49481. instance._boundingInfo.update(instance._worldMatrix);
  49482. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49483. if (options.colors) {
  49484. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49485. for (var c = 0; c < options.colors.length; c++) {
  49486. colors[c * 4] = options.colors[c].r;
  49487. colors[c * 4 + 1] = options.colors[c].g;
  49488. colors[c * 4 + 2] = options.colors[c].b;
  49489. colors[c * 4 + 3] = options.colors[c].a;
  49490. }
  49491. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  49492. }
  49493. if (options.uvs) {
  49494. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49495. for (var i = 0; i < options.uvs.length; i++) {
  49496. uvs[i * 2] = options.uvs[i].x;
  49497. uvs[i * 2 + 1] = options.uvs[i].y;
  49498. }
  49499. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  49500. }
  49501. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  49502. var indices = instance.getIndices();
  49503. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49504. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  49505. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  49506. if (instance._closePath) {
  49507. var indexFirst = 0;
  49508. var indexLast = 0;
  49509. for (var p = 0; p < pathArray.length; p++) {
  49510. indexFirst = instance._idx[p] * 3;
  49511. if (p + 1 < pathArray.length) {
  49512. indexLast = (instance._idx[p + 1] - 1) * 3;
  49513. }
  49514. else {
  49515. indexLast = normals.length - 3;
  49516. }
  49517. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49518. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49519. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49520. normals[indexLast] = normals[indexFirst];
  49521. normals[indexLast + 1] = normals[indexFirst + 1];
  49522. normals[indexLast + 2] = normals[indexFirst + 2];
  49523. }
  49524. }
  49525. if (!(instance.areNormalsFrozen)) {
  49526. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49527. }
  49528. }
  49529. return instance;
  49530. }
  49531. else {
  49532. var ribbon = new BABYLON.Mesh(name, scene);
  49533. ribbon._originalBuilderSideOrientation = sideOrientation;
  49534. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49535. if (closePath) {
  49536. ribbon._idx = vertexData._idx;
  49537. }
  49538. ribbon._closePath = closePath;
  49539. ribbon._closeArray = closeArray;
  49540. vertexData.applyToMesh(ribbon, updatable);
  49541. return ribbon;
  49542. }
  49543. };
  49544. /**
  49545. * Creates a cylinder or a cone mesh.
  49546. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49547. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49548. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49549. * 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.
  49550. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49551. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49552. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49553. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49554. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49555. * 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).
  49556. * 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
  49557. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49558. * 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
  49559. * 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.
  49560. * If `enclose` is false, a ring surface is one element.
  49561. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49562. * 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
  49563. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49564. * 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).
  49565. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49566. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49567. */
  49568. MeshBuilder.CreateCylinder = function (name, options, scene) {
  49569. var cylinder = new BABYLON.Mesh(name, scene);
  49570. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49571. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49572. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49573. vertexData.applyToMesh(cylinder, options.updatable);
  49574. return cylinder;
  49575. };
  49576. /**
  49577. * Creates a torus mesh.
  49578. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49579. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49580. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49581. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49583. * 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).
  49584. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49585. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49586. */
  49587. MeshBuilder.CreateTorus = function (name, options, scene) {
  49588. var torus = new BABYLON.Mesh(name, scene);
  49589. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49590. torus._originalBuilderSideOrientation = options.sideOrientation;
  49591. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49592. vertexData.applyToMesh(torus, options.updatable);
  49593. return torus;
  49594. };
  49595. /**
  49596. * Creates a torus knot mesh.
  49597. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49598. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49599. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49600. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49601. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49602. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49603. * 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).
  49604. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49605. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49606. */
  49607. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49608. var torusKnot = new BABYLON.Mesh(name, scene);
  49609. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49610. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49611. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49612. vertexData.applyToMesh(torusKnot, options.updatable);
  49613. return torusKnot;
  49614. };
  49615. /**
  49616. * Creates a line system mesh.
  49617. * A line system is a pool of many lines gathered in a single mesh.
  49618. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49619. * 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.
  49620. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49621. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49622. * 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
  49623. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49624. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49625. * 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
  49626. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49627. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49628. */
  49629. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49630. var instance = options.instance;
  49631. var lines = options.lines;
  49632. var colors = options.colors;
  49633. if (instance) {
  49634. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49635. var vertexColor;
  49636. var lineColors;
  49637. if (colors) {
  49638. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49639. }
  49640. var i = 0;
  49641. var c = 0;
  49642. for (var l = 0; l < lines.length; l++) {
  49643. var points = lines[l];
  49644. for (var p = 0; p < points.length; p++) {
  49645. positions[i] = points[p].x;
  49646. positions[i + 1] = points[p].y;
  49647. positions[i + 2] = points[p].z;
  49648. if (colors && vertexColor) {
  49649. lineColors = colors[l];
  49650. vertexColor[c] = lineColors[p].r;
  49651. vertexColor[c + 1] = lineColors[p].g;
  49652. vertexColor[c + 2] = lineColors[p].b;
  49653. vertexColor[c + 3] = lineColors[p].a;
  49654. c += 4;
  49655. }
  49656. i += 3;
  49657. }
  49658. }
  49659. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49660. if (colors && vertexColor) {
  49661. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49662. }
  49663. return instance;
  49664. }
  49665. // line system creation
  49666. var useVertexColor = (colors) ? true : false;
  49667. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49668. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49669. vertexData.applyToMesh(lineSystem, options.updatable);
  49670. return lineSystem;
  49671. };
  49672. /**
  49673. * Creates a line mesh.
  49674. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49675. * 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.
  49676. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49677. * The parameter `points` is an array successive Vector3.
  49678. * 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
  49679. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49680. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49681. * When updating an instance, remember that only point positions can change, not the number of points.
  49682. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49683. */
  49684. MeshBuilder.CreateLines = function (name, options, scene) {
  49685. if (scene === void 0) { scene = null; }
  49686. var colors = (options.colors) ? [options.colors] : null;
  49687. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49688. return lines;
  49689. };
  49690. /**
  49691. * Creates a dashed line mesh.
  49692. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49693. * 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.
  49694. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49695. * The parameter `points` is an array successive Vector3.
  49696. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49697. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49698. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49699. * 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
  49700. * When updating an instance, remember that only point positions can change, not the number of points.
  49701. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49702. */
  49703. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49704. if (scene === void 0) { scene = null; }
  49705. var points = options.points;
  49706. var instance = options.instance;
  49707. var gapSize = options.gapSize || 1;
  49708. var dashSize = options.dashSize || 3;
  49709. if (instance) {
  49710. var positionFunction = function (positions) {
  49711. var curvect = BABYLON.Vector3.Zero();
  49712. var nbSeg = positions.length / 6;
  49713. var lg = 0;
  49714. var nb = 0;
  49715. var shft = 0;
  49716. var dashshft = 0;
  49717. var curshft = 0;
  49718. var p = 0;
  49719. var i = 0;
  49720. var j = 0;
  49721. for (i = 0; i < points.length - 1; i++) {
  49722. points[i + 1].subtractToRef(points[i], curvect);
  49723. lg += curvect.length();
  49724. }
  49725. shft = lg / nbSeg;
  49726. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49727. for (i = 0; i < points.length - 1; i++) {
  49728. points[i + 1].subtractToRef(points[i], curvect);
  49729. nb = Math.floor(curvect.length() / shft);
  49730. curvect.normalize();
  49731. j = 0;
  49732. while (j < nb && p < positions.length) {
  49733. curshft = shft * j;
  49734. positions[p] = points[i].x + curshft * curvect.x;
  49735. positions[p + 1] = points[i].y + curshft * curvect.y;
  49736. positions[p + 2] = points[i].z + curshft * curvect.z;
  49737. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49738. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49739. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49740. p += 6;
  49741. j++;
  49742. }
  49743. }
  49744. while (p < positions.length) {
  49745. positions[p] = points[i].x;
  49746. positions[p + 1] = points[i].y;
  49747. positions[p + 2] = points[i].z;
  49748. p += 3;
  49749. }
  49750. };
  49751. instance.updateMeshPositions(positionFunction, false);
  49752. return instance;
  49753. }
  49754. // dashed lines creation
  49755. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49756. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49757. vertexData.applyToMesh(dashedLines, options.updatable);
  49758. dashedLines.dashSize = dashSize;
  49759. dashedLines.gapSize = gapSize;
  49760. return dashedLines;
  49761. };
  49762. /**
  49763. * Creates an extruded shape mesh.
  49764. * 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.
  49765. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49766. *
  49767. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49768. * 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
  49769. * extruded along the Z axis.
  49770. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49771. * 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.
  49772. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49773. * 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
  49774. * 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
  49775. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49777. * 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).
  49778. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49779. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49780. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49781. */
  49782. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49783. if (scene === void 0) { scene = null; }
  49784. var path = options.path;
  49785. var shape = options.shape;
  49786. var scale = options.scale || 1;
  49787. var rotation = options.rotation || 0;
  49788. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49789. var updatable = options.updatable;
  49790. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49791. var instance = options.instance || null;
  49792. var invertUV = options.invertUV || false;
  49793. 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);
  49794. };
  49795. /**
  49796. * Creates an custom extruded shape mesh.
  49797. * 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.
  49798. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49799. *
  49800. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49801. * 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
  49802. * extruded along the Z axis.
  49803. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49804. * 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
  49805. * and the distance of this point from the begining of the path :
  49806. * ```javascript
  49807. * var rotationFunction = function(i, distance) {
  49808. * // do things
  49809. * return rotationValue; }
  49810. * ```
  49811. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49812. * 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
  49813. * and the distance of this point from the begining of the path :
  49814. * ```javascript
  49815. * var scaleFunction = function(i, distance) {
  49816. * // do things
  49817. * return scaleValue;}
  49818. * ```
  49819. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49820. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49821. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49822. * 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
  49823. * 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
  49824. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49825. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49826. * 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).
  49827. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49828. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49829. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49830. */
  49831. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49832. var path = options.path;
  49833. var shape = options.shape;
  49834. var scaleFunction = options.scaleFunction || (function () { return 1; });
  49835. var rotationFunction = options.rotationFunction || (function () { return 0; });
  49836. var ribbonCloseArray = options.ribbonCloseArray || false;
  49837. var ribbonClosePath = options.ribbonClosePath || false;
  49838. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49839. var updatable = options.updatable;
  49840. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49841. var instance = options.instance;
  49842. var invertUV = options.invertUV || false;
  49843. 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);
  49844. };
  49845. /**
  49846. * Creates lathe mesh.
  49847. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  49848. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  49849. *
  49850. * 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
  49851. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  49852. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  49853. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  49854. * 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.
  49855. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  49856. * 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
  49857. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49858. * 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).
  49859. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49860. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49861. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49862. */
  49863. MeshBuilder.CreateLathe = function (name, options, scene) {
  49864. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  49865. var closed = (options.closed === undefined) ? true : options.closed;
  49866. var shape = options.shape;
  49867. var radius = options.radius || 1;
  49868. var tessellation = options.tessellation || 64;
  49869. var updatable = options.updatable;
  49870. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49871. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49872. var pi2 = Math.PI * 2;
  49873. var paths = new Array();
  49874. var invertUV = options.invertUV || false;
  49875. var i = 0;
  49876. var p = 0;
  49877. var step = pi2 / tessellation * arc;
  49878. var rotated;
  49879. var path = new Array();
  49880. ;
  49881. for (i = 0; i <= tessellation; i++) {
  49882. var path = [];
  49883. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  49884. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  49885. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  49886. }
  49887. for (p = 0; p < shape.length; p++) {
  49888. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  49889. path.push(rotated);
  49890. }
  49891. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  49892. 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));
  49893. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  49894. }
  49895. paths.push(path);
  49896. }
  49897. // lathe ribbon
  49898. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49899. return lathe;
  49900. };
  49901. /**
  49902. * Creates a plane mesh.
  49903. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49904. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  49905. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  49906. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  49907. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49908. * 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).
  49909. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49911. */
  49912. MeshBuilder.CreatePlane = function (name, options, scene) {
  49913. var plane = new BABYLON.Mesh(name, scene);
  49914. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49915. plane._originalBuilderSideOrientation = options.sideOrientation;
  49916. var vertexData = BABYLON.VertexData.CreatePlane(options);
  49917. vertexData.applyToMesh(plane, options.updatable);
  49918. if (options.sourcePlane) {
  49919. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  49920. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  49921. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  49922. plane.rotate(vectorProduct, product);
  49923. }
  49924. return plane;
  49925. };
  49926. /**
  49927. * Creates a ground mesh.
  49928. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49929. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  49930. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  49931. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49932. */
  49933. MeshBuilder.CreateGround = function (name, options, scene) {
  49934. var ground = new BABYLON.GroundMesh(name, scene);
  49935. ground._setReady(false);
  49936. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  49937. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  49938. ground._width = options.width || 1;
  49939. ground._height = options.height || 1;
  49940. ground._maxX = ground._width / 2;
  49941. ground._maxZ = ground._height / 2;
  49942. ground._minX = -ground._maxX;
  49943. ground._minZ = -ground._maxZ;
  49944. var vertexData = BABYLON.VertexData.CreateGround(options);
  49945. vertexData.applyToMesh(ground, options.updatable);
  49946. ground._setReady(true);
  49947. return ground;
  49948. };
  49949. /**
  49950. * Creates a tiled ground mesh.
  49951. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  49952. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  49953. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  49954. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  49955. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  49956. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  49957. * numbers of subdivisions on the ground width and height of each tile.
  49958. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49959. */
  49960. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  49961. var tiledGround = new BABYLON.Mesh(name, scene);
  49962. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  49963. vertexData.applyToMesh(tiledGround, options.updatable);
  49964. return tiledGround;
  49965. };
  49966. /**
  49967. * Creates a ground mesh from a height map.
  49968. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  49969. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  49970. * The parameter `url` sets the URL of the height map image resource.
  49971. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  49972. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  49973. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  49974. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  49975. * 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.
  49976. * 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).
  49977. * This function is passed the newly built mesh :
  49978. * ```javascript
  49979. * function(mesh) { // do things
  49980. * return; }
  49981. * ```
  49982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49983. */
  49984. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49985. var width = options.width || 10.0;
  49986. var height = options.height || 10.0;
  49987. var subdivisions = options.subdivisions || 1 | 0;
  49988. var minHeight = options.minHeight || 0.0;
  49989. var maxHeight = options.maxHeight || 1.0;
  49990. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  49991. var updatable = options.updatable;
  49992. var onReady = options.onReady;
  49993. var ground = new BABYLON.GroundMesh(name, scene);
  49994. ground._subdivisionsX = subdivisions;
  49995. ground._subdivisionsY = subdivisions;
  49996. ground._width = width;
  49997. ground._height = height;
  49998. ground._maxX = ground._width / 2.0;
  49999. ground._maxZ = ground._height / 2.0;
  50000. ground._minX = -ground._maxX;
  50001. ground._minZ = -ground._maxZ;
  50002. ground._setReady(false);
  50003. var onload = function (img) {
  50004. // Getting height map data
  50005. var canvas = document.createElement("canvas");
  50006. var context = canvas.getContext("2d");
  50007. if (!context) {
  50008. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  50009. }
  50010. if (scene.isDisposed) {
  50011. return;
  50012. }
  50013. var bufferWidth = img.width;
  50014. var bufferHeight = img.height;
  50015. canvas.width = bufferWidth;
  50016. canvas.height = bufferHeight;
  50017. context.drawImage(img, 0, 0);
  50018. // Create VertexData from map data
  50019. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  50020. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  50021. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  50022. width: width, height: height,
  50023. subdivisions: subdivisions,
  50024. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  50025. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  50026. });
  50027. vertexData.applyToMesh(ground, updatable);
  50028. ground._setReady(true);
  50029. //execute ready callback, if set
  50030. if (onReady) {
  50031. onReady(ground);
  50032. }
  50033. };
  50034. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  50035. return ground;
  50036. };
  50037. /**
  50038. * Creates a polygon mesh.
  50039. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  50040. * 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.
  50041. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50042. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50043. * 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).
  50044. * Remember you can only change the shape positions, not their number when updating a polygon.
  50045. */
  50046. MeshBuilder.CreatePolygon = function (name, options, scene) {
  50047. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50048. var shape = options.shape;
  50049. var holes = options.holes || [];
  50050. var depth = options.depth || 0;
  50051. var contours = [];
  50052. var hole = [];
  50053. for (var i = 0; i < shape.length; i++) {
  50054. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  50055. }
  50056. var epsilon = 0.00000001;
  50057. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  50058. contours.pop();
  50059. }
  50060. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  50061. for (var hNb = 0; hNb < holes.length; hNb++) {
  50062. hole = [];
  50063. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  50064. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  50065. }
  50066. polygonTriangulation.addHole(hole);
  50067. }
  50068. var polygon = polygonTriangulation.build(options.updatable, depth);
  50069. polygon._originalBuilderSideOrientation = options.sideOrientation;
  50070. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  50071. vertexData.applyToMesh(polygon, options.updatable);
  50072. return polygon;
  50073. };
  50074. ;
  50075. /**
  50076. * Creates an extruded polygon mesh, with depth in the Y direction.
  50077. * 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).
  50078. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  50079. */
  50080. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  50081. return MeshBuilder.CreatePolygon(name, options, scene);
  50082. };
  50083. ;
  50084. /**
  50085. * Creates a tube mesh.
  50086. * 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.
  50087. *
  50088. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  50089. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  50090. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  50091. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  50092. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  50093. * 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.
  50094. * It must return a radius value (positive float) :
  50095. * ```javascript
  50096. * var radiusFunction = function(i, distance) {
  50097. * // do things
  50098. * return radius; }
  50099. * ```
  50100. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  50101. * 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
  50102. * 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
  50103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50104. * 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).
  50105. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50106. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  50107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50108. */
  50109. MeshBuilder.CreateTube = function (name, options, scene) {
  50110. var path = options.path;
  50111. var instance = options.instance;
  50112. var radius = 1.0;
  50113. if (instance) {
  50114. radius = instance.radius;
  50115. }
  50116. if (options.radius !== undefined) {
  50117. radius = options.radius;
  50118. }
  50119. ;
  50120. var tessellation = options.tessellation || 64 | 0;
  50121. var radiusFunction = options.radiusFunction || null;
  50122. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  50123. var invertUV = options.invertUV || false;
  50124. var updatable = options.updatable;
  50125. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50126. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  50127. // tube geometry
  50128. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  50129. var tangents = path3D.getTangents();
  50130. var normals = path3D.getNormals();
  50131. var distances = path3D.getDistances();
  50132. var pi2 = Math.PI * 2;
  50133. var step = pi2 / tessellation * arc;
  50134. var returnRadius = function () { return radius; };
  50135. var radiusFunctionFinal = radiusFunction || returnRadius;
  50136. var circlePath;
  50137. var rad;
  50138. var normal;
  50139. var rotated;
  50140. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50141. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50142. for (var i = 0; i < path.length; i++) {
  50143. rad = radiusFunctionFinal(i, distances[i]); // current radius
  50144. circlePath = Array(); // current circle array
  50145. normal = normals[i]; // current normal
  50146. for (var t = 0; t < tessellation; t++) {
  50147. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  50148. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  50149. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  50150. rotated.scaleInPlace(rad).addInPlace(path[i]);
  50151. circlePath[t] = rotated;
  50152. }
  50153. circlePaths[index] = circlePath;
  50154. index++;
  50155. }
  50156. // cap
  50157. var capPath = function (nbPoints, pathIndex) {
  50158. var pointCap = Array();
  50159. for (var i = 0; i < nbPoints; i++) {
  50160. pointCap.push(path[pathIndex]);
  50161. }
  50162. return pointCap;
  50163. };
  50164. switch (cap) {
  50165. case BABYLON.Mesh.NO_CAP:
  50166. break;
  50167. case BABYLON.Mesh.CAP_START:
  50168. circlePaths[0] = capPath(tessellation, 0);
  50169. circlePaths[1] = circlePaths[2].slice(0);
  50170. break;
  50171. case BABYLON.Mesh.CAP_END:
  50172. circlePaths[index] = circlePaths[index - 1].slice(0);
  50173. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50174. break;
  50175. case BABYLON.Mesh.CAP_ALL:
  50176. circlePaths[0] = capPath(tessellation, 0);
  50177. circlePaths[1] = circlePaths[2].slice(0);
  50178. circlePaths[index] = circlePaths[index - 1].slice(0);
  50179. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  50180. break;
  50181. default:
  50182. break;
  50183. }
  50184. return circlePaths;
  50185. };
  50186. var path3D;
  50187. var pathArray;
  50188. if (instance) {
  50189. var arc = options.arc || instance.arc;
  50190. path3D = (instance.path3D).update(path);
  50191. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  50192. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  50193. instance.path3D = path3D;
  50194. instance.pathArray = pathArray;
  50195. instance.arc = arc;
  50196. instance.radius = radius;
  50197. return instance;
  50198. }
  50199. // tube creation
  50200. path3D = new BABYLON.Path3D(path);
  50201. var newPathArray = new Array();
  50202. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50203. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  50204. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  50205. tube.pathArray = pathArray;
  50206. tube.path3D = path3D;
  50207. tube.tessellation = tessellation;
  50208. tube.cap = cap;
  50209. tube.arc = options.arc;
  50210. tube.radius = radius;
  50211. return tube;
  50212. };
  50213. /**
  50214. * Creates a polyhedron mesh.
  50215. *
  50216. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  50217. * 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
  50218. * to choose the wanted type.
  50219. * The parameter `size` (positive float, default 1) sets the polygon size.
  50220. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  50221. * 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`.
  50222. * 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
  50223. * 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)`).
  50224. * 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
  50225. * 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.
  50226. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  50227. * 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).
  50228. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  50229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  50230. */
  50231. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  50232. var polyhedron = new BABYLON.Mesh(name, scene);
  50233. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  50234. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  50235. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  50236. vertexData.applyToMesh(polyhedron, options.updatable);
  50237. return polyhedron;
  50238. };
  50239. /**
  50240. * Creates a decal mesh.
  50241. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  50242. * 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.
  50243. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  50244. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  50245. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  50246. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  50247. */
  50248. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  50249. var indices = sourceMesh.getIndices();
  50250. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50251. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50252. var position = options.position || BABYLON.Vector3.Zero();
  50253. var normal = options.normal || BABYLON.Vector3.Up();
  50254. var size = options.size || BABYLON.Vector3.One();
  50255. var angle = options.angle || 0;
  50256. // Getting correct rotation
  50257. if (!normal) {
  50258. var target = new BABYLON.Vector3(0, 0, 1);
  50259. var camera = sourceMesh.getScene().activeCamera;
  50260. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  50261. normal = camera.globalPosition.subtract(cameraWorldTarget);
  50262. }
  50263. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  50264. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  50265. var pitch = Math.atan2(normal.y, len);
  50266. // Matrix
  50267. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  50268. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  50269. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  50270. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  50271. var vertexData = new BABYLON.VertexData();
  50272. vertexData.indices = [];
  50273. vertexData.positions = [];
  50274. vertexData.normals = [];
  50275. vertexData.uvs = [];
  50276. var currentVertexDataIndex = 0;
  50277. var extractDecalVector3 = function (indexId) {
  50278. var result = new BABYLON.PositionNormalVertex();
  50279. if (!indices || !positions || !normals) {
  50280. return result;
  50281. }
  50282. var vertexId = indices[indexId];
  50283. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  50284. // Send vector to decal local world
  50285. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  50286. // Get normal
  50287. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  50288. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  50289. return result;
  50290. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  50291. var clip = function (vertices, axis) {
  50292. if (vertices.length === 0) {
  50293. return vertices;
  50294. }
  50295. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  50296. var clipVertices = function (v0, v1) {
  50297. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  50298. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  50299. };
  50300. var result = new Array();
  50301. for (var index = 0; index < vertices.length; index += 3) {
  50302. var v1Out;
  50303. var v2Out;
  50304. var v3Out;
  50305. var total = 0;
  50306. var nV1 = null;
  50307. var nV2 = null;
  50308. var nV3 = null;
  50309. var nV4 = null;
  50310. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  50311. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  50312. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  50313. v1Out = d1 > 0;
  50314. v2Out = d2 > 0;
  50315. v3Out = d3 > 0;
  50316. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  50317. switch (total) {
  50318. case 0:
  50319. result.push(vertices[index]);
  50320. result.push(vertices[index + 1]);
  50321. result.push(vertices[index + 2]);
  50322. break;
  50323. case 1:
  50324. if (v1Out) {
  50325. nV1 = vertices[index + 1];
  50326. nV2 = vertices[index + 2];
  50327. nV3 = clipVertices(vertices[index], nV1);
  50328. nV4 = clipVertices(vertices[index], nV2);
  50329. }
  50330. if (v2Out) {
  50331. nV1 = vertices[index];
  50332. nV2 = vertices[index + 2];
  50333. nV3 = clipVertices(vertices[index + 1], nV1);
  50334. nV4 = clipVertices(vertices[index + 1], nV2);
  50335. result.push(nV3);
  50336. result.push(nV2.clone());
  50337. result.push(nV1.clone());
  50338. result.push(nV2.clone());
  50339. result.push(nV3.clone());
  50340. result.push(nV4);
  50341. break;
  50342. }
  50343. if (v3Out) {
  50344. nV1 = vertices[index];
  50345. nV2 = vertices[index + 1];
  50346. nV3 = clipVertices(vertices[index + 2], nV1);
  50347. nV4 = clipVertices(vertices[index + 2], nV2);
  50348. }
  50349. if (nV1 && nV2 && nV3 && nV4) {
  50350. result.push(nV1.clone());
  50351. result.push(nV2.clone());
  50352. result.push(nV3);
  50353. result.push(nV4);
  50354. result.push(nV3.clone());
  50355. result.push(nV2.clone());
  50356. }
  50357. break;
  50358. case 2:
  50359. if (!v1Out) {
  50360. nV1 = vertices[index].clone();
  50361. nV2 = clipVertices(nV1, vertices[index + 1]);
  50362. nV3 = clipVertices(nV1, vertices[index + 2]);
  50363. result.push(nV1);
  50364. result.push(nV2);
  50365. result.push(nV3);
  50366. }
  50367. if (!v2Out) {
  50368. nV1 = vertices[index + 1].clone();
  50369. nV2 = clipVertices(nV1, vertices[index + 2]);
  50370. nV3 = clipVertices(nV1, vertices[index]);
  50371. result.push(nV1);
  50372. result.push(nV2);
  50373. result.push(nV3);
  50374. }
  50375. if (!v3Out) {
  50376. nV1 = vertices[index + 2].clone();
  50377. nV2 = clipVertices(nV1, vertices[index]);
  50378. nV3 = clipVertices(nV1, vertices[index + 1]);
  50379. result.push(nV1);
  50380. result.push(nV2);
  50381. result.push(nV3);
  50382. }
  50383. break;
  50384. case 3:
  50385. break;
  50386. }
  50387. }
  50388. return result;
  50389. };
  50390. for (var index = 0; index < indices.length; index += 3) {
  50391. var faceVertices = new Array();
  50392. faceVertices.push(extractDecalVector3(index));
  50393. faceVertices.push(extractDecalVector3(index + 1));
  50394. faceVertices.push(extractDecalVector3(index + 2));
  50395. // Clip
  50396. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  50397. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  50398. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  50399. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  50400. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  50401. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  50402. if (faceVertices.length === 0) {
  50403. continue;
  50404. }
  50405. // Add UVs and get back to world
  50406. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  50407. var vertex = faceVertices[vIndex];
  50408. //TODO check for Int32Array | Uint32Array | Uint16Array
  50409. vertexData.indices.push(currentVertexDataIndex);
  50410. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  50411. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  50412. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  50413. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  50414. currentVertexDataIndex++;
  50415. }
  50416. }
  50417. // Return mesh
  50418. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  50419. vertexData.applyToMesh(decal);
  50420. decal.position = position.clone();
  50421. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  50422. return decal;
  50423. };
  50424. // Privates
  50425. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  50426. // extrusion geometry
  50427. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  50428. var tangents = path3D.getTangents();
  50429. var normals = path3D.getNormals();
  50430. var binormals = path3D.getBinormals();
  50431. var distances = path3D.getDistances();
  50432. var angle = 0;
  50433. var returnScale = function () { return scale !== null ? scale : 1; };
  50434. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  50435. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  50436. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  50437. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  50438. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  50439. for (var i = 0; i < curve.length; i++) {
  50440. var shapePath = new Array();
  50441. var angleStep = rotate(i, distances[i]);
  50442. var scaleRatio = scl(i, distances[i]);
  50443. for (var p = 0; p < shape.length; p++) {
  50444. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  50445. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  50446. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  50447. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  50448. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  50449. shapePath[p] = rotated;
  50450. }
  50451. shapePaths[index] = shapePath;
  50452. angle += angleStep;
  50453. index++;
  50454. }
  50455. // cap
  50456. var capPath = function (shapePath) {
  50457. var pointCap = Array();
  50458. var barycenter = BABYLON.Vector3.Zero();
  50459. var i;
  50460. for (i = 0; i < shapePath.length; i++) {
  50461. barycenter.addInPlace(shapePath[i]);
  50462. }
  50463. barycenter.scaleInPlace(1.0 / shapePath.length);
  50464. for (i = 0; i < shapePath.length; i++) {
  50465. pointCap.push(barycenter);
  50466. }
  50467. return pointCap;
  50468. };
  50469. switch (cap) {
  50470. case BABYLON.Mesh.NO_CAP:
  50471. break;
  50472. case BABYLON.Mesh.CAP_START:
  50473. shapePaths[0] = capPath(shapePaths[2]);
  50474. shapePaths[1] = shapePaths[2];
  50475. break;
  50476. case BABYLON.Mesh.CAP_END:
  50477. shapePaths[index] = shapePaths[index - 1];
  50478. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50479. break;
  50480. case BABYLON.Mesh.CAP_ALL:
  50481. shapePaths[0] = capPath(shapePaths[2]);
  50482. shapePaths[1] = shapePaths[2];
  50483. shapePaths[index] = shapePaths[index - 1];
  50484. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  50485. break;
  50486. default:
  50487. break;
  50488. }
  50489. return shapePaths;
  50490. };
  50491. var path3D;
  50492. var pathArray;
  50493. if (instance) {
  50494. path3D = (instance.path3D).update(curve);
  50495. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  50496. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  50497. return instance;
  50498. }
  50499. // extruded shape creation
  50500. path3D = new BABYLON.Path3D(curve);
  50501. var newShapePaths = new Array();
  50502. cap = (cap < 0 || cap > 3) ? 0 : cap;
  50503. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  50504. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  50505. extrudedGeneric.pathArray = pathArray;
  50506. extrudedGeneric.path3D = path3D;
  50507. extrudedGeneric.cap = cap;
  50508. return extrudedGeneric;
  50509. };
  50510. return MeshBuilder;
  50511. }());
  50512. BABYLON.MeshBuilder = MeshBuilder;
  50513. })(BABYLON || (BABYLON = {}));
  50514. //# sourceMappingURL=babylon.meshBuilder.js.map
  50515. var BABYLON;
  50516. (function (BABYLON) {
  50517. var AudioEngine = /** @class */ (function () {
  50518. function AudioEngine() {
  50519. this._audioContext = null;
  50520. this._audioContextInitialized = false;
  50521. this.canUseWebAudio = false;
  50522. this.WarnedWebAudioUnsupported = false;
  50523. this.unlocked = false;
  50524. this.isMP3supported = false;
  50525. this.isOGGsupported = false;
  50526. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50527. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50528. this.canUseWebAudio = true;
  50529. }
  50530. var audioElem = document.createElement('audio');
  50531. try {
  50532. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50533. this.isMP3supported = true;
  50534. }
  50535. }
  50536. catch (e) {
  50537. // protect error during capability check.
  50538. }
  50539. try {
  50540. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50541. this.isOGGsupported = true;
  50542. }
  50543. }
  50544. catch (e) {
  50545. // protect error during capability check.
  50546. }
  50547. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50548. this._unlockiOSaudio();
  50549. }
  50550. else {
  50551. this.unlocked = true;
  50552. }
  50553. }
  50554. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50555. get: function () {
  50556. if (!this._audioContextInitialized) {
  50557. this._initializeAudioContext();
  50558. }
  50559. return this._audioContext;
  50560. },
  50561. enumerable: true,
  50562. configurable: true
  50563. });
  50564. AudioEngine.prototype._unlockiOSaudio = function () {
  50565. var _this = this;
  50566. var unlockaudio = function () {
  50567. if (!_this.audioContext) {
  50568. return;
  50569. }
  50570. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50571. var source = _this.audioContext.createBufferSource();
  50572. source.buffer = buffer;
  50573. source.connect(_this.audioContext.destination);
  50574. source.start(0);
  50575. setTimeout(function () {
  50576. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50577. _this.unlocked = true;
  50578. window.removeEventListener('touchend', unlockaudio, false);
  50579. if (_this.onAudioUnlocked) {
  50580. _this.onAudioUnlocked();
  50581. }
  50582. }
  50583. }, 0);
  50584. };
  50585. window.addEventListener('touchend', unlockaudio, false);
  50586. };
  50587. AudioEngine.prototype._initializeAudioContext = function () {
  50588. try {
  50589. if (this.canUseWebAudio) {
  50590. this._audioContext = new AudioContext();
  50591. // create a global volume gain node
  50592. this.masterGain = this._audioContext.createGain();
  50593. this.masterGain.gain.value = 1;
  50594. this.masterGain.connect(this._audioContext.destination);
  50595. this._audioContextInitialized = true;
  50596. }
  50597. }
  50598. catch (e) {
  50599. this.canUseWebAudio = false;
  50600. BABYLON.Tools.Error("Web Audio: " + e.message);
  50601. }
  50602. };
  50603. AudioEngine.prototype.dispose = function () {
  50604. if (this.canUseWebAudio && this._audioContextInitialized) {
  50605. if (this._connectedAnalyser && this._audioContext) {
  50606. this._connectedAnalyser.stopDebugCanvas();
  50607. this._connectedAnalyser.dispose();
  50608. this.masterGain.disconnect();
  50609. this.masterGain.connect(this._audioContext.destination);
  50610. this._connectedAnalyser = null;
  50611. }
  50612. this.masterGain.gain.value = 1;
  50613. }
  50614. this.WarnedWebAudioUnsupported = false;
  50615. };
  50616. AudioEngine.prototype.getGlobalVolume = function () {
  50617. if (this.canUseWebAudio && this._audioContextInitialized) {
  50618. return this.masterGain.gain.value;
  50619. }
  50620. else {
  50621. return -1;
  50622. }
  50623. };
  50624. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50625. if (this.canUseWebAudio && this._audioContextInitialized) {
  50626. this.masterGain.gain.value = newVolume;
  50627. }
  50628. };
  50629. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50630. if (this._connectedAnalyser) {
  50631. this._connectedAnalyser.stopDebugCanvas();
  50632. }
  50633. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50634. this._connectedAnalyser = analyser;
  50635. this.masterGain.disconnect();
  50636. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50637. }
  50638. };
  50639. return AudioEngine;
  50640. }());
  50641. BABYLON.AudioEngine = AudioEngine;
  50642. })(BABYLON || (BABYLON = {}));
  50643. //# sourceMappingURL=babylon.audioEngine.js.map
  50644. var BABYLON;
  50645. (function (BABYLON) {
  50646. var Sound = /** @class */ (function () {
  50647. /**
  50648. * Create a sound and attach it to a scene
  50649. * @param name Name of your sound
  50650. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50651. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50652. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50653. */
  50654. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50655. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50656. var _this = this;
  50657. this.autoplay = false;
  50658. this.loop = false;
  50659. this.useCustomAttenuation = false;
  50660. this.spatialSound = false;
  50661. this.refDistance = 1;
  50662. this.rolloffFactor = 1;
  50663. this.maxDistance = 100;
  50664. this.distanceModel = "linear";
  50665. this._panningModel = "equalpower";
  50666. this._playbackRate = 1;
  50667. this._streaming = false;
  50668. this._startTime = 0;
  50669. this._startOffset = 0;
  50670. this._position = BABYLON.Vector3.Zero();
  50671. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50672. this._volume = 1;
  50673. this._isReadyToPlay = false;
  50674. this.isPlaying = false;
  50675. this.isPaused = false;
  50676. this._isDirectional = false;
  50677. // Used if you'd like to create a directional sound.
  50678. // If not set, the sound will be omnidirectional
  50679. this._coneInnerAngle = 360;
  50680. this._coneOuterAngle = 360;
  50681. this._coneOuterGain = 0;
  50682. this._isOutputConnected = false;
  50683. this._urlType = "Unknown";
  50684. this.name = name;
  50685. this._scene = scene;
  50686. this._readyToPlayCallback = readyToPlayCallback;
  50687. // Default custom attenuation function is a linear attenuation
  50688. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50689. if (currentDistance < maxDistance) {
  50690. return currentVolume * (1 - currentDistance / maxDistance);
  50691. }
  50692. else {
  50693. return 0;
  50694. }
  50695. };
  50696. if (options) {
  50697. this.autoplay = options.autoplay || false;
  50698. this.loop = options.loop || false;
  50699. // if volume === 0, we need another way to check this option
  50700. if (options.volume !== undefined) {
  50701. this._volume = options.volume;
  50702. }
  50703. this.spatialSound = options.spatialSound || false;
  50704. this.maxDistance = options.maxDistance || 100;
  50705. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50706. this.rolloffFactor = options.rolloffFactor || 1;
  50707. this.refDistance = options.refDistance || 1;
  50708. this.distanceModel = options.distanceModel || "linear";
  50709. this._playbackRate = options.playbackRate || 1;
  50710. this._streaming = options.streaming || false;
  50711. }
  50712. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50713. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50714. this._soundGain.gain.value = this._volume;
  50715. this._inputAudioNode = this._soundGain;
  50716. this._ouputAudioNode = this._soundGain;
  50717. if (this.spatialSound) {
  50718. this._createSpatialParameters();
  50719. }
  50720. this._scene.mainSoundTrack.AddSound(this);
  50721. var validParameter = true;
  50722. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50723. if (urlOrArrayBuffer) {
  50724. if (typeof (urlOrArrayBuffer) === "string")
  50725. this._urlType = "String";
  50726. if (Array.isArray(urlOrArrayBuffer))
  50727. this._urlType = "Array";
  50728. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50729. this._urlType = "ArrayBuffer";
  50730. var urls = [];
  50731. var codecSupportedFound = false;
  50732. switch (this._urlType) {
  50733. case "ArrayBuffer":
  50734. if (urlOrArrayBuffer.byteLength > 0) {
  50735. codecSupportedFound = true;
  50736. this._soundLoaded(urlOrArrayBuffer);
  50737. }
  50738. break;
  50739. case "String":
  50740. urls.push(urlOrArrayBuffer);
  50741. case "Array":
  50742. if (urls.length === 0)
  50743. urls = urlOrArrayBuffer;
  50744. // If we found a supported format, we load it immediately and stop the loop
  50745. for (var i = 0; i < urls.length; i++) {
  50746. var url = urls[i];
  50747. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50748. codecSupportedFound = true;
  50749. }
  50750. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50751. codecSupportedFound = true;
  50752. }
  50753. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50754. codecSupportedFound = true;
  50755. }
  50756. if (url.indexOf("blob:") !== -1) {
  50757. codecSupportedFound = true;
  50758. }
  50759. if (codecSupportedFound) {
  50760. // Loading sound using XHR2
  50761. if (!this._streaming) {
  50762. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50763. }
  50764. else {
  50765. this._htmlAudioElement = new Audio(url);
  50766. this._htmlAudioElement.controls = false;
  50767. this._htmlAudioElement.loop = this.loop;
  50768. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50769. this._htmlAudioElement.preload = "auto";
  50770. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50771. _this._isReadyToPlay = true;
  50772. if (_this.autoplay) {
  50773. _this.play();
  50774. }
  50775. if (_this._readyToPlayCallback) {
  50776. _this._readyToPlayCallback();
  50777. }
  50778. });
  50779. document.body.appendChild(this._htmlAudioElement);
  50780. }
  50781. break;
  50782. }
  50783. }
  50784. break;
  50785. default:
  50786. validParameter = false;
  50787. break;
  50788. }
  50789. if (!validParameter) {
  50790. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50791. }
  50792. else {
  50793. if (!codecSupportedFound) {
  50794. this._isReadyToPlay = true;
  50795. // Simulating a ready to play event to avoid breaking code path
  50796. if (this._readyToPlayCallback) {
  50797. window.setTimeout(function () {
  50798. if (_this._readyToPlayCallback) {
  50799. _this._readyToPlayCallback();
  50800. }
  50801. }, 1000);
  50802. }
  50803. }
  50804. }
  50805. }
  50806. }
  50807. else {
  50808. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50809. this._scene.mainSoundTrack.AddSound(this);
  50810. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50811. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50812. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50813. }
  50814. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50815. if (this._readyToPlayCallback) {
  50816. window.setTimeout(function () {
  50817. if (_this._readyToPlayCallback) {
  50818. _this._readyToPlayCallback();
  50819. }
  50820. }, 1000);
  50821. }
  50822. }
  50823. }
  50824. Sound.prototype.dispose = function () {
  50825. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50826. if (this.isPlaying) {
  50827. this.stop();
  50828. }
  50829. this._isReadyToPlay = false;
  50830. if (this.soundTrackId === -1) {
  50831. this._scene.mainSoundTrack.RemoveSound(this);
  50832. }
  50833. else {
  50834. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  50835. }
  50836. if (this._soundGain) {
  50837. this._soundGain.disconnect();
  50838. this._soundGain = null;
  50839. }
  50840. if (this._soundPanner) {
  50841. this._soundPanner.disconnect();
  50842. this._soundPanner = null;
  50843. }
  50844. if (this._soundSource) {
  50845. this._soundSource.disconnect();
  50846. this._soundSource = null;
  50847. }
  50848. this._audioBuffer = null;
  50849. if (this._htmlAudioElement) {
  50850. this._htmlAudioElement.pause();
  50851. this._htmlAudioElement.src = "";
  50852. document.body.removeChild(this._htmlAudioElement);
  50853. }
  50854. if (this._connectedMesh && this._registerFunc) {
  50855. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50856. this._connectedMesh = null;
  50857. }
  50858. }
  50859. };
  50860. Sound.prototype.isReady = function () {
  50861. return this._isReadyToPlay;
  50862. };
  50863. Sound.prototype._soundLoaded = function (audioData) {
  50864. var _this = this;
  50865. if (!BABYLON.Engine.audioEngine.audioContext) {
  50866. return;
  50867. }
  50868. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  50869. _this._audioBuffer = buffer;
  50870. _this._isReadyToPlay = true;
  50871. if (_this.autoplay) {
  50872. _this.play();
  50873. }
  50874. if (_this._readyToPlayCallback) {
  50875. _this._readyToPlayCallback();
  50876. }
  50877. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  50878. };
  50879. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  50880. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50881. this._audioBuffer = audioBuffer;
  50882. this._isReadyToPlay = true;
  50883. }
  50884. };
  50885. Sound.prototype.updateOptions = function (options) {
  50886. if (options) {
  50887. this.loop = options.loop || this.loop;
  50888. this.maxDistance = options.maxDistance || this.maxDistance;
  50889. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  50890. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  50891. this.refDistance = options.refDistance || this.refDistance;
  50892. this.distanceModel = options.distanceModel || this.distanceModel;
  50893. this._playbackRate = options.playbackRate || this._playbackRate;
  50894. this._updateSpatialParameters();
  50895. if (this.isPlaying) {
  50896. if (this._streaming) {
  50897. this._htmlAudioElement.playbackRate = this._playbackRate;
  50898. }
  50899. else {
  50900. if (this._soundSource) {
  50901. this._soundSource.playbackRate.value = this._playbackRate;
  50902. }
  50903. }
  50904. }
  50905. }
  50906. };
  50907. Sound.prototype._createSpatialParameters = function () {
  50908. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50909. if (this._scene.headphone) {
  50910. this._panningModel = "HRTF";
  50911. }
  50912. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  50913. this._updateSpatialParameters();
  50914. this._soundPanner.connect(this._ouputAudioNode);
  50915. this._inputAudioNode = this._soundPanner;
  50916. }
  50917. };
  50918. Sound.prototype._updateSpatialParameters = function () {
  50919. if (this.spatialSound && this._soundPanner) {
  50920. if (this.useCustomAttenuation) {
  50921. // Tricks to disable in a way embedded Web Audio attenuation
  50922. this._soundPanner.distanceModel = "linear";
  50923. this._soundPanner.maxDistance = Number.MAX_VALUE;
  50924. this._soundPanner.refDistance = 1;
  50925. this._soundPanner.rolloffFactor = 1;
  50926. this._soundPanner.panningModel = this._panningModel;
  50927. }
  50928. else {
  50929. this._soundPanner.distanceModel = this.distanceModel;
  50930. this._soundPanner.maxDistance = this.maxDistance;
  50931. this._soundPanner.refDistance = this.refDistance;
  50932. this._soundPanner.rolloffFactor = this.rolloffFactor;
  50933. this._soundPanner.panningModel = this._panningModel;
  50934. }
  50935. }
  50936. };
  50937. Sound.prototype.switchPanningModelToHRTF = function () {
  50938. this._panningModel = "HRTF";
  50939. this._switchPanningModel();
  50940. };
  50941. Sound.prototype.switchPanningModelToEqualPower = function () {
  50942. this._panningModel = "equalpower";
  50943. this._switchPanningModel();
  50944. };
  50945. Sound.prototype._switchPanningModel = function () {
  50946. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50947. this._soundPanner.panningModel = this._panningModel;
  50948. }
  50949. };
  50950. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  50951. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50952. if (this._isOutputConnected) {
  50953. this._ouputAudioNode.disconnect();
  50954. }
  50955. this._ouputAudioNode.connect(soundTrackAudioNode);
  50956. this._isOutputConnected = true;
  50957. }
  50958. };
  50959. /**
  50960. * Transform this sound into a directional source
  50961. * @param coneInnerAngle Size of the inner cone in degree
  50962. * @param coneOuterAngle Size of the outer cone in degree
  50963. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  50964. */
  50965. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  50966. if (coneOuterAngle < coneInnerAngle) {
  50967. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  50968. return;
  50969. }
  50970. this._coneInnerAngle = coneInnerAngle;
  50971. this._coneOuterAngle = coneOuterAngle;
  50972. this._coneOuterGain = coneOuterGain;
  50973. this._isDirectional = true;
  50974. if (this.isPlaying && this.loop) {
  50975. this.stop();
  50976. this.play();
  50977. }
  50978. };
  50979. Sound.prototype.setPosition = function (newPosition) {
  50980. this._position = newPosition;
  50981. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50982. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50983. }
  50984. };
  50985. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  50986. this._localDirection = newLocalDirection;
  50987. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  50988. this._updateDirection();
  50989. }
  50990. };
  50991. Sound.prototype._updateDirection = function () {
  50992. if (!this._connectedMesh || !this._soundPanner) {
  50993. return;
  50994. }
  50995. var mat = this._connectedMesh.getWorldMatrix();
  50996. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  50997. direction.normalize();
  50998. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  50999. };
  51000. Sound.prototype.updateDistanceFromListener = function () {
  51001. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  51002. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  51003. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  51004. }
  51005. };
  51006. Sound.prototype.setAttenuationFunction = function (callback) {
  51007. this._customAttenuationFunction = callback;
  51008. };
  51009. /**
  51010. * Play the sound
  51011. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  51012. * @param offset (optional) Start the sound setting it at a specific time
  51013. */
  51014. Sound.prototype.play = function (time, offset) {
  51015. var _this = this;
  51016. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  51017. try {
  51018. if (this._startOffset < 0) {
  51019. time = -this._startOffset;
  51020. this._startOffset = 0;
  51021. }
  51022. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51023. if (!this._soundSource || !this._streamingSource) {
  51024. if (this.spatialSound && this._soundPanner) {
  51025. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  51026. if (this._isDirectional) {
  51027. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  51028. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  51029. this._soundPanner.coneOuterGain = this._coneOuterGain;
  51030. if (this._connectedMesh) {
  51031. this._updateDirection();
  51032. }
  51033. else {
  51034. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  51035. }
  51036. }
  51037. }
  51038. }
  51039. if (this._streaming) {
  51040. if (!this._streamingSource) {
  51041. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  51042. this._htmlAudioElement.onended = function () { _this._onended(); };
  51043. this._htmlAudioElement.playbackRate = this._playbackRate;
  51044. }
  51045. this._streamingSource.disconnect();
  51046. this._streamingSource.connect(this._inputAudioNode);
  51047. this._htmlAudioElement.play();
  51048. }
  51049. else {
  51050. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  51051. this._soundSource.buffer = this._audioBuffer;
  51052. this._soundSource.connect(this._inputAudioNode);
  51053. this._soundSource.loop = this.loop;
  51054. this._soundSource.playbackRate.value = this._playbackRate;
  51055. this._soundSource.onended = function () { _this._onended(); };
  51056. if (this._soundSource.buffer) {
  51057. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  51058. }
  51059. }
  51060. this._startTime = startTime;
  51061. this.isPlaying = true;
  51062. this.isPaused = false;
  51063. }
  51064. catch (ex) {
  51065. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  51066. }
  51067. }
  51068. };
  51069. Sound.prototype._onended = function () {
  51070. this.isPlaying = false;
  51071. if (this.onended) {
  51072. this.onended();
  51073. }
  51074. };
  51075. /**
  51076. * Stop the sound
  51077. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  51078. */
  51079. Sound.prototype.stop = function (time) {
  51080. if (this.isPlaying) {
  51081. if (this._streaming) {
  51082. this._htmlAudioElement.pause();
  51083. // Test needed for Firefox or it will generate an Invalid State Error
  51084. if (this._htmlAudioElement.currentTime > 0) {
  51085. this._htmlAudioElement.currentTime = 0;
  51086. }
  51087. }
  51088. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  51089. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  51090. this._soundSource.stop(stopTime);
  51091. this._soundSource.onended = function () { };
  51092. if (!this.isPaused) {
  51093. this._startOffset = 0;
  51094. }
  51095. }
  51096. this.isPlaying = false;
  51097. }
  51098. };
  51099. Sound.prototype.pause = function () {
  51100. if (this.isPlaying) {
  51101. this.isPaused = true;
  51102. if (this._streaming) {
  51103. this._htmlAudioElement.pause();
  51104. }
  51105. else if (BABYLON.Engine.audioEngine.audioContext) {
  51106. this.stop(0);
  51107. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  51108. }
  51109. }
  51110. };
  51111. Sound.prototype.setVolume = function (newVolume, time) {
  51112. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  51113. if (time && BABYLON.Engine.audioEngine.audioContext) {
  51114. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  51115. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  51116. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  51117. }
  51118. else {
  51119. this._soundGain.gain.value = newVolume;
  51120. }
  51121. }
  51122. this._volume = newVolume;
  51123. };
  51124. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  51125. this._playbackRate = newPlaybackRate;
  51126. if (this.isPlaying) {
  51127. if (this._streaming) {
  51128. this._htmlAudioElement.playbackRate = this._playbackRate;
  51129. }
  51130. else if (this._soundSource) {
  51131. this._soundSource.playbackRate.value = this._playbackRate;
  51132. }
  51133. }
  51134. };
  51135. Sound.prototype.getVolume = function () {
  51136. return this._volume;
  51137. };
  51138. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  51139. var _this = this;
  51140. if (this._connectedMesh && this._registerFunc) {
  51141. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51142. this._registerFunc = null;
  51143. }
  51144. this._connectedMesh = meshToConnectTo;
  51145. if (!this.spatialSound) {
  51146. this.spatialSound = true;
  51147. this._createSpatialParameters();
  51148. if (this.isPlaying && this.loop) {
  51149. this.stop();
  51150. this.play();
  51151. }
  51152. }
  51153. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  51154. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  51155. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  51156. };
  51157. Sound.prototype.detachFromMesh = function () {
  51158. if (this._connectedMesh && this._registerFunc) {
  51159. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  51160. this._registerFunc = null;
  51161. this._connectedMesh = null;
  51162. }
  51163. };
  51164. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  51165. if (!node.getBoundingInfo) {
  51166. return;
  51167. }
  51168. var mesh = node;
  51169. var boundingInfo = mesh.getBoundingInfo();
  51170. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  51171. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  51172. this._updateDirection();
  51173. }
  51174. };
  51175. Sound.prototype.clone = function () {
  51176. var _this = this;
  51177. if (!this._streaming) {
  51178. var setBufferAndRun = function () {
  51179. if (_this._isReadyToPlay) {
  51180. clonedSound._audioBuffer = _this.getAudioBuffer();
  51181. clonedSound._isReadyToPlay = true;
  51182. if (clonedSound.autoplay) {
  51183. clonedSound.play();
  51184. }
  51185. }
  51186. else {
  51187. window.setTimeout(setBufferAndRun, 300);
  51188. }
  51189. };
  51190. var currentOptions = {
  51191. autoplay: this.autoplay, loop: this.loop,
  51192. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  51193. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  51194. refDistance: this.refDistance, distanceModel: this.distanceModel
  51195. };
  51196. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  51197. if (this.useCustomAttenuation) {
  51198. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  51199. }
  51200. clonedSound.setPosition(this._position);
  51201. clonedSound.setPlaybackRate(this._playbackRate);
  51202. setBufferAndRun();
  51203. return clonedSound;
  51204. }
  51205. else {
  51206. return null;
  51207. }
  51208. };
  51209. Sound.prototype.getAudioBuffer = function () {
  51210. return this._audioBuffer;
  51211. };
  51212. Sound.prototype.serialize = function () {
  51213. var serializationObject = {
  51214. name: this.name,
  51215. url: this.name,
  51216. autoplay: this.autoplay,
  51217. loop: this.loop,
  51218. volume: this._volume,
  51219. spatialSound: this.spatialSound,
  51220. maxDistance: this.maxDistance,
  51221. rolloffFactor: this.rolloffFactor,
  51222. refDistance: this.refDistance,
  51223. distanceModel: this.distanceModel,
  51224. playbackRate: this._playbackRate,
  51225. panningModel: this._panningModel,
  51226. soundTrackId: this.soundTrackId
  51227. };
  51228. if (this.spatialSound) {
  51229. if (this._connectedMesh)
  51230. serializationObject.connectedMeshId = this._connectedMesh.id;
  51231. serializationObject.position = this._position.asArray();
  51232. serializationObject.refDistance = this.refDistance;
  51233. serializationObject.distanceModel = this.distanceModel;
  51234. serializationObject.isDirectional = this._isDirectional;
  51235. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  51236. serializationObject.coneInnerAngle = this._coneInnerAngle;
  51237. serializationObject.coneOuterAngle = this._coneOuterAngle;
  51238. serializationObject.coneOuterGain = this._coneOuterGain;
  51239. }
  51240. return serializationObject;
  51241. };
  51242. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  51243. var soundName = parsedSound.name;
  51244. var soundUrl;
  51245. if (parsedSound.url) {
  51246. soundUrl = rootUrl + parsedSound.url;
  51247. }
  51248. else {
  51249. soundUrl = rootUrl + soundName;
  51250. }
  51251. var options = {
  51252. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  51253. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  51254. rolloffFactor: parsedSound.rolloffFactor,
  51255. refDistance: parsedSound.refDistance,
  51256. distanceModel: parsedSound.distanceModel,
  51257. playbackRate: parsedSound.playbackRate
  51258. };
  51259. var newSound;
  51260. if (!sourceSound) {
  51261. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  51262. scene._addPendingData(newSound);
  51263. }
  51264. else {
  51265. var setBufferAndRun = function () {
  51266. if (sourceSound._isReadyToPlay) {
  51267. newSound._audioBuffer = sourceSound.getAudioBuffer();
  51268. newSound._isReadyToPlay = true;
  51269. if (newSound.autoplay) {
  51270. newSound.play();
  51271. }
  51272. }
  51273. else {
  51274. window.setTimeout(setBufferAndRun, 300);
  51275. }
  51276. };
  51277. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  51278. setBufferAndRun();
  51279. }
  51280. if (parsedSound.position) {
  51281. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  51282. newSound.setPosition(soundPosition);
  51283. }
  51284. if (parsedSound.isDirectional) {
  51285. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  51286. if (parsedSound.localDirectionToMesh) {
  51287. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  51288. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  51289. }
  51290. }
  51291. if (parsedSound.connectedMeshId) {
  51292. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  51293. if (connectedMesh) {
  51294. newSound.attachToMesh(connectedMesh);
  51295. }
  51296. }
  51297. return newSound;
  51298. };
  51299. return Sound;
  51300. }());
  51301. BABYLON.Sound = Sound;
  51302. })(BABYLON || (BABYLON = {}));
  51303. //# sourceMappingURL=babylon.sound.js.map
  51304. var BABYLON;
  51305. (function (BABYLON) {
  51306. var SoundTrack = /** @class */ (function () {
  51307. function SoundTrack(scene, options) {
  51308. this.id = -1;
  51309. this._isMainTrack = false;
  51310. this._isInitialized = false;
  51311. this._scene = scene;
  51312. this.soundCollection = new Array();
  51313. this._options = options;
  51314. if (!this._isMainTrack) {
  51315. this._scene.soundTracks.push(this);
  51316. this.id = this._scene.soundTracks.length - 1;
  51317. }
  51318. }
  51319. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  51320. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  51321. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  51322. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  51323. if (this._options) {
  51324. if (this._options.volume) {
  51325. this._outputAudioNode.gain.value = this._options.volume;
  51326. }
  51327. if (this._options.mainTrack) {
  51328. this._isMainTrack = this._options.mainTrack;
  51329. }
  51330. }
  51331. this._isInitialized = true;
  51332. }
  51333. };
  51334. SoundTrack.prototype.dispose = function () {
  51335. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51336. if (this._connectedAnalyser) {
  51337. this._connectedAnalyser.stopDebugCanvas();
  51338. }
  51339. while (this.soundCollection.length) {
  51340. this.soundCollection[0].dispose();
  51341. }
  51342. if (this._outputAudioNode) {
  51343. this._outputAudioNode.disconnect();
  51344. }
  51345. this._outputAudioNode = null;
  51346. }
  51347. };
  51348. SoundTrack.prototype.AddSound = function (sound) {
  51349. if (!this._isInitialized) {
  51350. this._initializeSoundTrackAudioGraph();
  51351. }
  51352. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51353. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  51354. }
  51355. if (sound.soundTrackId) {
  51356. if (sound.soundTrackId === -1) {
  51357. this._scene.mainSoundTrack.RemoveSound(sound);
  51358. }
  51359. else {
  51360. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  51361. }
  51362. }
  51363. this.soundCollection.push(sound);
  51364. sound.soundTrackId = this.id;
  51365. };
  51366. SoundTrack.prototype.RemoveSound = function (sound) {
  51367. var index = this.soundCollection.indexOf(sound);
  51368. if (index !== -1) {
  51369. this.soundCollection.splice(index, 1);
  51370. }
  51371. };
  51372. SoundTrack.prototype.setVolume = function (newVolume) {
  51373. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51374. this._outputAudioNode.gain.value = newVolume;
  51375. }
  51376. };
  51377. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  51378. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51379. for (var i = 0; i < this.soundCollection.length; i++) {
  51380. this.soundCollection[i].switchPanningModelToHRTF();
  51381. }
  51382. }
  51383. };
  51384. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  51385. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  51386. for (var i = 0; i < this.soundCollection.length; i++) {
  51387. this.soundCollection[i].switchPanningModelToEqualPower();
  51388. }
  51389. }
  51390. };
  51391. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  51392. if (this._connectedAnalyser) {
  51393. this._connectedAnalyser.stopDebugCanvas();
  51394. }
  51395. this._connectedAnalyser = analyser;
  51396. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  51397. this._outputAudioNode.disconnect();
  51398. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  51399. }
  51400. };
  51401. return SoundTrack;
  51402. }());
  51403. BABYLON.SoundTrack = SoundTrack;
  51404. })(BABYLON || (BABYLON = {}));
  51405. //# sourceMappingURL=babylon.soundtrack.js.map
  51406. var BABYLON;
  51407. (function (BABYLON) {
  51408. var Analyser = /** @class */ (function () {
  51409. function Analyser(scene) {
  51410. this.SMOOTHING = 0.75;
  51411. this.FFT_SIZE = 512;
  51412. this.BARGRAPHAMPLITUDE = 256;
  51413. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  51414. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  51415. this._scene = scene;
  51416. this._audioEngine = BABYLON.Engine.audioEngine;
  51417. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  51418. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  51419. this._webAudioAnalyser.minDecibels = -140;
  51420. this._webAudioAnalyser.maxDecibels = 0;
  51421. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51422. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  51423. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  51424. }
  51425. }
  51426. Analyser.prototype.getFrequencyBinCount = function () {
  51427. if (this._audioEngine.canUseWebAudio) {
  51428. return this._webAudioAnalyser.frequencyBinCount;
  51429. }
  51430. else {
  51431. return 0;
  51432. }
  51433. };
  51434. Analyser.prototype.getByteFrequencyData = function () {
  51435. if (this._audioEngine.canUseWebAudio) {
  51436. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51437. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51438. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  51439. }
  51440. return this._byteFreqs;
  51441. };
  51442. Analyser.prototype.getByteTimeDomainData = function () {
  51443. if (this._audioEngine.canUseWebAudio) {
  51444. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51445. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51446. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  51447. }
  51448. return this._byteTime;
  51449. };
  51450. Analyser.prototype.getFloatFrequencyData = function () {
  51451. if (this._audioEngine.canUseWebAudio) {
  51452. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  51453. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  51454. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  51455. }
  51456. return this._floatFreqs;
  51457. };
  51458. Analyser.prototype.drawDebugCanvas = function () {
  51459. var _this = this;
  51460. if (this._audioEngine.canUseWebAudio) {
  51461. if (!this._debugCanvas) {
  51462. this._debugCanvas = document.createElement("canvas");
  51463. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  51464. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  51465. this._debugCanvas.style.position = "absolute";
  51466. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  51467. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  51468. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  51469. document.body.appendChild(this._debugCanvas);
  51470. this._registerFunc = function () {
  51471. _this.drawDebugCanvas();
  51472. };
  51473. this._scene.registerBeforeRender(this._registerFunc);
  51474. }
  51475. if (this._registerFunc && this._debugCanvasContext) {
  51476. var workingArray = this.getByteFrequencyData();
  51477. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  51478. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  51479. // Draw the frequency domain chart.
  51480. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  51481. var value = workingArray[i];
  51482. var percent = value / this.BARGRAPHAMPLITUDE;
  51483. var height = this.DEBUGCANVASSIZE.height * percent;
  51484. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  51485. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  51486. var hue = i / this.getFrequencyBinCount() * 360;
  51487. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  51488. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  51489. }
  51490. }
  51491. }
  51492. };
  51493. Analyser.prototype.stopDebugCanvas = function () {
  51494. if (this._debugCanvas) {
  51495. if (this._registerFunc) {
  51496. this._scene.unregisterBeforeRender(this._registerFunc);
  51497. this._registerFunc = null;
  51498. }
  51499. document.body.removeChild(this._debugCanvas);
  51500. this._debugCanvas = null;
  51501. this._debugCanvasContext = null;
  51502. }
  51503. };
  51504. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  51505. if (this._audioEngine.canUseWebAudio) {
  51506. inputAudioNode.connect(this._webAudioAnalyser);
  51507. this._webAudioAnalyser.connect(outputAudioNode);
  51508. }
  51509. };
  51510. Analyser.prototype.dispose = function () {
  51511. if (this._audioEngine.canUseWebAudio) {
  51512. this._webAudioAnalyser.disconnect();
  51513. }
  51514. };
  51515. return Analyser;
  51516. }());
  51517. BABYLON.Analyser = Analyser;
  51518. })(BABYLON || (BABYLON = {}));
  51519. //# sourceMappingURL=babylon.analyser.js.map
  51520. var BABYLON;
  51521. (function (BABYLON) {
  51522. var CubeTexture = /** @class */ (function (_super) {
  51523. __extends(CubeTexture, _super);
  51524. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51525. if (extensions === void 0) { extensions = null; }
  51526. if (noMipmap === void 0) { noMipmap = false; }
  51527. if (files === void 0) { files = null; }
  51528. if (onLoad === void 0) { onLoad = null; }
  51529. if (onError === void 0) { onError = null; }
  51530. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51531. if (prefiltered === void 0) { prefiltered = false; }
  51532. if (forcedExtension === void 0) { forcedExtension = null; }
  51533. var _this = _super.call(this, scene) || this;
  51534. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51535. _this.name = rootUrl;
  51536. _this.url = rootUrl;
  51537. _this._noMipmap = noMipmap;
  51538. _this.hasAlpha = false;
  51539. _this._format = format;
  51540. _this._prefiltered = prefiltered;
  51541. _this.isCube = true;
  51542. _this._textureMatrix = BABYLON.Matrix.Identity();
  51543. if (prefiltered) {
  51544. _this.gammaSpace = false;
  51545. }
  51546. if (!rootUrl && !files) {
  51547. return _this;
  51548. }
  51549. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51550. var lastDot = rootUrl.lastIndexOf(".");
  51551. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51552. var isDDS = (extension === ".dds");
  51553. if (!files) {
  51554. if (!isDDS && !extensions) {
  51555. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51556. }
  51557. files = [];
  51558. if (extensions) {
  51559. for (var index = 0; index < extensions.length; index++) {
  51560. files.push(rootUrl + extensions[index]);
  51561. }
  51562. }
  51563. }
  51564. _this._files = files;
  51565. if (!_this._texture) {
  51566. if (!scene.useDelayedTextureLoading) {
  51567. if (prefiltered) {
  51568. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51569. }
  51570. else {
  51571. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51572. }
  51573. }
  51574. else {
  51575. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51576. }
  51577. }
  51578. else if (onLoad) {
  51579. if (_this._texture.isReady) {
  51580. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51581. }
  51582. else {
  51583. _this._texture.onLoadedObservable.add(onLoad);
  51584. }
  51585. }
  51586. return _this;
  51587. }
  51588. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51589. return new CubeTexture("", scene, null, noMipmap, files);
  51590. };
  51591. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51592. if (forcedExtension === void 0) { forcedExtension = null; }
  51593. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51594. };
  51595. // Methods
  51596. CubeTexture.prototype.delayLoad = function () {
  51597. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51598. return;
  51599. }
  51600. var scene = this.getScene();
  51601. if (!scene) {
  51602. return;
  51603. }
  51604. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51605. this._texture = this._getFromCache(this.url, this._noMipmap);
  51606. if (!this._texture) {
  51607. if (this._prefiltered) {
  51608. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51609. }
  51610. else {
  51611. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51612. }
  51613. }
  51614. };
  51615. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51616. return this._textureMatrix;
  51617. };
  51618. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51619. this._textureMatrix = value;
  51620. };
  51621. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51622. var texture = BABYLON.SerializationHelper.Parse(function () {
  51623. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51624. }, parsedTexture, scene);
  51625. // Animations
  51626. if (parsedTexture.animations) {
  51627. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51628. var parsedAnimation = parsedTexture.animations[animationIndex];
  51629. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51630. }
  51631. }
  51632. return texture;
  51633. };
  51634. CubeTexture.prototype.clone = function () {
  51635. var _this = this;
  51636. return BABYLON.SerializationHelper.Clone(function () {
  51637. var scene = _this.getScene();
  51638. if (!scene) {
  51639. return _this;
  51640. }
  51641. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51642. }, this);
  51643. };
  51644. return CubeTexture;
  51645. }(BABYLON.BaseTexture));
  51646. BABYLON.CubeTexture = CubeTexture;
  51647. })(BABYLON || (BABYLON = {}));
  51648. //# sourceMappingURL=babylon.cubeTexture.js.map
  51649. var BABYLON;
  51650. (function (BABYLON) {
  51651. var RenderTargetTexture = /** @class */ (function (_super) {
  51652. __extends(RenderTargetTexture, _super);
  51653. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51654. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51655. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51656. if (isCube === void 0) { isCube = false; }
  51657. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51658. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51659. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51660. if (isMulti === void 0) { isMulti = false; }
  51661. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51662. _this.isCube = isCube;
  51663. /**
  51664. * Use this list to define the list of mesh you want to render.
  51665. */
  51666. _this.renderList = new Array();
  51667. _this.renderParticles = true;
  51668. _this.renderSprites = false;
  51669. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51670. _this.ignoreCameraViewport = false;
  51671. // Events
  51672. /**
  51673. * An event triggered when the texture is unbind.
  51674. * @type {BABYLON.Observable}
  51675. */
  51676. _this.onBeforeBindObservable = new BABYLON.Observable();
  51677. /**
  51678. * An event triggered when the texture is unbind.
  51679. * @type {BABYLON.Observable}
  51680. */
  51681. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51682. /**
  51683. * An event triggered before rendering the texture
  51684. * @type {BABYLON.Observable}
  51685. */
  51686. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51687. /**
  51688. * An event triggered after rendering the texture
  51689. * @type {BABYLON.Observable}
  51690. */
  51691. _this.onAfterRenderObservable = new BABYLON.Observable();
  51692. /**
  51693. * An event triggered after the texture clear
  51694. * @type {BABYLON.Observable}
  51695. */
  51696. _this.onClearObservable = new BABYLON.Observable();
  51697. _this._currentRefreshId = -1;
  51698. _this._refreshRate = 1;
  51699. _this._samples = 1;
  51700. scene = _this.getScene();
  51701. if (!scene) {
  51702. return _this;
  51703. }
  51704. _this._engine = scene.getEngine();
  51705. _this.name = name;
  51706. _this.isRenderTarget = true;
  51707. _this._initialSizeParameter = size;
  51708. _this._processSizeParameter(size);
  51709. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51710. });
  51711. _this._generateMipMaps = generateMipMaps ? true : false;
  51712. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51713. // Rendering groups
  51714. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51715. if (isMulti) {
  51716. return _this;
  51717. }
  51718. _this._renderTargetOptions = {
  51719. generateMipMaps: generateMipMaps,
  51720. type: type,
  51721. samplingMode: samplingMode,
  51722. generateDepthBuffer: generateDepthBuffer,
  51723. generateStencilBuffer: generateStencilBuffer
  51724. };
  51725. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51726. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51727. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51728. }
  51729. if (isCube) {
  51730. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51731. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51732. _this._textureMatrix = BABYLON.Matrix.Identity();
  51733. }
  51734. else {
  51735. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51736. }
  51737. return _this;
  51738. }
  51739. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51740. get: function () {
  51741. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51742. },
  51743. enumerable: true,
  51744. configurable: true
  51745. });
  51746. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51747. get: function () {
  51748. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51749. },
  51750. enumerable: true,
  51751. configurable: true
  51752. });
  51753. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51754. get: function () {
  51755. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51756. },
  51757. enumerable: true,
  51758. configurable: true
  51759. });
  51760. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51761. set: function (callback) {
  51762. if (this._onAfterUnbindObserver) {
  51763. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51764. }
  51765. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51766. },
  51767. enumerable: true,
  51768. configurable: true
  51769. });
  51770. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51771. set: function (callback) {
  51772. if (this._onBeforeRenderObserver) {
  51773. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51774. }
  51775. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51776. },
  51777. enumerable: true,
  51778. configurable: true
  51779. });
  51780. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51781. set: function (callback) {
  51782. if (this._onAfterRenderObserver) {
  51783. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51784. }
  51785. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51786. },
  51787. enumerable: true,
  51788. configurable: true
  51789. });
  51790. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51791. set: function (callback) {
  51792. if (this._onClearObserver) {
  51793. this.onClearObservable.remove(this._onClearObserver);
  51794. }
  51795. this._onClearObserver = this.onClearObservable.add(callback);
  51796. },
  51797. enumerable: true,
  51798. configurable: true
  51799. });
  51800. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51801. get: function () {
  51802. return this._renderTargetOptions;
  51803. },
  51804. enumerable: true,
  51805. configurable: true
  51806. });
  51807. RenderTargetTexture.prototype._onRatioRescale = function () {
  51808. if (this._sizeRatio) {
  51809. this.resize(this._initialSizeParameter);
  51810. }
  51811. };
  51812. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51813. if (size.ratio) {
  51814. this._sizeRatio = size.ratio;
  51815. this._size = {
  51816. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51817. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51818. };
  51819. }
  51820. else {
  51821. this._size = size;
  51822. }
  51823. };
  51824. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51825. get: function () {
  51826. return this._samples;
  51827. },
  51828. set: function (value) {
  51829. if (this._samples === value) {
  51830. return;
  51831. }
  51832. var scene = this.getScene();
  51833. if (!scene) {
  51834. return;
  51835. }
  51836. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  51837. },
  51838. enumerable: true,
  51839. configurable: true
  51840. });
  51841. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  51842. this._currentRefreshId = -1;
  51843. };
  51844. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  51845. get: function () {
  51846. return this._refreshRate;
  51847. },
  51848. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51849. set: function (value) {
  51850. this._refreshRate = value;
  51851. this.resetRefreshCounter();
  51852. },
  51853. enumerable: true,
  51854. configurable: true
  51855. });
  51856. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  51857. if (!this._postProcessManager) {
  51858. var scene = this.getScene();
  51859. if (!scene) {
  51860. return;
  51861. }
  51862. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  51863. this._postProcesses = new Array();
  51864. }
  51865. this._postProcesses.push(postProcess);
  51866. this._postProcesses[0].autoClear = false;
  51867. };
  51868. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  51869. if (!this._postProcesses) {
  51870. return;
  51871. }
  51872. if (dispose) {
  51873. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  51874. var postProcess = _a[_i];
  51875. postProcess.dispose();
  51876. }
  51877. }
  51878. this._postProcesses = [];
  51879. };
  51880. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  51881. if (!this._postProcesses) {
  51882. return;
  51883. }
  51884. var index = this._postProcesses.indexOf(postProcess);
  51885. if (index === -1) {
  51886. return;
  51887. }
  51888. this._postProcesses.splice(index, 1);
  51889. if (this._postProcesses.length > 0) {
  51890. this._postProcesses[0].autoClear = false;
  51891. }
  51892. };
  51893. RenderTargetTexture.prototype._shouldRender = function () {
  51894. if (this._currentRefreshId === -1) {
  51895. this._currentRefreshId = 1;
  51896. return true;
  51897. }
  51898. if (this.refreshRate === this._currentRefreshId) {
  51899. this._currentRefreshId = 1;
  51900. return true;
  51901. }
  51902. this._currentRefreshId++;
  51903. return false;
  51904. };
  51905. RenderTargetTexture.prototype.getRenderSize = function () {
  51906. if (this._size.width) {
  51907. return this._size.width;
  51908. }
  51909. return this._size;
  51910. };
  51911. RenderTargetTexture.prototype.getRenderWidth = function () {
  51912. if (this._size.width) {
  51913. return this._size.width;
  51914. }
  51915. return this._size;
  51916. };
  51917. RenderTargetTexture.prototype.getRenderHeight = function () {
  51918. if (this._size.width) {
  51919. return this._size.height;
  51920. }
  51921. return this._size;
  51922. };
  51923. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  51924. get: function () {
  51925. return true;
  51926. },
  51927. enumerable: true,
  51928. configurable: true
  51929. });
  51930. RenderTargetTexture.prototype.scale = function (ratio) {
  51931. var newSize = this.getRenderSize() * ratio;
  51932. this.resize(newSize);
  51933. };
  51934. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  51935. if (this.isCube) {
  51936. return this._textureMatrix;
  51937. }
  51938. return _super.prototype.getReflectionTextureMatrix.call(this);
  51939. };
  51940. RenderTargetTexture.prototype.resize = function (size) {
  51941. this.releaseInternalTexture();
  51942. var scene = this.getScene();
  51943. if (!scene) {
  51944. return;
  51945. }
  51946. this._processSizeParameter(size);
  51947. if (this.isCube) {
  51948. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  51949. }
  51950. else {
  51951. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  51952. }
  51953. };
  51954. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  51955. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  51956. if (dumpForDebug === void 0) { dumpForDebug = false; }
  51957. var scene = this.getScene();
  51958. if (!scene) {
  51959. return;
  51960. }
  51961. var engine = scene.getEngine();
  51962. if (this.useCameraPostProcesses !== undefined) {
  51963. useCameraPostProcess = this.useCameraPostProcesses;
  51964. }
  51965. if (this._waitingRenderList) {
  51966. this.renderList = [];
  51967. for (var index = 0; index < this._waitingRenderList.length; index++) {
  51968. var id = this._waitingRenderList[index];
  51969. var mesh_1 = scene.getMeshByID(id);
  51970. if (mesh_1) {
  51971. this.renderList.push(mesh_1);
  51972. }
  51973. }
  51974. delete this._waitingRenderList;
  51975. }
  51976. // Is predicate defined?
  51977. if (this.renderListPredicate) {
  51978. if (this.renderList) {
  51979. this.renderList.splice(0); // Clear previous renderList
  51980. }
  51981. else {
  51982. this.renderList = [];
  51983. }
  51984. var scene = this.getScene();
  51985. if (!scene) {
  51986. return;
  51987. }
  51988. var sceneMeshes = scene.meshes;
  51989. for (var index = 0; index < sceneMeshes.length; index++) {
  51990. var mesh = sceneMeshes[index];
  51991. if (this.renderListPredicate(mesh)) {
  51992. this.renderList.push(mesh);
  51993. }
  51994. }
  51995. }
  51996. this.onBeforeBindObservable.notifyObservers(this);
  51997. // Set custom projection.
  51998. // Needs to be before binding to prevent changing the aspect ratio.
  51999. var camera;
  52000. if (this.activeCamera) {
  52001. camera = this.activeCamera;
  52002. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  52003. if (this.activeCamera !== scene.activeCamera) {
  52004. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  52005. }
  52006. }
  52007. else {
  52008. camera = scene.activeCamera;
  52009. if (camera) {
  52010. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  52011. }
  52012. }
  52013. // Prepare renderingManager
  52014. this._renderingManager.reset();
  52015. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  52016. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  52017. var sceneRenderId = scene.getRenderId();
  52018. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  52019. var mesh = currentRenderList[meshIndex];
  52020. if (mesh) {
  52021. if (!mesh.isReady()) {
  52022. // Reset _currentRefreshId
  52023. this.resetRefreshCounter();
  52024. continue;
  52025. }
  52026. mesh._preActivateForIntermediateRendering(sceneRenderId);
  52027. var isMasked = void 0;
  52028. if (!this.renderList && camera) {
  52029. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  52030. }
  52031. else {
  52032. isMasked = false;
  52033. }
  52034. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  52035. mesh._activate(sceneRenderId);
  52036. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  52037. var subMesh = mesh.subMeshes[subIndex];
  52038. scene._activeIndices.addCount(subMesh.indexCount, false);
  52039. this._renderingManager.dispatch(subMesh, mesh);
  52040. }
  52041. }
  52042. }
  52043. }
  52044. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  52045. var particleSystem = scene.particleSystems[particleIndex];
  52046. var emitter = particleSystem.emitter;
  52047. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  52048. continue;
  52049. }
  52050. if (currentRenderList.indexOf(emitter) >= 0) {
  52051. this._renderingManager.dispatchParticles(particleSystem);
  52052. }
  52053. }
  52054. if (this.isCube) {
  52055. for (var face = 0; face < 6; face++) {
  52056. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52057. scene.incrementRenderId();
  52058. scene.resetCachedMaterial();
  52059. }
  52060. }
  52061. else {
  52062. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  52063. }
  52064. this.onAfterUnbindObservable.notifyObservers(this);
  52065. if (scene.activeCamera) {
  52066. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  52067. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  52068. }
  52069. engine.setViewport(scene.activeCamera.viewport);
  52070. }
  52071. scene.resetCachedMaterial();
  52072. };
  52073. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  52074. var minimum = 128;
  52075. var x = renderDimension * scale;
  52076. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  52077. // Ensure we don't exceed the render dimension (while staying POT)
  52078. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  52079. };
  52080. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52081. var _this = this;
  52082. if (!this._texture) {
  52083. return;
  52084. }
  52085. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  52086. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52087. });
  52088. };
  52089. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  52090. var scene = this.getScene();
  52091. if (!scene) {
  52092. return;
  52093. }
  52094. var engine = scene.getEngine();
  52095. if (!this._texture) {
  52096. return;
  52097. }
  52098. // Bind
  52099. if (this._postProcessManager) {
  52100. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  52101. }
  52102. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  52103. if (this._texture) {
  52104. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  52105. }
  52106. }
  52107. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  52108. // Clear
  52109. if (this.onClearObservable.hasObservers()) {
  52110. this.onClearObservable.notifyObservers(engine);
  52111. }
  52112. else {
  52113. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  52114. }
  52115. if (!this._doNotChangeAspectRatio) {
  52116. scene.updateTransformMatrix(true);
  52117. }
  52118. // Render
  52119. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  52120. if (this._postProcessManager) {
  52121. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  52122. }
  52123. else if (useCameraPostProcess) {
  52124. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  52125. }
  52126. if (!this._doNotChangeAspectRatio) {
  52127. scene.updateTransformMatrix(true);
  52128. }
  52129. // Dump ?
  52130. if (dumpForDebug) {
  52131. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  52132. }
  52133. // Unbind
  52134. if (!this.isCube || faceIndex === 5) {
  52135. if (this.isCube) {
  52136. if (faceIndex === 5) {
  52137. engine.generateMipMapsForCubemap(this._texture);
  52138. }
  52139. }
  52140. this.unbindFrameBuffer(engine, faceIndex);
  52141. }
  52142. else {
  52143. this.onAfterRenderObservable.notifyObservers(faceIndex);
  52144. }
  52145. };
  52146. /**
  52147. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  52148. * This allowed control for front to back rendering or reversly depending of the special needs.
  52149. *
  52150. * @param renderingGroupId The rendering group id corresponding to its index
  52151. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  52152. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  52153. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  52154. */
  52155. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  52156. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  52157. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  52158. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  52159. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  52160. };
  52161. /**
  52162. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  52163. *
  52164. * @param renderingGroupId The rendering group id corresponding to its index
  52165. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  52166. */
  52167. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  52168. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  52169. };
  52170. RenderTargetTexture.prototype.clone = function () {
  52171. var textureSize = this.getSize();
  52172. 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);
  52173. // Base texture
  52174. newTexture.hasAlpha = this.hasAlpha;
  52175. newTexture.level = this.level;
  52176. // RenderTarget Texture
  52177. newTexture.coordinatesMode = this.coordinatesMode;
  52178. if (this.renderList) {
  52179. newTexture.renderList = this.renderList.slice(0);
  52180. }
  52181. return newTexture;
  52182. };
  52183. RenderTargetTexture.prototype.serialize = function () {
  52184. if (!this.name) {
  52185. return null;
  52186. }
  52187. var serializationObject = _super.prototype.serialize.call(this);
  52188. serializationObject.renderTargetSize = this.getRenderSize();
  52189. serializationObject.renderList = [];
  52190. if (this.renderList) {
  52191. for (var index = 0; index < this.renderList.length; index++) {
  52192. serializationObject.renderList.push(this.renderList[index].id);
  52193. }
  52194. }
  52195. return serializationObject;
  52196. };
  52197. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  52198. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  52199. var objBuffer = this.getInternalTexture();
  52200. var scene = this.getScene();
  52201. if (objBuffer && scene) {
  52202. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  52203. }
  52204. };
  52205. RenderTargetTexture.prototype.dispose = function () {
  52206. if (this._postProcessManager) {
  52207. this._postProcessManager.dispose();
  52208. this._postProcessManager = null;
  52209. }
  52210. this.clearPostProcesses(true);
  52211. if (this._resizeObserver) {
  52212. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  52213. this._resizeObserver = null;
  52214. }
  52215. this.renderList = null;
  52216. // Remove from custom render targets
  52217. var scene = this.getScene();
  52218. if (!scene) {
  52219. return;
  52220. }
  52221. var index = scene.customRenderTargets.indexOf(this);
  52222. if (index >= 0) {
  52223. scene.customRenderTargets.splice(index, 1);
  52224. }
  52225. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  52226. var camera = _a[_i];
  52227. index = camera.customRenderTargets.indexOf(this);
  52228. if (index >= 0) {
  52229. camera.customRenderTargets.splice(index, 1);
  52230. }
  52231. }
  52232. _super.prototype.dispose.call(this);
  52233. };
  52234. RenderTargetTexture.prototype._rebuild = function () {
  52235. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  52236. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  52237. }
  52238. if (this._postProcessManager) {
  52239. this._postProcessManager._rebuild();
  52240. }
  52241. };
  52242. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  52243. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  52244. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  52245. return RenderTargetTexture;
  52246. }(BABYLON.Texture));
  52247. BABYLON.RenderTargetTexture = RenderTargetTexture;
  52248. })(BABYLON || (BABYLON = {}));
  52249. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  52250. var BABYLON;
  52251. (function (BABYLON) {
  52252. ;
  52253. var MultiRenderTarget = /** @class */ (function (_super) {
  52254. __extends(MultiRenderTarget, _super);
  52255. function MultiRenderTarget(name, size, count, scene, options) {
  52256. var _this = this;
  52257. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  52258. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  52259. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  52260. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  52261. _this._engine = scene.getEngine();
  52262. if (!_this.isSupported) {
  52263. _this.dispose();
  52264. return;
  52265. }
  52266. var types = [];
  52267. var samplingModes = [];
  52268. for (var i = 0; i < count; i++) {
  52269. if (options && options.types && options.types[i] !== undefined) {
  52270. types.push(options.types[i]);
  52271. }
  52272. else {
  52273. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  52274. }
  52275. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  52276. samplingModes.push(options.samplingModes[i]);
  52277. }
  52278. else {
  52279. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52280. }
  52281. }
  52282. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  52283. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  52284. _this._size = size;
  52285. _this._multiRenderTargetOptions = {
  52286. samplingModes: samplingModes,
  52287. generateMipMaps: generateMipMaps,
  52288. generateDepthBuffer: generateDepthBuffer,
  52289. generateStencilBuffer: generateStencilBuffer,
  52290. generateDepthTexture: generateDepthTexture,
  52291. types: types,
  52292. textureCount: count
  52293. };
  52294. _this._createInternalTextures();
  52295. _this._createTextures();
  52296. return _this;
  52297. }
  52298. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  52299. get: function () {
  52300. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  52301. },
  52302. enumerable: true,
  52303. configurable: true
  52304. });
  52305. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  52306. get: function () {
  52307. return this._textures;
  52308. },
  52309. enumerable: true,
  52310. configurable: true
  52311. });
  52312. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  52313. get: function () {
  52314. return this._textures[this._textures.length - 1];
  52315. },
  52316. enumerable: true,
  52317. configurable: true
  52318. });
  52319. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  52320. set: function (wrap) {
  52321. if (this._textures) {
  52322. for (var i = 0; i < this._textures.length; i++) {
  52323. this._textures[i].wrapU = wrap;
  52324. }
  52325. }
  52326. },
  52327. enumerable: true,
  52328. configurable: true
  52329. });
  52330. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  52331. set: function (wrap) {
  52332. if (this._textures) {
  52333. for (var i = 0; i < this._textures.length; i++) {
  52334. this._textures[i].wrapV = wrap;
  52335. }
  52336. }
  52337. },
  52338. enumerable: true,
  52339. configurable: true
  52340. });
  52341. MultiRenderTarget.prototype._rebuild = function () {
  52342. this.releaseInternalTextures();
  52343. this._createInternalTextures();
  52344. for (var i = 0; i < this._internalTextures.length; i++) {
  52345. var texture = this._textures[i];
  52346. texture._texture = this._internalTextures[i];
  52347. }
  52348. // Keeps references to frame buffer and stencil/depth buffer
  52349. this._texture = this._internalTextures[0];
  52350. };
  52351. MultiRenderTarget.prototype._createInternalTextures = function () {
  52352. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  52353. };
  52354. MultiRenderTarget.prototype._createTextures = function () {
  52355. this._textures = [];
  52356. for (var i = 0; i < this._internalTextures.length; i++) {
  52357. var texture = new BABYLON.Texture(null, this.getScene());
  52358. texture._texture = this._internalTextures[i];
  52359. this._textures.push(texture);
  52360. }
  52361. // Keeps references to frame buffer and stencil/depth buffer
  52362. this._texture = this._internalTextures[0];
  52363. };
  52364. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  52365. get: function () {
  52366. return this._samples;
  52367. },
  52368. set: function (value) {
  52369. if (this._samples === value) {
  52370. return;
  52371. }
  52372. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  52373. },
  52374. enumerable: true,
  52375. configurable: true
  52376. });
  52377. MultiRenderTarget.prototype.resize = function (size) {
  52378. this.releaseInternalTextures();
  52379. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  52380. this._createInternalTextures();
  52381. };
  52382. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  52383. var _this = this;
  52384. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  52385. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  52386. });
  52387. };
  52388. MultiRenderTarget.prototype.dispose = function () {
  52389. this.releaseInternalTextures();
  52390. _super.prototype.dispose.call(this);
  52391. };
  52392. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  52393. if (!this._internalTextures) {
  52394. return;
  52395. }
  52396. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  52397. if (this._internalTextures[i] !== undefined) {
  52398. this._internalTextures[i].dispose();
  52399. this._internalTextures.splice(i, 1);
  52400. }
  52401. }
  52402. };
  52403. return MultiRenderTarget;
  52404. }(BABYLON.RenderTargetTexture));
  52405. BABYLON.MultiRenderTarget = MultiRenderTarget;
  52406. })(BABYLON || (BABYLON = {}));
  52407. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  52408. var BABYLON;
  52409. (function (BABYLON) {
  52410. var MirrorTexture = /** @class */ (function (_super) {
  52411. __extends(MirrorTexture, _super);
  52412. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  52413. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52414. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  52415. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  52416. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  52417. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  52418. _this._transformMatrix = BABYLON.Matrix.Zero();
  52419. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  52420. _this._adaptiveBlurKernel = 0;
  52421. _this._blurKernelX = 0;
  52422. _this._blurKernelY = 0;
  52423. _this._blurRatio = 1.0;
  52424. _this.ignoreCameraViewport = true;
  52425. _this.onBeforeRenderObservable.add(function () {
  52426. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  52427. _this._savedViewMatrix = scene.getViewMatrix();
  52428. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  52429. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  52430. scene.clipPlane = _this.mirrorPlane;
  52431. scene.getEngine().cullBackFaces = false;
  52432. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  52433. });
  52434. _this.onAfterRenderObservable.add(function () {
  52435. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  52436. scene.getEngine().cullBackFaces = true;
  52437. scene._mirroredCameraPosition = null;
  52438. delete scene.clipPlane;
  52439. });
  52440. return _this;
  52441. }
  52442. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  52443. get: function () {
  52444. return this._blurRatio;
  52445. },
  52446. set: function (value) {
  52447. if (this._blurRatio === value) {
  52448. return;
  52449. }
  52450. this._blurRatio = value;
  52451. this._preparePostProcesses();
  52452. },
  52453. enumerable: true,
  52454. configurable: true
  52455. });
  52456. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  52457. set: function (value) {
  52458. this._adaptiveBlurKernel = value;
  52459. this._autoComputeBlurKernel();
  52460. },
  52461. enumerable: true,
  52462. configurable: true
  52463. });
  52464. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  52465. set: function (value) {
  52466. this.blurKernelX = value;
  52467. this.blurKernelY = value;
  52468. },
  52469. enumerable: true,
  52470. configurable: true
  52471. });
  52472. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  52473. get: function () {
  52474. return this._blurKernelX;
  52475. },
  52476. set: function (value) {
  52477. if (this._blurKernelX === value) {
  52478. return;
  52479. }
  52480. this._blurKernelX = value;
  52481. this._preparePostProcesses();
  52482. },
  52483. enumerable: true,
  52484. configurable: true
  52485. });
  52486. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  52487. get: function () {
  52488. return this._blurKernelY;
  52489. },
  52490. set: function (value) {
  52491. if (this._blurKernelY === value) {
  52492. return;
  52493. }
  52494. this._blurKernelY = value;
  52495. this._preparePostProcesses();
  52496. },
  52497. enumerable: true,
  52498. configurable: true
  52499. });
  52500. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  52501. var engine = this.getScene().getEngine();
  52502. var dw = this.getRenderWidth() / engine.getRenderWidth();
  52503. var dh = this.getRenderHeight() / engine.getRenderHeight();
  52504. this.blurKernelX = this._adaptiveBlurKernel * dw;
  52505. this.blurKernelY = this._adaptiveBlurKernel * dh;
  52506. };
  52507. MirrorTexture.prototype._onRatioRescale = function () {
  52508. if (this._sizeRatio) {
  52509. this.resize(this._initialSizeParameter);
  52510. if (!this._adaptiveBlurKernel) {
  52511. this._preparePostProcesses();
  52512. }
  52513. }
  52514. if (this._adaptiveBlurKernel) {
  52515. this._autoComputeBlurKernel();
  52516. }
  52517. };
  52518. MirrorTexture.prototype._preparePostProcesses = function () {
  52519. this.clearPostProcesses(true);
  52520. if (this._blurKernelX && this._blurKernelY) {
  52521. var engine = this.getScene().getEngine();
  52522. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52523. 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);
  52524. this._blurX.autoClear = false;
  52525. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52526. this._blurX.outputTexture = this._texture;
  52527. }
  52528. else {
  52529. this._blurX.alwaysForcePOT = true;
  52530. }
  52531. 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);
  52532. this._blurY.autoClear = false;
  52533. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52534. this.addPostProcess(this._blurX);
  52535. this.addPostProcess(this._blurY);
  52536. }
  52537. else {
  52538. if (this._blurY) {
  52539. this.removePostProcess(this._blurY);
  52540. this._blurY.dispose();
  52541. this._blurY = null;
  52542. }
  52543. if (this._blurX) {
  52544. this.removePostProcess(this._blurX);
  52545. this._blurX.dispose();
  52546. this._blurX = null;
  52547. }
  52548. }
  52549. };
  52550. MirrorTexture.prototype.clone = function () {
  52551. var scene = this.getScene();
  52552. if (!scene) {
  52553. return this;
  52554. }
  52555. var textureSize = this.getSize();
  52556. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52557. // Base texture
  52558. newTexture.hasAlpha = this.hasAlpha;
  52559. newTexture.level = this.level;
  52560. // Mirror Texture
  52561. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52562. if (this.renderList) {
  52563. newTexture.renderList = this.renderList.slice(0);
  52564. }
  52565. return newTexture;
  52566. };
  52567. MirrorTexture.prototype.serialize = function () {
  52568. if (!this.name) {
  52569. return null;
  52570. }
  52571. var serializationObject = _super.prototype.serialize.call(this);
  52572. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52573. return serializationObject;
  52574. };
  52575. return MirrorTexture;
  52576. }(BABYLON.RenderTargetTexture));
  52577. BABYLON.MirrorTexture = MirrorTexture;
  52578. })(BABYLON || (BABYLON = {}));
  52579. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52580. var BABYLON;
  52581. (function (BABYLON) {
  52582. /**
  52583. * Creates a refraction texture used by refraction channel of the standard material.
  52584. * @param name the texture name
  52585. * @param size size of the underlying texture
  52586. * @param scene root scene
  52587. */
  52588. var RefractionTexture = /** @class */ (function (_super) {
  52589. __extends(RefractionTexture, _super);
  52590. function RefractionTexture(name, size, scene, generateMipMaps) {
  52591. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52592. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52593. _this.depth = 2.0;
  52594. _this.onBeforeRenderObservable.add(function () {
  52595. scene.clipPlane = _this.refractionPlane;
  52596. });
  52597. _this.onAfterRenderObservable.add(function () {
  52598. delete scene.clipPlane;
  52599. });
  52600. return _this;
  52601. }
  52602. RefractionTexture.prototype.clone = function () {
  52603. var scene = this.getScene();
  52604. if (!scene) {
  52605. return this;
  52606. }
  52607. var textureSize = this.getSize();
  52608. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52609. // Base texture
  52610. newTexture.hasAlpha = this.hasAlpha;
  52611. newTexture.level = this.level;
  52612. // Refraction Texture
  52613. newTexture.refractionPlane = this.refractionPlane.clone();
  52614. if (this.renderList) {
  52615. newTexture.renderList = this.renderList.slice(0);
  52616. }
  52617. newTexture.depth = this.depth;
  52618. return newTexture;
  52619. };
  52620. RefractionTexture.prototype.serialize = function () {
  52621. if (!this.name) {
  52622. return null;
  52623. }
  52624. var serializationObject = _super.prototype.serialize.call(this);
  52625. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52626. serializationObject.depth = this.depth;
  52627. return serializationObject;
  52628. };
  52629. return RefractionTexture;
  52630. }(BABYLON.RenderTargetTexture));
  52631. BABYLON.RefractionTexture = RefractionTexture;
  52632. })(BABYLON || (BABYLON = {}));
  52633. //# sourceMappingURL=babylon.refractionTexture.js.map
  52634. var BABYLON;
  52635. (function (BABYLON) {
  52636. var DynamicTexture = /** @class */ (function (_super) {
  52637. __extends(DynamicTexture, _super);
  52638. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52639. if (scene === void 0) { scene = null; }
  52640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52641. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52642. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52643. _this.name = name;
  52644. _this._engine = _this.getScene().getEngine();
  52645. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52646. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52647. _this._generateMipMaps = generateMipMaps;
  52648. if (options.getContext) {
  52649. _this._canvas = options;
  52650. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52651. }
  52652. else {
  52653. _this._canvas = document.createElement("canvas");
  52654. if (options.width) {
  52655. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52656. }
  52657. else {
  52658. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52659. }
  52660. }
  52661. var textureSize = _this.getSize();
  52662. _this._canvas.width = textureSize.width;
  52663. _this._canvas.height = textureSize.height;
  52664. _this._context = _this._canvas.getContext("2d");
  52665. return _this;
  52666. }
  52667. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52668. get: function () {
  52669. return true;
  52670. },
  52671. enumerable: true,
  52672. configurable: true
  52673. });
  52674. DynamicTexture.prototype._recreate = function (textureSize) {
  52675. this._canvas.width = textureSize.width;
  52676. this._canvas.height = textureSize.height;
  52677. this.releaseInternalTexture();
  52678. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52679. };
  52680. DynamicTexture.prototype.scale = function (ratio) {
  52681. var textureSize = this.getSize();
  52682. textureSize.width *= ratio;
  52683. textureSize.height *= ratio;
  52684. this._recreate(textureSize);
  52685. };
  52686. DynamicTexture.prototype.scaleTo = function (width, height) {
  52687. var textureSize = this.getSize();
  52688. textureSize.width = width;
  52689. textureSize.height = height;
  52690. this._recreate(textureSize);
  52691. };
  52692. DynamicTexture.prototype.getContext = function () {
  52693. return this._context;
  52694. };
  52695. DynamicTexture.prototype.clear = function () {
  52696. var size = this.getSize();
  52697. this._context.fillRect(0, 0, size.width, size.height);
  52698. };
  52699. DynamicTexture.prototype.update = function (invertY) {
  52700. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52701. };
  52702. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52703. if (update === void 0) { update = true; }
  52704. var size = this.getSize();
  52705. if (clearColor) {
  52706. this._context.fillStyle = clearColor;
  52707. this._context.fillRect(0, 0, size.width, size.height);
  52708. }
  52709. this._context.font = font;
  52710. if (x === null || x === undefined) {
  52711. var textSize = this._context.measureText(text);
  52712. x = (size.width - textSize.width) / 2;
  52713. }
  52714. if (y === null || y === undefined) {
  52715. var fontSize = parseInt((font.replace(/\D/g, '')));
  52716. ;
  52717. y = (size.height / 2) + (fontSize / 3.65);
  52718. }
  52719. this._context.fillStyle = color;
  52720. this._context.fillText(text, x, y);
  52721. if (update) {
  52722. this.update(invertY);
  52723. }
  52724. };
  52725. DynamicTexture.prototype.clone = function () {
  52726. var scene = this.getScene();
  52727. if (!scene) {
  52728. return this;
  52729. }
  52730. var textureSize = this.getSize();
  52731. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52732. // Base texture
  52733. newTexture.hasAlpha = this.hasAlpha;
  52734. newTexture.level = this.level;
  52735. // Dynamic Texture
  52736. newTexture.wrapU = this.wrapU;
  52737. newTexture.wrapV = this.wrapV;
  52738. return newTexture;
  52739. };
  52740. DynamicTexture.prototype._rebuild = function () {
  52741. this.update();
  52742. };
  52743. return DynamicTexture;
  52744. }(BABYLON.Texture));
  52745. BABYLON.DynamicTexture = DynamicTexture;
  52746. })(BABYLON || (BABYLON = {}));
  52747. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52748. var BABYLON;
  52749. (function (BABYLON) {
  52750. var VideoTexture = /** @class */ (function (_super) {
  52751. __extends(VideoTexture, _super);
  52752. /**
  52753. * Creates a video texture.
  52754. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52755. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52756. * @param {BABYLON.Scene} scene is obviously the current scene.
  52757. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52758. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52759. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52760. */
  52761. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52762. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52763. if (invertY === void 0) { invertY = false; }
  52764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52765. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52766. _this._autoLaunch = true;
  52767. var urls = null;
  52768. _this.name = name;
  52769. if (urlsOrVideo instanceof HTMLVideoElement) {
  52770. _this.video = urlsOrVideo;
  52771. }
  52772. else {
  52773. urls = urlsOrVideo;
  52774. _this.video = document.createElement("video");
  52775. _this.video.autoplay = false;
  52776. _this.video.loop = true;
  52777. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52778. }
  52779. _this._engine = _this.getScene().getEngine();
  52780. _this._generateMipMaps = generateMipMaps;
  52781. _this._samplingMode = samplingMode;
  52782. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52783. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52784. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52785. }
  52786. else {
  52787. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52788. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52789. _this._generateMipMaps = false;
  52790. }
  52791. if (urls) {
  52792. _this.video.addEventListener("canplay", function () {
  52793. if (_this._texture === undefined) {
  52794. _this._createTexture();
  52795. }
  52796. });
  52797. urls.forEach(function (url) {
  52798. var source = document.createElement("source");
  52799. source.src = url;
  52800. _this.video.appendChild(source);
  52801. });
  52802. }
  52803. else {
  52804. _this._createTexture();
  52805. }
  52806. _this._lastUpdate = BABYLON.Tools.Now;
  52807. return _this;
  52808. }
  52809. VideoTexture.prototype.__setTextureReady = function () {
  52810. if (this._texture) {
  52811. this._texture.isReady = true;
  52812. }
  52813. };
  52814. VideoTexture.prototype._createTexture = function () {
  52815. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52816. if (this._autoLaunch) {
  52817. this._autoLaunch = false;
  52818. this.video.play();
  52819. }
  52820. this._setTextureReady = this.__setTextureReady.bind(this);
  52821. this.video.addEventListener("playing", this._setTextureReady);
  52822. };
  52823. VideoTexture.prototype._rebuild = function () {
  52824. this.update();
  52825. };
  52826. VideoTexture.prototype.update = function () {
  52827. var now = BABYLON.Tools.Now;
  52828. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52829. return false;
  52830. }
  52831. this._lastUpdate = now;
  52832. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52833. return true;
  52834. };
  52835. VideoTexture.prototype.dispose = function () {
  52836. _super.prototype.dispose.call(this);
  52837. this.video.removeEventListener("playing", this._setTextureReady);
  52838. };
  52839. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  52840. var video = document.createElement("video");
  52841. var constraintsDeviceId;
  52842. if (constraints && constraints.deviceId) {
  52843. constraintsDeviceId = {
  52844. exact: constraints.deviceId
  52845. };
  52846. }
  52847. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  52848. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  52849. if (navigator.getUserMedia) {
  52850. navigator.getUserMedia({
  52851. video: {
  52852. deviceId: constraintsDeviceId,
  52853. width: {
  52854. min: (constraints && constraints.minWidth) || 256,
  52855. max: (constraints && constraints.maxWidth) || 640
  52856. },
  52857. height: {
  52858. min: (constraints && constraints.minHeight) || 256,
  52859. max: (constraints && constraints.maxHeight) || 480
  52860. }
  52861. }
  52862. }, function (stream) {
  52863. if (video.mozSrcObject !== undefined) {
  52864. video.mozSrcObject = stream;
  52865. }
  52866. else {
  52867. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  52868. }
  52869. video.play();
  52870. if (onReady) {
  52871. onReady(new VideoTexture("video", video, scene, true, true));
  52872. }
  52873. }, function (e) {
  52874. BABYLON.Tools.Error(e.name);
  52875. });
  52876. }
  52877. };
  52878. return VideoTexture;
  52879. }(BABYLON.Texture));
  52880. BABYLON.VideoTexture = VideoTexture;
  52881. })(BABYLON || (BABYLON = {}));
  52882. //# sourceMappingURL=babylon.videoTexture.js.map
  52883. var BABYLON;
  52884. (function (BABYLON) {
  52885. var RawTexture = /** @class */ (function (_super) {
  52886. __extends(RawTexture, _super);
  52887. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  52888. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52889. if (invertY === void 0) { invertY = false; }
  52890. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52891. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52892. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52893. _this.format = format;
  52894. _this._engine = scene.getEngine();
  52895. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  52896. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52897. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52898. return _this;
  52899. }
  52900. RawTexture.prototype.update = function (data) {
  52901. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  52902. };
  52903. // Statics
  52904. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52905. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52906. if (invertY === void 0) { invertY = false; }
  52907. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52908. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52909. };
  52910. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52911. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52912. if (invertY === void 0) { invertY = false; }
  52913. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52914. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52915. };
  52916. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52917. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52918. if (invertY === void 0) { invertY = false; }
  52919. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52920. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52921. };
  52922. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52923. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52924. if (invertY === void 0) { invertY = false; }
  52925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52926. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52927. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  52928. };
  52929. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52930. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52931. if (invertY === void 0) { invertY = false; }
  52932. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52933. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52934. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  52935. };
  52936. return RawTexture;
  52937. }(BABYLON.Texture));
  52938. BABYLON.RawTexture = RawTexture;
  52939. })(BABYLON || (BABYLON = {}));
  52940. //# sourceMappingURL=babylon.rawTexture.js.map
  52941. var BABYLON;
  52942. (function (BABYLON) {
  52943. var PostProcess = /** @class */ (function () {
  52944. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  52945. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  52946. if (defines === void 0) { defines = null; }
  52947. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52948. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  52949. if (blockCompilation === void 0) { blockCompilation = false; }
  52950. this.name = name;
  52951. this.width = -1;
  52952. this.height = -1;
  52953. this.autoClear = true;
  52954. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  52955. this.animations = new Array();
  52956. /*
  52957. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  52958. Can only be used on a single postprocess or on the last one of a chain.
  52959. */
  52960. this.enablePixelPerfectMode = false;
  52961. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  52962. this.alwaysForcePOT = false;
  52963. this.samples = 1;
  52964. this.adaptScaleToCurrentViewport = false;
  52965. this._reusable = false;
  52966. this._textures = new BABYLON.SmartArray(2);
  52967. this._currentRenderTextureInd = 0;
  52968. this._scaleRatio = new BABYLON.Vector2(1, 1);
  52969. this._texelSize = BABYLON.Vector2.Zero();
  52970. // Events
  52971. /**
  52972. * An event triggered when the postprocess is activated.
  52973. * @type {BABYLON.Observable}
  52974. */
  52975. this.onActivateObservable = new BABYLON.Observable();
  52976. /**
  52977. * An event triggered when the postprocess changes its size.
  52978. * @type {BABYLON.Observable}
  52979. */
  52980. this.onSizeChangedObservable = new BABYLON.Observable();
  52981. /**
  52982. * An event triggered when the postprocess applies its effect.
  52983. * @type {BABYLON.Observable}
  52984. */
  52985. this.onApplyObservable = new BABYLON.Observable();
  52986. /**
  52987. * An event triggered before rendering the postprocess
  52988. * @type {BABYLON.Observable}
  52989. */
  52990. this.onBeforeRenderObservable = new BABYLON.Observable();
  52991. /**
  52992. * An event triggered after rendering the postprocess
  52993. * @type {BABYLON.Observable}
  52994. */
  52995. this.onAfterRenderObservable = new BABYLON.Observable();
  52996. if (camera != null) {
  52997. this._camera = camera;
  52998. this._scene = camera.getScene();
  52999. camera.attachPostProcess(this);
  53000. this._engine = this._scene.getEngine();
  53001. this._scene.postProcesses.push(this);
  53002. }
  53003. else if (engine) {
  53004. this._engine = engine;
  53005. this._engine.postProcesses.push(this);
  53006. }
  53007. this._options = options;
  53008. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  53009. this._reusable = reusable || false;
  53010. this._textureType = textureType;
  53011. this._samplers = samplers || [];
  53012. this._samplers.push("textureSampler");
  53013. this._fragmentUrl = fragmentUrl;
  53014. this._vertexUrl = vertexUrl;
  53015. this._parameters = parameters || [];
  53016. this._parameters.push("scale");
  53017. this._indexParameters = indexParameters;
  53018. if (!blockCompilation) {
  53019. this.updateEffect(defines);
  53020. }
  53021. }
  53022. Object.defineProperty(PostProcess.prototype, "onActivate", {
  53023. set: function (callback) {
  53024. if (this._onActivateObserver) {
  53025. this.onActivateObservable.remove(this._onActivateObserver);
  53026. }
  53027. if (callback) {
  53028. this._onActivateObserver = this.onActivateObservable.add(callback);
  53029. }
  53030. },
  53031. enumerable: true,
  53032. configurable: true
  53033. });
  53034. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  53035. set: function (callback) {
  53036. if (this._onSizeChangedObserver) {
  53037. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  53038. }
  53039. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  53040. },
  53041. enumerable: true,
  53042. configurable: true
  53043. });
  53044. Object.defineProperty(PostProcess.prototype, "onApply", {
  53045. set: function (callback) {
  53046. if (this._onApplyObserver) {
  53047. this.onApplyObservable.remove(this._onApplyObserver);
  53048. }
  53049. this._onApplyObserver = this.onApplyObservable.add(callback);
  53050. },
  53051. enumerable: true,
  53052. configurable: true
  53053. });
  53054. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  53055. set: function (callback) {
  53056. if (this._onBeforeRenderObserver) {
  53057. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  53058. }
  53059. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  53060. },
  53061. enumerable: true,
  53062. configurable: true
  53063. });
  53064. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  53065. set: function (callback) {
  53066. if (this._onAfterRenderObserver) {
  53067. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  53068. }
  53069. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  53070. },
  53071. enumerable: true,
  53072. configurable: true
  53073. });
  53074. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  53075. get: function () {
  53076. return this._textures.data[this._currentRenderTextureInd];
  53077. },
  53078. set: function (value) {
  53079. this._forcedOutputTexture = value;
  53080. },
  53081. enumerable: true,
  53082. configurable: true
  53083. });
  53084. PostProcess.prototype.getCamera = function () {
  53085. return this._camera;
  53086. };
  53087. Object.defineProperty(PostProcess.prototype, "texelSize", {
  53088. get: function () {
  53089. if (this._shareOutputWithPostProcess) {
  53090. return this._shareOutputWithPostProcess.texelSize;
  53091. }
  53092. if (this._forcedOutputTexture) {
  53093. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  53094. }
  53095. return this._texelSize;
  53096. },
  53097. enumerable: true,
  53098. configurable: true
  53099. });
  53100. PostProcess.prototype.getEngine = function () {
  53101. return this._engine;
  53102. };
  53103. PostProcess.prototype.getEffect = function () {
  53104. return this._effect;
  53105. };
  53106. PostProcess.prototype.shareOutputWith = function (postProcess) {
  53107. this._disposeTextures();
  53108. this._shareOutputWithPostProcess = postProcess;
  53109. return this;
  53110. };
  53111. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  53112. if (defines === void 0) { defines = null; }
  53113. if (uniforms === void 0) { uniforms = null; }
  53114. if (samplers === void 0) { samplers = null; }
  53115. 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);
  53116. };
  53117. PostProcess.prototype.isReusable = function () {
  53118. return this._reusable;
  53119. };
  53120. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  53121. PostProcess.prototype.markTextureDirty = function () {
  53122. this.width = -1;
  53123. };
  53124. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  53125. var _this = this;
  53126. if (sourceTexture === void 0) { sourceTexture = null; }
  53127. camera = camera || this._camera;
  53128. var scene = camera.getScene();
  53129. var engine = scene.getEngine();
  53130. var maxSize = engine.getCaps().maxTextureSize;
  53131. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  53132. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  53133. var desiredWidth = (this._options.width || requiredWidth);
  53134. var desiredHeight = this._options.height || requiredHeight;
  53135. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  53136. if (this.adaptScaleToCurrentViewport) {
  53137. var currentViewport = engine.currentViewport;
  53138. if (currentViewport) {
  53139. desiredWidth *= currentViewport.width;
  53140. desiredHeight *= currentViewport.height;
  53141. }
  53142. }
  53143. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  53144. if (!this._options.width) {
  53145. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  53146. }
  53147. if (!this._options.height) {
  53148. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  53149. }
  53150. }
  53151. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  53152. if (this._textures.length > 0) {
  53153. for (var i = 0; i < this._textures.length; i++) {
  53154. this._engine._releaseTexture(this._textures.data[i]);
  53155. }
  53156. this._textures.reset();
  53157. }
  53158. this.width = desiredWidth;
  53159. this.height = desiredHeight;
  53160. var textureSize = { width: this.width, height: this.height };
  53161. var textureOptions = {
  53162. generateMipMaps: false,
  53163. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  53164. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  53165. samplingMode: this.renderTargetSamplingMode,
  53166. type: this._textureType
  53167. };
  53168. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53169. if (this._reusable) {
  53170. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  53171. }
  53172. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  53173. this.onSizeChangedObservable.notifyObservers(this);
  53174. }
  53175. this._textures.forEach(function (texture) {
  53176. if (texture.samples !== _this.samples) {
  53177. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  53178. }
  53179. });
  53180. }
  53181. var target;
  53182. if (this._shareOutputWithPostProcess) {
  53183. target = this._shareOutputWithPostProcess.outputTexture;
  53184. }
  53185. else if (this._forcedOutputTexture) {
  53186. target = this._forcedOutputTexture;
  53187. this.width = this._forcedOutputTexture.width;
  53188. this.height = this._forcedOutputTexture.height;
  53189. }
  53190. else {
  53191. target = this.outputTexture;
  53192. }
  53193. if (this.enablePixelPerfectMode) {
  53194. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  53195. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  53196. }
  53197. else {
  53198. this._scaleRatio.copyFromFloats(1, 1);
  53199. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  53200. }
  53201. this.onActivateObservable.notifyObservers(camera);
  53202. // Clear
  53203. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  53204. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  53205. }
  53206. if (this._reusable) {
  53207. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  53208. }
  53209. };
  53210. Object.defineProperty(PostProcess.prototype, "isSupported", {
  53211. get: function () {
  53212. return this._effect.isSupported;
  53213. },
  53214. enumerable: true,
  53215. configurable: true
  53216. });
  53217. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  53218. get: function () {
  53219. if (this._shareOutputWithPostProcess) {
  53220. return this._shareOutputWithPostProcess.aspectRatio;
  53221. }
  53222. if (this._forcedOutputTexture) {
  53223. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  53224. }
  53225. return this.width / this.height;
  53226. },
  53227. enumerable: true,
  53228. configurable: true
  53229. });
  53230. /**
  53231. * Get a value indicating if the post-process is ready to be used
  53232. * @returns true if the post-process is ready (shader is compiled)
  53233. */
  53234. PostProcess.prototype.isReady = function () {
  53235. return this._effect && this._effect.isReady();
  53236. };
  53237. PostProcess.prototype.apply = function () {
  53238. // Check
  53239. if (!this._effect || !this._effect.isReady())
  53240. return null;
  53241. // States
  53242. this._engine.enableEffect(this._effect);
  53243. this._engine.setState(false);
  53244. this._engine.setDepthBuffer(false);
  53245. this._engine.setDepthWrite(false);
  53246. // Alpha
  53247. this._engine.setAlphaMode(this.alphaMode);
  53248. if (this.alphaConstants) {
  53249. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  53250. }
  53251. // Texture
  53252. var source;
  53253. if (this._shareOutputWithPostProcess) {
  53254. source = this._shareOutputWithPostProcess.outputTexture;
  53255. }
  53256. else if (this._forcedOutputTexture) {
  53257. source = this._forcedOutputTexture;
  53258. }
  53259. else {
  53260. source = this.outputTexture;
  53261. }
  53262. this._effect._bindTexture("textureSampler", source);
  53263. // Parameters
  53264. this._effect.setVector2("scale", this._scaleRatio);
  53265. this.onApplyObservable.notifyObservers(this._effect);
  53266. return this._effect;
  53267. };
  53268. PostProcess.prototype._disposeTextures = function () {
  53269. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  53270. return;
  53271. }
  53272. if (this._textures.length > 0) {
  53273. for (var i = 0; i < this._textures.length; i++) {
  53274. this._engine._releaseTexture(this._textures.data[i]);
  53275. }
  53276. }
  53277. this._textures.dispose();
  53278. };
  53279. PostProcess.prototype.dispose = function (camera) {
  53280. camera = camera || this._camera;
  53281. this._disposeTextures();
  53282. if (this._scene) {
  53283. var index_1 = this._scene.postProcesses.indexOf(this);
  53284. if (index_1 !== -1) {
  53285. this._scene.postProcesses.splice(index_1, 1);
  53286. }
  53287. }
  53288. else {
  53289. var index_2 = this._engine.postProcesses.indexOf(this);
  53290. if (index_2 !== -1) {
  53291. this._engine.postProcesses.splice(index_2, 1);
  53292. }
  53293. }
  53294. if (!camera) {
  53295. return;
  53296. }
  53297. camera.detachPostProcess(this);
  53298. var index = camera._postProcesses.indexOf(this);
  53299. if (index === 0 && camera._postProcesses.length > 0) {
  53300. this._camera._postProcesses[0].markTextureDirty();
  53301. }
  53302. this.onActivateObservable.clear();
  53303. this.onAfterRenderObservable.clear();
  53304. this.onApplyObservable.clear();
  53305. this.onBeforeRenderObservable.clear();
  53306. this.onSizeChangedObservable.clear();
  53307. };
  53308. return PostProcess;
  53309. }());
  53310. BABYLON.PostProcess = PostProcess;
  53311. })(BABYLON || (BABYLON = {}));
  53312. //# sourceMappingURL=babylon.postProcess.js.map
  53313. var BABYLON;
  53314. (function (BABYLON) {
  53315. var PassPostProcess = /** @class */ (function (_super) {
  53316. __extends(PassPostProcess, _super);
  53317. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53318. if (camera === void 0) { camera = null; }
  53319. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53320. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  53321. }
  53322. return PassPostProcess;
  53323. }(BABYLON.PostProcess));
  53324. BABYLON.PassPostProcess = PassPostProcess;
  53325. })(BABYLON || (BABYLON = {}));
  53326. //# sourceMappingURL=babylon.passPostProcess.js.map
  53327. var __assign = (this && this.__assign) || Object.assign || function(t) {
  53328. for (var s, i = 1, n = arguments.length; i < n; i++) {
  53329. s = arguments[i];
  53330. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  53331. t[p] = s[p];
  53332. }
  53333. return t;
  53334. };
  53335. var BABYLON;
  53336. (function (BABYLON) {
  53337. var ShadowGenerator = /** @class */ (function () {
  53338. /**
  53339. * Creates a ShadowGenerator object.
  53340. * A ShadowGenerator is the required tool to use the shadows.
  53341. * Each light casting shadows needs to use its own ShadowGenerator.
  53342. * Required parameters :
  53343. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  53344. * - `light`: the light object generating the shadows.
  53345. * - `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.
  53346. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  53347. */
  53348. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  53349. // Members
  53350. this._bias = 0.00005;
  53351. this._blurBoxOffset = 1;
  53352. this._blurScale = 2;
  53353. this._blurKernel = 1;
  53354. this._useKernelBlur = false;
  53355. this._filter = ShadowGenerator.FILTER_NONE;
  53356. this._darkness = 0;
  53357. this._transparencyShadow = false;
  53358. /**
  53359. * Controls the extent to which the shadows fade out at the edge of the frustum
  53360. * Used only by directionals and spots
  53361. */
  53362. this.frustumEdgeFalloff = 0;
  53363. this.forceBackFacesOnly = false;
  53364. this._lightDirection = BABYLON.Vector3.Zero();
  53365. this._viewMatrix = BABYLON.Matrix.Zero();
  53366. this._projectionMatrix = BABYLON.Matrix.Zero();
  53367. this._transformMatrix = BABYLON.Matrix.Zero();
  53368. this._currentFaceIndex = 0;
  53369. this._currentFaceIndexCache = 0;
  53370. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  53371. this._mapSize = mapSize;
  53372. this._light = light;
  53373. this._scene = light.getScene();
  53374. light._shadowGenerator = this;
  53375. // Texture type fallback from float to int if not supported.
  53376. var caps = this._scene.getEngine().getCaps();
  53377. if (!useFullFloatFirst) {
  53378. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53379. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53380. }
  53381. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53382. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53383. }
  53384. else {
  53385. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53386. }
  53387. }
  53388. else {
  53389. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  53390. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53391. }
  53392. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  53393. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53394. }
  53395. else {
  53396. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53397. }
  53398. }
  53399. this._initializeGenerator();
  53400. }
  53401. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  53402. // Static
  53403. get: function () {
  53404. return ShadowGenerator._FILTER_NONE;
  53405. },
  53406. enumerable: true,
  53407. configurable: true
  53408. });
  53409. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  53410. get: function () {
  53411. return ShadowGenerator._FILTER_POISSONSAMPLING;
  53412. },
  53413. enumerable: true,
  53414. configurable: true
  53415. });
  53416. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  53417. get: function () {
  53418. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  53419. },
  53420. enumerable: true,
  53421. configurable: true
  53422. });
  53423. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  53424. get: function () {
  53425. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  53426. },
  53427. enumerable: true,
  53428. configurable: true
  53429. });
  53430. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  53431. get: function () {
  53432. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53433. },
  53434. enumerable: true,
  53435. configurable: true
  53436. });
  53437. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  53438. get: function () {
  53439. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53440. },
  53441. enumerable: true,
  53442. configurable: true
  53443. });
  53444. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  53445. get: function () {
  53446. return this._bias;
  53447. },
  53448. set: function (bias) {
  53449. this._bias = bias;
  53450. },
  53451. enumerable: true,
  53452. configurable: true
  53453. });
  53454. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  53455. get: function () {
  53456. return this._blurBoxOffset;
  53457. },
  53458. set: function (value) {
  53459. if (this._blurBoxOffset === value) {
  53460. return;
  53461. }
  53462. this._blurBoxOffset = value;
  53463. this._disposeBlurPostProcesses();
  53464. },
  53465. enumerable: true,
  53466. configurable: true
  53467. });
  53468. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  53469. get: function () {
  53470. return this._blurScale;
  53471. },
  53472. set: function (value) {
  53473. if (this._blurScale === value) {
  53474. return;
  53475. }
  53476. this._blurScale = value;
  53477. this._disposeBlurPostProcesses();
  53478. },
  53479. enumerable: true,
  53480. configurable: true
  53481. });
  53482. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  53483. get: function () {
  53484. return this._blurKernel;
  53485. },
  53486. set: function (value) {
  53487. if (this._blurKernel === value) {
  53488. return;
  53489. }
  53490. this._blurKernel = value;
  53491. this._disposeBlurPostProcesses();
  53492. },
  53493. enumerable: true,
  53494. configurable: true
  53495. });
  53496. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  53497. get: function () {
  53498. return this._useKernelBlur;
  53499. },
  53500. set: function (value) {
  53501. if (this._useKernelBlur === value) {
  53502. return;
  53503. }
  53504. this._useKernelBlur = value;
  53505. this._disposeBlurPostProcesses();
  53506. },
  53507. enumerable: true,
  53508. configurable: true
  53509. });
  53510. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  53511. get: function () {
  53512. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  53513. },
  53514. set: function (value) {
  53515. this._depthScale = value;
  53516. },
  53517. enumerable: true,
  53518. configurable: true
  53519. });
  53520. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  53521. get: function () {
  53522. return this._filter;
  53523. },
  53524. set: function (value) {
  53525. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53526. if (this._light.needCube()) {
  53527. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53528. this.useExponentialShadowMap = true;
  53529. return;
  53530. }
  53531. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53532. this.useCloseExponentialShadowMap = true;
  53533. return;
  53534. }
  53535. }
  53536. if (this._filter === value) {
  53537. return;
  53538. }
  53539. this._filter = value;
  53540. this._disposeBlurPostProcesses();
  53541. this._applyFilterValues();
  53542. this._light._markMeshesAsLightDirty();
  53543. },
  53544. enumerable: true,
  53545. configurable: true
  53546. });
  53547. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53548. get: function () {
  53549. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53550. },
  53551. set: function (value) {
  53552. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53553. return;
  53554. }
  53555. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53556. },
  53557. enumerable: true,
  53558. configurable: true
  53559. });
  53560. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53561. get: function () {
  53562. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53563. return this.useExponentialShadowMap;
  53564. },
  53565. set: function (value) {
  53566. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53567. this.useExponentialShadowMap = value;
  53568. },
  53569. enumerable: true,
  53570. configurable: true
  53571. });
  53572. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53573. get: function () {
  53574. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53575. return this.useBlurExponentialShadowMap;
  53576. },
  53577. set: function (value) {
  53578. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53579. this.useBlurExponentialShadowMap = value;
  53580. },
  53581. enumerable: true,
  53582. configurable: true
  53583. });
  53584. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53585. get: function () {
  53586. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53587. },
  53588. set: function (value) {
  53589. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53590. return;
  53591. }
  53592. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53593. },
  53594. enumerable: true,
  53595. configurable: true
  53596. });
  53597. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53598. get: function () {
  53599. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53600. },
  53601. set: function (value) {
  53602. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53603. return;
  53604. }
  53605. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53606. },
  53607. enumerable: true,
  53608. configurable: true
  53609. });
  53610. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53611. get: function () {
  53612. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53613. },
  53614. set: function (value) {
  53615. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53616. return;
  53617. }
  53618. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53619. },
  53620. enumerable: true,
  53621. configurable: true
  53622. });
  53623. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53624. get: function () {
  53625. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53626. },
  53627. set: function (value) {
  53628. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53629. return;
  53630. }
  53631. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53632. },
  53633. enumerable: true,
  53634. configurable: true
  53635. });
  53636. /**
  53637. * Returns the darkness value (float).
  53638. */
  53639. ShadowGenerator.prototype.getDarkness = function () {
  53640. return this._darkness;
  53641. };
  53642. /**
  53643. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53644. * Returns the ShadowGenerator.
  53645. */
  53646. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53647. if (darkness >= 1.0)
  53648. this._darkness = 1.0;
  53649. else if (darkness <= 0.0)
  53650. this._darkness = 0.0;
  53651. else
  53652. this._darkness = darkness;
  53653. return this;
  53654. };
  53655. /**
  53656. * Sets the ability to have transparent shadow (boolean).
  53657. * Returns the ShadowGenerator.
  53658. */
  53659. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53660. this._transparencyShadow = hasShadow;
  53661. return this;
  53662. };
  53663. /**
  53664. * Returns a RenderTargetTexture object : the shadow map texture.
  53665. */
  53666. ShadowGenerator.prototype.getShadowMap = function () {
  53667. return this._shadowMap;
  53668. };
  53669. /**
  53670. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53671. */
  53672. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53673. if (this._shadowMap2) {
  53674. return this._shadowMap2;
  53675. }
  53676. return this._shadowMap;
  53677. };
  53678. /**
  53679. * Helper function to add a mesh and its descendants to the list of shadow casters
  53680. * @param mesh Mesh to add
  53681. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53682. */
  53683. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53684. if (includeDescendants === void 0) { includeDescendants = true; }
  53685. if (!this._shadowMap) {
  53686. return this;
  53687. }
  53688. if (!this._shadowMap.renderList) {
  53689. this._shadowMap.renderList = [];
  53690. }
  53691. this._shadowMap.renderList.push(mesh);
  53692. if (includeDescendants) {
  53693. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53694. }
  53695. return this;
  53696. var _a;
  53697. };
  53698. /**
  53699. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53700. * @param mesh Mesh to remove
  53701. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53702. */
  53703. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53704. if (includeDescendants === void 0) { includeDescendants = true; }
  53705. if (!this._shadowMap || !this._shadowMap.renderList) {
  53706. return this;
  53707. }
  53708. var index = this._shadowMap.renderList.indexOf(mesh);
  53709. if (index !== -1) {
  53710. this._shadowMap.renderList.splice(index, 1);
  53711. }
  53712. if (includeDescendants) {
  53713. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53714. var child = _a[_i];
  53715. this.removeShadowCaster(child);
  53716. }
  53717. }
  53718. return this;
  53719. };
  53720. /**
  53721. * Returns the associated light object.
  53722. */
  53723. ShadowGenerator.prototype.getLight = function () {
  53724. return this._light;
  53725. };
  53726. ShadowGenerator.prototype._initializeGenerator = function () {
  53727. this._light._markMeshesAsLightDirty();
  53728. this._initializeShadowMap();
  53729. };
  53730. ShadowGenerator.prototype._initializeShadowMap = function () {
  53731. var _this = this;
  53732. // Render target
  53733. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53734. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53735. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53736. this._shadowMap.anisotropicFilteringLevel = 1;
  53737. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53738. this._shadowMap.renderParticles = false;
  53739. this._shadowMap.ignoreCameraViewport = true;
  53740. // Record Face Index before render.
  53741. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53742. _this._currentFaceIndex = faceIndex;
  53743. });
  53744. // Custom render function.
  53745. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53746. // Blur if required afer render.
  53747. this._shadowMap.onAfterUnbindObservable.add(function () {
  53748. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53749. return;
  53750. }
  53751. var shadowMap = _this.getShadowMapForRendering();
  53752. if (shadowMap) {
  53753. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53754. }
  53755. });
  53756. // Clear according to the chosen filter.
  53757. this._shadowMap.onClearObservable.add(function (engine) {
  53758. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53759. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53760. }
  53761. else {
  53762. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53763. }
  53764. });
  53765. };
  53766. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53767. var _this = this;
  53768. var engine = this._scene.getEngine();
  53769. var targetSize = this._mapSize / this.blurScale;
  53770. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53771. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53772. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53773. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53774. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53775. }
  53776. if (this.useKernelBlur) {
  53777. 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);
  53778. this._kernelBlurXPostprocess.width = targetSize;
  53779. this._kernelBlurXPostprocess.height = targetSize;
  53780. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53781. effect.setTexture("textureSampler", _this._shadowMap);
  53782. });
  53783. 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);
  53784. this._kernelBlurXPostprocess.autoClear = false;
  53785. this._kernelBlurYPostprocess.autoClear = false;
  53786. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53787. this._kernelBlurXPostprocess.packedFloat = true;
  53788. this._kernelBlurYPostprocess.packedFloat = true;
  53789. }
  53790. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53791. }
  53792. else {
  53793. 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);
  53794. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53795. effect.setFloat2("screenSize", targetSize, targetSize);
  53796. effect.setTexture("textureSampler", _this._shadowMap);
  53797. });
  53798. this._boxBlurPostprocess.autoClear = false;
  53799. this._blurPostProcesses = [this._boxBlurPostprocess];
  53800. }
  53801. };
  53802. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53803. var index;
  53804. var engine = this._scene.getEngine();
  53805. if (depthOnlySubMeshes.length) {
  53806. engine.setColorWrite(false);
  53807. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53808. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53809. }
  53810. engine.setColorWrite(true);
  53811. }
  53812. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53813. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53814. }
  53815. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53816. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53817. }
  53818. if (this._transparencyShadow) {
  53819. for (index = 0; index < transparentSubMeshes.length; index++) {
  53820. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53821. }
  53822. }
  53823. };
  53824. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53825. var _this = this;
  53826. var mesh = subMesh.getRenderingMesh();
  53827. var scene = this._scene;
  53828. var engine = scene.getEngine();
  53829. var material = subMesh.getMaterial();
  53830. if (!material) {
  53831. return;
  53832. }
  53833. // Culling
  53834. engine.setState(material.backFaceCulling);
  53835. // Managing instances
  53836. var batch = mesh._getInstancesRenderList(subMesh._id);
  53837. if (batch.mustReturn) {
  53838. return;
  53839. }
  53840. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53841. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  53842. engine.enableEffect(this._effect);
  53843. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53844. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  53845. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  53846. this._effect.setVector3("lightPosition", this.getLight().position);
  53847. if (scene.activeCamera) {
  53848. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  53849. }
  53850. // Alpha test
  53851. if (material && material.needAlphaTesting()) {
  53852. var alphaTexture = material.getAlphaTestTexture();
  53853. if (alphaTexture) {
  53854. this._effect.setTexture("diffuseSampler", alphaTexture);
  53855. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  53856. }
  53857. }
  53858. // Bones
  53859. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53860. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  53861. }
  53862. if (this.forceBackFacesOnly) {
  53863. engine.setState(true, 0, false, true);
  53864. }
  53865. // Draw
  53866. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53867. if (this.forceBackFacesOnly) {
  53868. engine.setState(true, 0, false, false);
  53869. }
  53870. }
  53871. else {
  53872. // Need to reset refresh rate of the shadowMap
  53873. if (this._shadowMap) {
  53874. this._shadowMap.resetRefreshCounter();
  53875. }
  53876. }
  53877. };
  53878. ShadowGenerator.prototype._applyFilterValues = function () {
  53879. if (!this._shadowMap) {
  53880. return;
  53881. }
  53882. if (this.filter === ShadowGenerator.FILTER_NONE) {
  53883. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  53884. }
  53885. else {
  53886. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53887. }
  53888. };
  53889. /**
  53890. * Force shader compilation including textures ready check
  53891. */
  53892. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  53893. var _this = this;
  53894. var localOptions = __assign({ useInstances: false }, options);
  53895. var shadowMap = this.getShadowMap();
  53896. if (!shadowMap) {
  53897. if (onCompiled) {
  53898. onCompiled(this);
  53899. }
  53900. return;
  53901. }
  53902. var renderList = shadowMap.renderList;
  53903. if (!renderList) {
  53904. if (onCompiled) {
  53905. onCompiled(this);
  53906. }
  53907. return;
  53908. }
  53909. var subMeshes = new Array();
  53910. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  53911. var mesh = renderList_1[_i];
  53912. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  53913. }
  53914. if (subMeshes.length === 0) {
  53915. if (onCompiled) {
  53916. onCompiled(this);
  53917. }
  53918. return;
  53919. }
  53920. var currentIndex = 0;
  53921. var checkReady = function () {
  53922. if (!_this._scene || !_this._scene.getEngine()) {
  53923. return;
  53924. }
  53925. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  53926. currentIndex++;
  53927. if (currentIndex >= subMeshes.length) {
  53928. if (onCompiled) {
  53929. onCompiled(_this);
  53930. }
  53931. return;
  53932. }
  53933. }
  53934. setTimeout(checkReady, 16);
  53935. };
  53936. checkReady();
  53937. };
  53938. /**
  53939. * Boolean : true when the ShadowGenerator is finally computed.
  53940. */
  53941. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  53942. var defines = [];
  53943. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53944. defines.push("#define FLOAT");
  53945. }
  53946. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53947. defines.push("#define ESM");
  53948. }
  53949. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53950. var mesh = subMesh.getMesh();
  53951. var material = subMesh.getMaterial();
  53952. // Alpha test
  53953. if (material && material.needAlphaTesting()) {
  53954. var alphaTexture = material.getAlphaTestTexture();
  53955. if (alphaTexture) {
  53956. defines.push("#define ALPHATEST");
  53957. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53958. attribs.push(BABYLON.VertexBuffer.UVKind);
  53959. defines.push("#define UV1");
  53960. }
  53961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53962. if (alphaTexture.coordinatesIndex === 1) {
  53963. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53964. defines.push("#define UV2");
  53965. }
  53966. }
  53967. }
  53968. }
  53969. // Bones
  53970. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53971. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53972. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53973. if (mesh.numBoneInfluencers > 4) {
  53974. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53975. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53976. }
  53977. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53978. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53979. }
  53980. else {
  53981. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53982. }
  53983. // Instances
  53984. if (useInstances) {
  53985. defines.push("#define INSTANCES");
  53986. attribs.push("world0");
  53987. attribs.push("world1");
  53988. attribs.push("world2");
  53989. attribs.push("world3");
  53990. }
  53991. // Get correct effect
  53992. var join = defines.join("\n");
  53993. if (this._cachedDefines !== join) {
  53994. this._cachedDefines = join;
  53995. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  53996. }
  53997. if (!this._effect.isReady()) {
  53998. return false;
  53999. }
  54000. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54001. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  54002. this._initializeBlurRTTAndPostProcesses();
  54003. }
  54004. }
  54005. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  54006. return false;
  54007. }
  54008. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  54009. return false;
  54010. }
  54011. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  54012. return false;
  54013. }
  54014. return true;
  54015. };
  54016. /**
  54017. * This creates the defines related to the standard BJS materials.
  54018. */
  54019. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  54020. var scene = this._scene;
  54021. var light = this._light;
  54022. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54023. return;
  54024. }
  54025. defines["SHADOW" + lightIndex] = true;
  54026. if (this.usePoissonSampling) {
  54027. defines["SHADOWPCF" + lightIndex] = true;
  54028. }
  54029. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  54030. defines["SHADOWESM" + lightIndex] = true;
  54031. }
  54032. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  54033. defines["SHADOWCLOSEESM" + lightIndex] = true;
  54034. }
  54035. if (light.needCube()) {
  54036. defines["SHADOWCUBE" + lightIndex] = true;
  54037. }
  54038. };
  54039. /**
  54040. * This binds shadow lights related to the standard BJS materials.
  54041. * It implies the unifroms available on the materials are the standard BJS ones.
  54042. */
  54043. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  54044. var light = this._light;
  54045. var scene = this._scene;
  54046. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  54047. return;
  54048. }
  54049. var camera = scene.activeCamera;
  54050. if (!camera) {
  54051. return;
  54052. }
  54053. var shadowMap = this.getShadowMap();
  54054. if (!shadowMap) {
  54055. return;
  54056. }
  54057. if (!light.needCube()) {
  54058. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  54059. }
  54060. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  54061. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  54062. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  54063. };
  54064. // Methods
  54065. /**
  54066. * Returns a Matrix object : the updated transformation matrix.
  54067. */
  54068. ShadowGenerator.prototype.getTransformMatrix = function () {
  54069. var scene = this._scene;
  54070. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  54071. return this._transformMatrix;
  54072. }
  54073. this._currentRenderID = scene.getRenderId();
  54074. this._currentFaceIndexCache = this._currentFaceIndex;
  54075. var lightPosition = this._light.position;
  54076. if (this._light.computeTransformedInformation()) {
  54077. lightPosition = this._light.transformedPosition;
  54078. }
  54079. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  54080. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  54081. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  54082. }
  54083. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  54084. this._cachedPosition = lightPosition.clone();
  54085. this._cachedDirection = this._lightDirection.clone();
  54086. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  54087. var shadowMap = this.getShadowMap();
  54088. if (shadowMap) {
  54089. var renderList = shadowMap.renderList;
  54090. if (renderList) {
  54091. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  54092. }
  54093. }
  54094. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  54095. }
  54096. return this._transformMatrix;
  54097. };
  54098. ShadowGenerator.prototype.recreateShadowMap = function () {
  54099. var shadowMap = this._shadowMap;
  54100. if (!shadowMap) {
  54101. return;
  54102. }
  54103. // Track render list.
  54104. var renderList = shadowMap.renderList;
  54105. // Clean up existing data.
  54106. this._disposeRTTandPostProcesses();
  54107. // Reinitializes.
  54108. this._initializeGenerator();
  54109. // Reaffect the filter to ensure a correct fallback if necessary.
  54110. this.filter = this.filter;
  54111. // Reaffect the filter.
  54112. this._applyFilterValues();
  54113. // Reaffect Render List.
  54114. this._shadowMap.renderList = renderList;
  54115. };
  54116. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  54117. if (this._shadowMap2) {
  54118. this._shadowMap2.dispose();
  54119. this._shadowMap2 = null;
  54120. }
  54121. if (this._boxBlurPostprocess) {
  54122. this._boxBlurPostprocess.dispose();
  54123. this._boxBlurPostprocess = null;
  54124. }
  54125. if (this._kernelBlurXPostprocess) {
  54126. this._kernelBlurXPostprocess.dispose();
  54127. this._kernelBlurXPostprocess = null;
  54128. }
  54129. if (this._kernelBlurYPostprocess) {
  54130. this._kernelBlurYPostprocess.dispose();
  54131. this._kernelBlurYPostprocess = null;
  54132. }
  54133. this._blurPostProcesses = [];
  54134. };
  54135. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  54136. if (this._shadowMap) {
  54137. this._shadowMap.dispose();
  54138. this._shadowMap = null;
  54139. }
  54140. this._disposeBlurPostProcesses();
  54141. };
  54142. /**
  54143. * Disposes the ShadowGenerator.
  54144. * Returns nothing.
  54145. */
  54146. ShadowGenerator.prototype.dispose = function () {
  54147. this._disposeRTTandPostProcesses();
  54148. if (this._light) {
  54149. this._light._shadowGenerator = null;
  54150. this._light._markMeshesAsLightDirty();
  54151. }
  54152. };
  54153. /**
  54154. * Serializes the ShadowGenerator and returns a serializationObject.
  54155. */
  54156. ShadowGenerator.prototype.serialize = function () {
  54157. var serializationObject = {};
  54158. var shadowMap = this.getShadowMap();
  54159. if (!shadowMap) {
  54160. return serializationObject;
  54161. }
  54162. serializationObject.lightId = this._light.id;
  54163. serializationObject.mapSize = shadowMap.getRenderSize();
  54164. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  54165. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  54166. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54167. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  54168. serializationObject.usePoissonSampling = this.usePoissonSampling;
  54169. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  54170. serializationObject.depthScale = this.depthScale;
  54171. serializationObject.darkness = this.getDarkness();
  54172. serializationObject.blurBoxOffset = this.blurBoxOffset;
  54173. serializationObject.blurKernel = this.blurKernel;
  54174. serializationObject.blurScale = this.blurScale;
  54175. serializationObject.useKernelBlur = this.useKernelBlur;
  54176. serializationObject.transparencyShadow = this._transparencyShadow;
  54177. serializationObject.renderList = [];
  54178. if (shadowMap.renderList) {
  54179. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  54180. var mesh = shadowMap.renderList[meshIndex];
  54181. serializationObject.renderList.push(mesh.id);
  54182. }
  54183. }
  54184. return serializationObject;
  54185. };
  54186. /**
  54187. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  54188. */
  54189. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  54190. //casting to point light, as light is missing the position attr and typescript complains.
  54191. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  54192. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  54193. var shadowMap = shadowGenerator.getShadowMap();
  54194. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  54195. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  54196. meshes.forEach(function (mesh) {
  54197. if (!shadowMap) {
  54198. return;
  54199. }
  54200. if (!shadowMap.renderList) {
  54201. shadowMap.renderList = [];
  54202. }
  54203. shadowMap.renderList.push(mesh);
  54204. });
  54205. }
  54206. if (parsedShadowGenerator.usePoissonSampling) {
  54207. shadowGenerator.usePoissonSampling = true;
  54208. }
  54209. else if (parsedShadowGenerator.useExponentialShadowMap) {
  54210. shadowGenerator.useExponentialShadowMap = true;
  54211. }
  54212. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  54213. shadowGenerator.useBlurExponentialShadowMap = true;
  54214. }
  54215. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  54216. shadowGenerator.useCloseExponentialShadowMap = true;
  54217. }
  54218. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  54219. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  54220. }
  54221. else if (parsedShadowGenerator.useVarianceShadowMap) {
  54222. shadowGenerator.useExponentialShadowMap = true;
  54223. }
  54224. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  54225. shadowGenerator.useBlurExponentialShadowMap = true;
  54226. }
  54227. if (parsedShadowGenerator.depthScale) {
  54228. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  54229. }
  54230. if (parsedShadowGenerator.blurScale) {
  54231. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  54232. }
  54233. if (parsedShadowGenerator.blurBoxOffset) {
  54234. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  54235. }
  54236. if (parsedShadowGenerator.useKernelBlur) {
  54237. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  54238. }
  54239. if (parsedShadowGenerator.blurKernel) {
  54240. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  54241. }
  54242. if (parsedShadowGenerator.bias !== undefined) {
  54243. shadowGenerator.bias = parsedShadowGenerator.bias;
  54244. }
  54245. if (parsedShadowGenerator.darkness) {
  54246. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  54247. }
  54248. if (parsedShadowGenerator.transparencyShadow) {
  54249. shadowGenerator.setTransparencyShadow(true);
  54250. }
  54251. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  54252. return shadowGenerator;
  54253. };
  54254. ShadowGenerator._FILTER_NONE = 0;
  54255. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  54256. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  54257. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  54258. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  54259. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  54260. return ShadowGenerator;
  54261. }());
  54262. BABYLON.ShadowGenerator = ShadowGenerator;
  54263. })(BABYLON || (BABYLON = {}));
  54264. //# sourceMappingURL=babylon.shadowGenerator.js.map
  54265. var BABYLON;
  54266. (function (BABYLON) {
  54267. var DefaultLoadingScreen = /** @class */ (function () {
  54268. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  54269. if (_loadingText === void 0) { _loadingText = ""; }
  54270. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  54271. var _this = this;
  54272. this._renderingCanvas = _renderingCanvas;
  54273. this._loadingText = _loadingText;
  54274. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  54275. // Resize
  54276. this._resizeLoadingUI = function () {
  54277. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  54278. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  54279. if (!_this._loadingDiv) {
  54280. return;
  54281. }
  54282. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  54283. _this._loadingDiv.style.left = canvasRect.left + "px";
  54284. _this._loadingDiv.style.top = canvasRect.top + "px";
  54285. _this._loadingDiv.style.width = canvasRect.width + "px";
  54286. _this._loadingDiv.style.height = canvasRect.height + "px";
  54287. };
  54288. }
  54289. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  54290. if (this._loadingDiv) {
  54291. // Do not add a loading screen if there is already one
  54292. return;
  54293. }
  54294. this._loadingDiv = document.createElement("div");
  54295. this._loadingDiv.id = "babylonjsLoadingDiv";
  54296. this._loadingDiv.style.opacity = "0";
  54297. this._loadingDiv.style.transition = "opacity 1.5s ease";
  54298. this._loadingDiv.style.pointerEvents = "none";
  54299. // Loading text
  54300. this._loadingTextDiv = document.createElement("div");
  54301. this._loadingTextDiv.style.position = "absolute";
  54302. this._loadingTextDiv.style.left = "0";
  54303. this._loadingTextDiv.style.top = "50%";
  54304. this._loadingTextDiv.style.marginTop = "80px";
  54305. this._loadingTextDiv.style.width = "100%";
  54306. this._loadingTextDiv.style.height = "20px";
  54307. this._loadingTextDiv.style.fontFamily = "Arial";
  54308. this._loadingTextDiv.style.fontSize = "14px";
  54309. this._loadingTextDiv.style.color = "white";
  54310. this._loadingTextDiv.style.textAlign = "center";
  54311. this._loadingTextDiv.innerHTML = "Loading";
  54312. this._loadingDiv.appendChild(this._loadingTextDiv);
  54313. //set the predefined text
  54314. this._loadingTextDiv.innerHTML = this._loadingText;
  54315. // Generating keyframes
  54316. var style = document.createElement('style');
  54317. style.type = 'text/css';
  54318. 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 }";
  54319. style.innerHTML = keyFrames;
  54320. document.getElementsByTagName('head')[0].appendChild(style);
  54321. // Loading img
  54322. var imgBack = new Image();
  54323. 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";
  54324. imgBack.style.position = "absolute";
  54325. imgBack.style.left = "50%";
  54326. imgBack.style.top = "50%";
  54327. imgBack.style.marginLeft = "-60px";
  54328. imgBack.style.marginTop = "-60px";
  54329. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  54330. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  54331. imgBack.style.transformOrigin = "50% 50%";
  54332. imgBack.style.webkitTransformOrigin = "50% 50%";
  54333. this._loadingDiv.appendChild(imgBack);
  54334. this._resizeLoadingUI();
  54335. window.addEventListener("resize", this._resizeLoadingUI);
  54336. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54337. document.body.appendChild(this._loadingDiv);
  54338. this._loadingDiv.style.opacity = "1";
  54339. };
  54340. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  54341. var _this = this;
  54342. if (!this._loadingDiv) {
  54343. return;
  54344. }
  54345. var onTransitionEnd = function () {
  54346. if (!_this._loadingDiv) {
  54347. return;
  54348. }
  54349. document.body.removeChild(_this._loadingDiv);
  54350. window.removeEventListener("resize", _this._resizeLoadingUI);
  54351. _this._loadingDiv = null;
  54352. };
  54353. this._loadingDiv.style.opacity = "0";
  54354. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  54355. };
  54356. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  54357. set: function (text) {
  54358. this._loadingText = text;
  54359. if (this._loadingTextDiv) {
  54360. this._loadingTextDiv.innerHTML = this._loadingText;
  54361. }
  54362. },
  54363. enumerable: true,
  54364. configurable: true
  54365. });
  54366. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  54367. get: function () {
  54368. return this._loadingDivBackgroundColor;
  54369. },
  54370. set: function (color) {
  54371. this._loadingDivBackgroundColor = color;
  54372. if (!this._loadingDiv) {
  54373. return;
  54374. }
  54375. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  54376. },
  54377. enumerable: true,
  54378. configurable: true
  54379. });
  54380. return DefaultLoadingScreen;
  54381. }());
  54382. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  54383. })(BABYLON || (BABYLON = {}));
  54384. //# sourceMappingURL=babylon.loadingScreen.js.map
  54385. var BABYLON;
  54386. (function (BABYLON) {
  54387. var SceneLoaderProgressEvent = /** @class */ (function () {
  54388. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  54389. this.lengthComputable = lengthComputable;
  54390. this.loaded = loaded;
  54391. this.total = total;
  54392. }
  54393. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  54394. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  54395. };
  54396. return SceneLoaderProgressEvent;
  54397. }());
  54398. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  54399. var SceneLoader = /** @class */ (function () {
  54400. function SceneLoader() {
  54401. }
  54402. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  54403. get: function () {
  54404. return 0;
  54405. },
  54406. enumerable: true,
  54407. configurable: true
  54408. });
  54409. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  54410. get: function () {
  54411. return 1;
  54412. },
  54413. enumerable: true,
  54414. configurable: true
  54415. });
  54416. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  54417. get: function () {
  54418. return 2;
  54419. },
  54420. enumerable: true,
  54421. configurable: true
  54422. });
  54423. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  54424. get: function () {
  54425. return 3;
  54426. },
  54427. enumerable: true,
  54428. configurable: true
  54429. });
  54430. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  54431. get: function () {
  54432. return SceneLoader._ForceFullSceneLoadingForIncremental;
  54433. },
  54434. set: function (value) {
  54435. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  54436. },
  54437. enumerable: true,
  54438. configurable: true
  54439. });
  54440. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  54441. get: function () {
  54442. return SceneLoader._ShowLoadingScreen;
  54443. },
  54444. set: function (value) {
  54445. SceneLoader._ShowLoadingScreen = value;
  54446. },
  54447. enumerable: true,
  54448. configurable: true
  54449. });
  54450. Object.defineProperty(SceneLoader, "loggingLevel", {
  54451. get: function () {
  54452. return SceneLoader._loggingLevel;
  54453. },
  54454. set: function (value) {
  54455. SceneLoader._loggingLevel = value;
  54456. },
  54457. enumerable: true,
  54458. configurable: true
  54459. });
  54460. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  54461. get: function () {
  54462. return SceneLoader._CleanBoneMatrixWeights;
  54463. },
  54464. set: function (value) {
  54465. SceneLoader._CleanBoneMatrixWeights = value;
  54466. },
  54467. enumerable: true,
  54468. configurable: true
  54469. });
  54470. SceneLoader._getDefaultPlugin = function () {
  54471. return SceneLoader._registeredPlugins[".babylon"];
  54472. };
  54473. SceneLoader._getPluginForExtension = function (extension) {
  54474. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  54475. if (registeredPlugin) {
  54476. return registeredPlugin;
  54477. }
  54478. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  54479. return SceneLoader._getDefaultPlugin();
  54480. };
  54481. SceneLoader._getPluginForDirectLoad = function (data) {
  54482. for (var extension in SceneLoader._registeredPlugins) {
  54483. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  54484. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  54485. return SceneLoader._registeredPlugins[extension];
  54486. }
  54487. }
  54488. return SceneLoader._getDefaultPlugin();
  54489. };
  54490. SceneLoader._getPluginForFilename = function (sceneFilename) {
  54491. if (sceneFilename.name) {
  54492. sceneFilename = sceneFilename.name;
  54493. }
  54494. var queryStringPosition = sceneFilename.indexOf("?");
  54495. if (queryStringPosition !== -1) {
  54496. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  54497. }
  54498. var dotPosition = sceneFilename.lastIndexOf(".");
  54499. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  54500. return SceneLoader._getPluginForExtension(extension);
  54501. };
  54502. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  54503. SceneLoader._getDirectLoad = function (sceneFilename) {
  54504. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  54505. return sceneFilename.substr(5);
  54506. }
  54507. return null;
  54508. };
  54509. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  54510. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  54511. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  54512. var plugin;
  54513. if (registeredPlugin.plugin.createPlugin) {
  54514. plugin = registeredPlugin.plugin.createPlugin();
  54515. }
  54516. else {
  54517. plugin = registeredPlugin.plugin;
  54518. }
  54519. var useArrayBuffer = registeredPlugin.isBinary;
  54520. var database;
  54521. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  54522. var dataCallback = function (data, responseURL) {
  54523. if (scene.isDisposed) {
  54524. onError("Scene has been disposed");
  54525. return;
  54526. }
  54527. scene.database = database;
  54528. onSuccess(plugin, data, responseURL);
  54529. };
  54530. var request = null;
  54531. var pluginDisposed = false;
  54532. var onDisposeObservable = plugin.onDisposeObservable;
  54533. if (onDisposeObservable) {
  54534. onDisposeObservable.add(function () {
  54535. pluginDisposed = true;
  54536. if (request) {
  54537. request.abort();
  54538. request = null;
  54539. }
  54540. onDispose();
  54541. });
  54542. }
  54543. var manifestChecked = function () {
  54544. if (pluginDisposed) {
  54545. return;
  54546. }
  54547. var url = rootUrl + sceneFilename;
  54548. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54549. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54550. } : undefined, database, useArrayBuffer, function (request, exception) {
  54551. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54552. });
  54553. };
  54554. if (directLoad) {
  54555. dataCallback(directLoad);
  54556. return plugin;
  54557. }
  54558. if (rootUrl.indexOf("file:") === -1) {
  54559. if (scene.getEngine().enableOfflineSupport) {
  54560. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54561. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54562. }
  54563. else {
  54564. manifestChecked();
  54565. }
  54566. }
  54567. else {
  54568. var fileOrString = sceneFilename;
  54569. if (fileOrString.name) {
  54570. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54571. }
  54572. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54573. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54574. }
  54575. else {
  54576. onError("Unable to find file named " + sceneFilename);
  54577. }
  54578. }
  54579. return plugin;
  54580. };
  54581. // Public functions
  54582. SceneLoader.GetPluginForExtension = function (extension) {
  54583. return SceneLoader._getPluginForExtension(extension).plugin;
  54584. };
  54585. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54586. return !!SceneLoader._registeredPlugins[extension];
  54587. };
  54588. SceneLoader.RegisterPlugin = function (plugin) {
  54589. if (typeof plugin.extensions === "string") {
  54590. var extension = plugin.extensions;
  54591. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54592. plugin: plugin,
  54593. isBinary: false
  54594. };
  54595. }
  54596. else {
  54597. var extensions = plugin.extensions;
  54598. Object.keys(extensions).forEach(function (extension) {
  54599. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54600. plugin: plugin,
  54601. isBinary: extensions[extension].isBinary
  54602. };
  54603. });
  54604. }
  54605. };
  54606. /**
  54607. * Import meshes into a scene
  54608. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54609. * @param rootUrl a string that defines the root url for scene and resources
  54610. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54611. * @param scene the instance of BABYLON.Scene to append to
  54612. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54613. * @param onProgress a callback with a progress event for each file being loaded
  54614. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54615. */
  54616. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54617. if (onSuccess === void 0) { onSuccess = null; }
  54618. if (onProgress === void 0) { onProgress = null; }
  54619. if (onError === void 0) { onError = null; }
  54620. if (pluginExtension === void 0) { pluginExtension = null; }
  54621. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54622. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54623. return null;
  54624. }
  54625. var loadingToken = {};
  54626. scene._addPendingData(loadingToken);
  54627. var disposeHandler = function () {
  54628. scene._removePendingData(loadingToken);
  54629. };
  54630. var errorHandler = function (message, exception) {
  54631. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54632. if (onError) {
  54633. onError(scene, errorMessage, exception);
  54634. }
  54635. else {
  54636. BABYLON.Tools.Error(errorMessage);
  54637. // should the exception be thrown?
  54638. }
  54639. disposeHandler();
  54640. };
  54641. var progressHandler = onProgress ? function (event) {
  54642. try {
  54643. onProgress(event);
  54644. }
  54645. catch (e) {
  54646. errorHandler("Error in onProgress callback", e);
  54647. }
  54648. } : undefined;
  54649. var successHandler = function (meshes, particleSystems, skeletons) {
  54650. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54651. if (onSuccess) {
  54652. try {
  54653. onSuccess(meshes, particleSystems, skeletons);
  54654. }
  54655. catch (e) {
  54656. errorHandler("Error in onSuccess callback", e);
  54657. }
  54658. }
  54659. scene._removePendingData(loadingToken);
  54660. };
  54661. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54662. if (plugin.rewriteRootURL) {
  54663. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54664. }
  54665. if (plugin.importMesh) {
  54666. var syncedPlugin = plugin;
  54667. var meshes = new Array();
  54668. var particleSystems = new Array();
  54669. var skeletons = new Array();
  54670. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54671. return;
  54672. }
  54673. scene.loadingPluginName = plugin.name;
  54674. successHandler(meshes, particleSystems, skeletons);
  54675. }
  54676. else {
  54677. var asyncedPlugin = plugin;
  54678. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54679. scene.loadingPluginName = plugin.name;
  54680. successHandler(meshes, particleSystems, skeletons);
  54681. }, progressHandler, errorHandler);
  54682. }
  54683. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54684. };
  54685. /**
  54686. * Load a scene
  54687. * @param rootUrl a string that defines the root url for scene and resources
  54688. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54689. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54690. * @param onSuccess a callback with the scene when import succeeds
  54691. * @param onProgress a callback with a progress event for each file being loaded
  54692. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54693. */
  54694. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54695. if (onSuccess === void 0) { onSuccess = null; }
  54696. if (onProgress === void 0) { onProgress = null; }
  54697. if (onError === void 0) { onError = null; }
  54698. if (pluginExtension === void 0) { pluginExtension = null; }
  54699. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54700. };
  54701. /**
  54702. * Append a scene
  54703. * @param rootUrl a string that defines the root url for scene and resources
  54704. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54705. * @param scene is the instance of BABYLON.Scene to append to
  54706. * @param onSuccess a callback with the scene when import succeeds
  54707. * @param onProgress a callback with a progress event for each file being loaded
  54708. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54709. */
  54710. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54711. if (onSuccess === void 0) { onSuccess = null; }
  54712. if (onProgress === void 0) { onProgress = null; }
  54713. if (onError === void 0) { onError = null; }
  54714. if (pluginExtension === void 0) { pluginExtension = null; }
  54715. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54716. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54717. return null;
  54718. }
  54719. if (SceneLoader.ShowLoadingScreen) {
  54720. scene.getEngine().displayLoadingUI();
  54721. }
  54722. var loadingToken = {};
  54723. scene._addPendingData(loadingToken);
  54724. var disposeHandler = function () {
  54725. scene._removePendingData(loadingToken);
  54726. scene.getEngine().hideLoadingUI();
  54727. };
  54728. var errorHandler = function (message, exception) {
  54729. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54730. if (onError) {
  54731. onError(scene, errorMessage, exception);
  54732. }
  54733. else {
  54734. BABYLON.Tools.Error(errorMessage);
  54735. // should the exception be thrown?
  54736. }
  54737. disposeHandler();
  54738. };
  54739. var progressHandler = onProgress ? function (event) {
  54740. try {
  54741. onProgress(event);
  54742. }
  54743. catch (e) {
  54744. errorHandler("Error in onProgress callback", e);
  54745. }
  54746. } : undefined;
  54747. var successHandler = function () {
  54748. if (onSuccess) {
  54749. try {
  54750. onSuccess(scene);
  54751. }
  54752. catch (e) {
  54753. errorHandler("Error in onSuccess callback", e);
  54754. }
  54755. }
  54756. scene._removePendingData(loadingToken);
  54757. };
  54758. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54759. if (plugin.load) {
  54760. var syncedPlugin = plugin;
  54761. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54762. return;
  54763. }
  54764. scene.loadingPluginName = plugin.name;
  54765. successHandler();
  54766. }
  54767. else {
  54768. var asyncedPlugin = plugin;
  54769. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54770. scene.loadingPluginName = plugin.name;
  54771. successHandler();
  54772. }, progressHandler, errorHandler);
  54773. }
  54774. if (SceneLoader.ShowLoadingScreen) {
  54775. scene.executeWhenReady(function () {
  54776. scene.getEngine().hideLoadingUI();
  54777. });
  54778. }
  54779. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54780. };
  54781. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54782. if (onSuccess === void 0) { onSuccess = null; }
  54783. if (onProgress === void 0) { onProgress = null; }
  54784. if (onError === void 0) { onError = null; }
  54785. if (pluginExtension === void 0) { pluginExtension = null; }
  54786. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54787. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54788. return null;
  54789. }
  54790. var loadingToken = {};
  54791. scene._addPendingData(loadingToken);
  54792. var disposeHandler = function () {
  54793. scene._removePendingData(loadingToken);
  54794. };
  54795. var errorHandler = function (message, exception) {
  54796. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54797. if (onError) {
  54798. onError(scene, errorMessage, exception);
  54799. }
  54800. else {
  54801. BABYLON.Tools.Error(errorMessage);
  54802. // should the exception be thrown?
  54803. }
  54804. disposeHandler();
  54805. };
  54806. var progressHandler = onProgress ? function (event) {
  54807. try {
  54808. onProgress(event);
  54809. }
  54810. catch (e) {
  54811. errorHandler("Error in onProgress callback", e);
  54812. }
  54813. } : undefined;
  54814. var successHandler = function (assets) {
  54815. if (onSuccess) {
  54816. try {
  54817. onSuccess(assets);
  54818. }
  54819. catch (e) {
  54820. errorHandler("Error in onSuccess callback", e);
  54821. }
  54822. }
  54823. scene._removePendingData(loadingToken);
  54824. };
  54825. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54826. if (plugin.loadAssets) {
  54827. var syncedPlugin = plugin;
  54828. var assetContainer = syncedPlugin.loadAssets(scene, data, rootUrl, errorHandler);
  54829. if (!assetContainer) {
  54830. return;
  54831. }
  54832. scene.loadingPluginName = plugin.name;
  54833. successHandler(assetContainer);
  54834. }
  54835. else if (plugin.loadAssetsAsync) {
  54836. var asyncedPlugin = plugin;
  54837. asyncedPlugin.loadAssetsAsync(scene, data, rootUrl, function (assetContainer) {
  54838. if (assetContainer) {
  54839. scene.loadingPluginName = plugin.name;
  54840. successHandler(assetContainer);
  54841. }
  54842. }, progressHandler, errorHandler);
  54843. }
  54844. else {
  54845. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssets or loadAssetsAsync method.");
  54846. }
  54847. if (SceneLoader.ShowLoadingScreen) {
  54848. scene.executeWhenReady(function () {
  54849. scene.getEngine().hideLoadingUI();
  54850. });
  54851. }
  54852. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54853. };
  54854. // Flags
  54855. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  54856. SceneLoader._ShowLoadingScreen = true;
  54857. SceneLoader._CleanBoneMatrixWeights = false;
  54858. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  54859. // Members
  54860. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  54861. SceneLoader._registeredPlugins = {};
  54862. return SceneLoader;
  54863. }());
  54864. BABYLON.SceneLoader = SceneLoader;
  54865. ;
  54866. })(BABYLON || (BABYLON = {}));
  54867. //# sourceMappingURL=babylon.sceneLoader.js.map
  54868. var BABYLON;
  54869. (function (BABYLON) {
  54870. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  54871. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54872. var parsedMaterial = parsedData.materials[index];
  54873. if (parsedMaterial.id === id) {
  54874. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54875. }
  54876. }
  54877. return null;
  54878. };
  54879. var isDescendantOf = function (mesh, names, hierarchyIds) {
  54880. for (var i in names) {
  54881. if (mesh.name === names[i]) {
  54882. hierarchyIds.push(mesh.id);
  54883. return true;
  54884. }
  54885. }
  54886. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  54887. hierarchyIds.push(mesh.id);
  54888. return true;
  54889. }
  54890. return false;
  54891. };
  54892. var logOperation = function (operation, producer) {
  54893. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  54894. };
  54895. var loadAssets = function (scene, data, rootUrl, onError, addToScene) {
  54896. if (addToScene === void 0) { addToScene = false; }
  54897. var container = new BABYLON.AssetContainer(scene);
  54898. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54899. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54900. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54901. // and avoid problems with multiple concurrent .babylon loads.
  54902. var log = "importScene has failed JSON parse";
  54903. try {
  54904. var parsedData = JSON.parse(data);
  54905. log = "";
  54906. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54907. var index;
  54908. var cache;
  54909. // Lights
  54910. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54911. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54912. var parsedLight = parsedData.lights[index];
  54913. var light = BABYLON.Light.Parse(parsedLight, scene);
  54914. if (light) {
  54915. container.lights.push(light);
  54916. log += (index === 0 ? "\n\tLights:" : "");
  54917. log += "\n\t\t" + light.toString(fullDetails);
  54918. }
  54919. }
  54920. }
  54921. // Animations
  54922. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54923. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54924. var parsedAnimation = parsedData.animations[index];
  54925. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54926. scene.animations.push(animation);
  54927. container.animations.push(animation);
  54928. log += (index === 0 ? "\n\tAnimations:" : "");
  54929. log += "\n\t\t" + animation.toString(fullDetails);
  54930. }
  54931. }
  54932. // Materials
  54933. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54934. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54935. var parsedMaterial = parsedData.materials[index];
  54936. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54937. container.materials.push(mat);
  54938. log += (index === 0 ? "\n\tMaterials:" : "");
  54939. log += "\n\t\t" + mat.toString(fullDetails);
  54940. }
  54941. }
  54942. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54943. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54944. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54945. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54946. container.multiMaterials.push(mmat);
  54947. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54948. log += "\n\t\t" + mmat.toString(fullDetails);
  54949. }
  54950. }
  54951. // Morph targets
  54952. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54953. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54954. var managerData = _a[_i];
  54955. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  54956. }
  54957. }
  54958. // Skeletons
  54959. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54960. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54961. var parsedSkeleton = parsedData.skeletons[index];
  54962. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54963. container.skeletons.push(skeleton);
  54964. log += (index === 0 ? "\n\tSkeletons:" : "");
  54965. log += "\n\t\t" + skeleton.toString(fullDetails);
  54966. }
  54967. }
  54968. // Geometries
  54969. var geometries = parsedData.geometries;
  54970. if (geometries !== undefined && geometries !== null) {
  54971. var addedGeometry = new Array();
  54972. // Boxes
  54973. var boxes = geometries.boxes;
  54974. if (boxes !== undefined && boxes !== null) {
  54975. for (index = 0, cache = boxes.length; index < cache; index++) {
  54976. var parsedBox = boxes[index];
  54977. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  54978. }
  54979. }
  54980. // Spheres
  54981. var spheres = geometries.spheres;
  54982. if (spheres !== undefined && spheres !== null) {
  54983. for (index = 0, cache = spheres.length; index < cache; index++) {
  54984. var parsedSphere = spheres[index];
  54985. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  54986. }
  54987. }
  54988. // Cylinders
  54989. var cylinders = geometries.cylinders;
  54990. if (cylinders !== undefined && cylinders !== null) {
  54991. for (index = 0, cache = cylinders.length; index < cache; index++) {
  54992. var parsedCylinder = cylinders[index];
  54993. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  54994. }
  54995. }
  54996. // Toruses
  54997. var toruses = geometries.toruses;
  54998. if (toruses !== undefined && toruses !== null) {
  54999. for (index = 0, cache = toruses.length; index < cache; index++) {
  55000. var parsedTorus = toruses[index];
  55001. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  55002. }
  55003. }
  55004. // Grounds
  55005. var grounds = geometries.grounds;
  55006. if (grounds !== undefined && grounds !== null) {
  55007. for (index = 0, cache = grounds.length; index < cache; index++) {
  55008. var parsedGround = grounds[index];
  55009. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  55010. }
  55011. }
  55012. // Planes
  55013. var planes = geometries.planes;
  55014. if (planes !== undefined && planes !== null) {
  55015. for (index = 0, cache = planes.length; index < cache; index++) {
  55016. var parsedPlane = planes[index];
  55017. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  55018. }
  55019. }
  55020. // TorusKnots
  55021. var torusKnots = geometries.torusKnots;
  55022. if (torusKnots !== undefined && torusKnots !== null) {
  55023. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  55024. var parsedTorusKnot = torusKnots[index];
  55025. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  55026. }
  55027. }
  55028. // VertexData
  55029. var vertexData = geometries.vertexData;
  55030. if (vertexData !== undefined && vertexData !== null) {
  55031. for (index = 0, cache = vertexData.length; index < cache; index++) {
  55032. var parsedVertexData = vertexData[index];
  55033. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  55034. }
  55035. }
  55036. addedGeometry.forEach(function (g) {
  55037. if (g) {
  55038. container.geometries.push(g);
  55039. }
  55040. });
  55041. }
  55042. // Transform nodes
  55043. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  55044. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  55045. var parsedTransformNode = parsedData.transformNodes[index];
  55046. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  55047. container.transformNodes.push(node);
  55048. }
  55049. }
  55050. // Meshes
  55051. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55052. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55053. var parsedMesh = parsedData.meshes[index];
  55054. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55055. container.meshes.push(mesh);
  55056. log += (index === 0 ? "\n\tMeshes:" : "");
  55057. log += "\n\t\t" + mesh.toString(fullDetails);
  55058. }
  55059. }
  55060. // Cameras
  55061. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  55062. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  55063. var parsedCamera = parsedData.cameras[index];
  55064. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  55065. container.cameras.push(camera);
  55066. log += (index === 0 ? "\n\tCameras:" : "");
  55067. log += "\n\t\t" + camera.toString(fullDetails);
  55068. }
  55069. }
  55070. // Browsing all the graph to connect the dots
  55071. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  55072. var camera = scene.cameras[index];
  55073. if (camera._waitingParentId) {
  55074. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  55075. camera._waitingParentId = null;
  55076. }
  55077. }
  55078. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55079. var light_1 = scene.lights[index];
  55080. if (light_1 && light_1._waitingParentId) {
  55081. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  55082. light_1._waitingParentId = null;
  55083. }
  55084. }
  55085. // Sounds
  55086. // TODO: add sound
  55087. var loadedSounds = [];
  55088. var loadedSound;
  55089. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  55090. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  55091. var parsedSound = parsedData.sounds[index];
  55092. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55093. if (!parsedSound.url)
  55094. parsedSound.url = parsedSound.name;
  55095. if (!loadedSounds[parsedSound.url]) {
  55096. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  55097. loadedSounds[parsedSound.url] = loadedSound;
  55098. container.sounds.push(loadedSound);
  55099. }
  55100. else {
  55101. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  55102. }
  55103. }
  55104. else {
  55105. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  55106. }
  55107. }
  55108. }
  55109. loadedSounds = [];
  55110. // Connect parents & children and parse actions
  55111. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  55112. var transformNode = scene.transformNodes[index];
  55113. if (transformNode._waitingParentId) {
  55114. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  55115. transformNode._waitingParentId = null;
  55116. }
  55117. }
  55118. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55119. var mesh = scene.meshes[index];
  55120. if (mesh._waitingParentId) {
  55121. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  55122. mesh._waitingParentId = null;
  55123. }
  55124. if (mesh._waitingActions) {
  55125. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  55126. mesh._waitingActions = null;
  55127. }
  55128. }
  55129. // freeze world matrix application
  55130. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55131. var currentMesh = scene.meshes[index];
  55132. if (currentMesh._waitingFreezeWorldMatrix) {
  55133. currentMesh.freezeWorldMatrix();
  55134. currentMesh._waitingFreezeWorldMatrix = null;
  55135. }
  55136. else {
  55137. currentMesh.computeWorldMatrix(true);
  55138. }
  55139. }
  55140. // Particles Systems
  55141. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55142. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55143. var parsedParticleSystem = parsedData.particleSystems[index];
  55144. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  55145. container.particleSystems.push(ps);
  55146. }
  55147. }
  55148. // Lens flares
  55149. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  55150. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  55151. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  55152. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  55153. container.lensFlareSystems.push(lf);
  55154. }
  55155. }
  55156. // Shadows
  55157. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  55158. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  55159. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  55160. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  55161. container.shadowGenerators.push(sg);
  55162. }
  55163. }
  55164. // Lights exclusions / inclusions
  55165. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  55166. var light_2 = scene.lights[index];
  55167. // Excluded check
  55168. if (light_2._excludedMeshesIds.length > 0) {
  55169. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  55170. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  55171. if (excludedMesh) {
  55172. light_2.excludedMeshes.push(excludedMesh);
  55173. }
  55174. }
  55175. light_2._excludedMeshesIds = [];
  55176. }
  55177. // Included check
  55178. if (light_2._includedOnlyMeshesIds.length > 0) {
  55179. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  55180. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  55181. if (includedOnlyMesh) {
  55182. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  55183. }
  55184. }
  55185. light_2._includedOnlyMeshesIds = [];
  55186. }
  55187. }
  55188. // Actions (scene)
  55189. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  55190. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  55191. }
  55192. if (!addToScene) {
  55193. container.removeAllFromScene();
  55194. }
  55195. return container;
  55196. }
  55197. catch (err) {
  55198. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  55199. if (onError) {
  55200. onError(msg, err);
  55201. }
  55202. else {
  55203. BABYLON.Tools.Log(msg);
  55204. throw err;
  55205. }
  55206. }
  55207. finally {
  55208. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55209. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55210. }
  55211. }
  55212. return null;
  55213. };
  55214. BABYLON.SceneLoader.RegisterPlugin({
  55215. name: "babylon.js",
  55216. extensions: ".babylon",
  55217. canDirectLoad: function (data) {
  55218. if (data.indexOf("babylon") !== -1) {
  55219. return true;
  55220. }
  55221. return false;
  55222. },
  55223. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  55224. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55225. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55226. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55227. // and avoid problems with multiple concurrent .babylon loads.
  55228. var log = "importMesh has failed JSON parse";
  55229. try {
  55230. var parsedData = JSON.parse(data);
  55231. log = "";
  55232. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  55233. if (!meshesNames) {
  55234. meshesNames = null;
  55235. }
  55236. else if (!Array.isArray(meshesNames)) {
  55237. meshesNames = [meshesNames];
  55238. }
  55239. var hierarchyIds = new Array();
  55240. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  55241. var loadedSkeletonsIds = [];
  55242. var loadedMaterialsIds = [];
  55243. var index;
  55244. var cache;
  55245. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  55246. var parsedMesh = parsedData.meshes[index];
  55247. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  55248. if (meshesNames !== null) {
  55249. // Remove found mesh name from list.
  55250. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  55251. }
  55252. //Geometry?
  55253. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  55254. //does the file contain geometries?
  55255. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  55256. //find the correct geometry and add it to the scene
  55257. var found = false;
  55258. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  55259. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  55260. return;
  55261. }
  55262. else {
  55263. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  55264. if (parsedGeometryData.id === parsedMesh.geometryId) {
  55265. switch (geometryType) {
  55266. case "boxes":
  55267. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  55268. break;
  55269. case "spheres":
  55270. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  55271. break;
  55272. case "cylinders":
  55273. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  55274. break;
  55275. case "toruses":
  55276. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  55277. break;
  55278. case "grounds":
  55279. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  55280. break;
  55281. case "planes":
  55282. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  55283. break;
  55284. case "torusKnots":
  55285. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  55286. break;
  55287. case "vertexData":
  55288. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  55289. break;
  55290. }
  55291. found = true;
  55292. }
  55293. });
  55294. }
  55295. });
  55296. if (found === false) {
  55297. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  55298. }
  55299. }
  55300. }
  55301. // Material ?
  55302. if (parsedMesh.materialId) {
  55303. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  55304. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  55305. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  55306. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  55307. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  55308. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  55309. var subMatId = parsedMultiMaterial.materials[matIndex];
  55310. loadedMaterialsIds.push(subMatId);
  55311. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  55312. log += "\n\tMaterial " + mat.toString(fullDetails);
  55313. }
  55314. loadedMaterialsIds.push(parsedMultiMaterial.id);
  55315. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  55316. materialFound = true;
  55317. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  55318. break;
  55319. }
  55320. }
  55321. }
  55322. if (materialFound === false) {
  55323. loadedMaterialsIds.push(parsedMesh.materialId);
  55324. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  55325. if (!mat) {
  55326. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  55327. }
  55328. else {
  55329. log += "\n\tMaterial " + mat.toString(fullDetails);
  55330. }
  55331. }
  55332. }
  55333. // Skeleton ?
  55334. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  55335. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  55336. if (skeletonAlreadyLoaded === false) {
  55337. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  55338. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  55339. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  55340. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  55341. skeletons.push(skeleton);
  55342. loadedSkeletonsIds.push(parsedSkeleton.id);
  55343. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  55344. }
  55345. }
  55346. }
  55347. }
  55348. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  55349. meshes.push(mesh);
  55350. log += "\n\tMesh " + mesh.toString(fullDetails);
  55351. }
  55352. }
  55353. // Connecting parents
  55354. var currentMesh;
  55355. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55356. currentMesh = scene.meshes[index];
  55357. if (currentMesh._waitingParentId) {
  55358. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  55359. currentMesh._waitingParentId = null;
  55360. }
  55361. }
  55362. // freeze and compute world matrix application
  55363. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  55364. currentMesh = scene.meshes[index];
  55365. if (currentMesh._waitingFreezeWorldMatrix) {
  55366. currentMesh.freezeWorldMatrix();
  55367. currentMesh._waitingFreezeWorldMatrix = null;
  55368. }
  55369. else {
  55370. currentMesh.computeWorldMatrix(true);
  55371. }
  55372. }
  55373. }
  55374. // Particles
  55375. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  55376. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  55377. var parsedParticleSystem = parsedData.particleSystems[index];
  55378. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  55379. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  55380. }
  55381. }
  55382. }
  55383. return true;
  55384. }
  55385. catch (err) {
  55386. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  55387. if (onError) {
  55388. onError(msg, err);
  55389. }
  55390. else {
  55391. BABYLON.Tools.Log(msg);
  55392. throw err;
  55393. }
  55394. }
  55395. finally {
  55396. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55397. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55398. }
  55399. }
  55400. return false;
  55401. },
  55402. load: function (scene, data, rootUrl, onError) {
  55403. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  55404. // when SceneLoader.debugLogging = true (default), or exception encountered.
  55405. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  55406. // and avoid problems with multiple concurrent .babylon loads.
  55407. var log = "importScene has failed JSON parse";
  55408. try {
  55409. var parsedData = JSON.parse(data);
  55410. log = "";
  55411. // Scene
  55412. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  55413. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  55414. }
  55415. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  55416. scene.autoClear = parsedData.autoClear;
  55417. }
  55418. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  55419. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  55420. }
  55421. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  55422. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  55423. }
  55424. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  55425. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  55426. }
  55427. // Fog
  55428. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  55429. scene.fogMode = parsedData.fogMode;
  55430. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  55431. scene.fogStart = parsedData.fogStart;
  55432. scene.fogEnd = parsedData.fogEnd;
  55433. scene.fogDensity = parsedData.fogDensity;
  55434. log += "\tFog mode for scene: ";
  55435. switch (scene.fogMode) {
  55436. // getters not compiling, so using hardcoded
  55437. case 1:
  55438. log += "exp\n";
  55439. break;
  55440. case 2:
  55441. log += "exp2\n";
  55442. break;
  55443. case 3:
  55444. log += "linear\n";
  55445. break;
  55446. }
  55447. }
  55448. //Physics
  55449. if (parsedData.physicsEnabled) {
  55450. var physicsPlugin;
  55451. if (parsedData.physicsEngine === "cannon") {
  55452. physicsPlugin = new BABYLON.CannonJSPlugin();
  55453. }
  55454. else if (parsedData.physicsEngine === "oimo") {
  55455. physicsPlugin = new BABYLON.OimoJSPlugin();
  55456. }
  55457. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  55458. //else - default engine, which is currently oimo
  55459. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  55460. scene.enablePhysics(physicsGravity, physicsPlugin);
  55461. }
  55462. // Metadata
  55463. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  55464. scene.metadata = parsedData.metadata;
  55465. }
  55466. //collisions, if defined. otherwise, default is true
  55467. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  55468. scene.collisionsEnabled = parsedData.collisionsEnabled;
  55469. }
  55470. scene.workerCollisions = !!parsedData.workerCollisions;
  55471. var container = loadAssets(scene, data, rootUrl, onerror, true);
  55472. if (!container) {
  55473. return false;
  55474. }
  55475. if (parsedData.autoAnimate) {
  55476. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  55477. }
  55478. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  55479. scene.setActiveCameraByID(parsedData.activeCameraID);
  55480. }
  55481. // Environment texture
  55482. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  55483. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  55484. if (parsedData.createDefaultSkybox === true) {
  55485. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  55486. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  55487. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  55488. }
  55489. }
  55490. // Finish
  55491. return true;
  55492. }
  55493. catch (err) {
  55494. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  55495. if (onError) {
  55496. onError(msg, err);
  55497. }
  55498. else {
  55499. BABYLON.Tools.Log(msg);
  55500. throw err;
  55501. }
  55502. }
  55503. finally {
  55504. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  55505. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  55506. }
  55507. }
  55508. return false;
  55509. },
  55510. loadAssets: function (scene, data, rootUrl, onError) {
  55511. var container = loadAssets(scene, data, rootUrl, onerror);
  55512. return container;
  55513. }
  55514. });
  55515. })(BABYLON || (BABYLON = {}));
  55516. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  55517. var BABYLON;
  55518. (function (BABYLON) {
  55519. var FilesInput = /** @class */ (function () {
  55520. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  55521. this.onProcessFileCallback = function () { return true; };
  55522. this._engine = engine;
  55523. this._currentScene = scene;
  55524. this._sceneLoadedCallback = sceneLoadedCallback;
  55525. this._progressCallback = progressCallback;
  55526. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  55527. this._textureLoadingCallback = textureLoadingCallback;
  55528. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  55529. this._onReloadCallback = onReloadCallback;
  55530. this._errorCallback = errorCallback;
  55531. }
  55532. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  55533. var _this = this;
  55534. if (elementToMonitor) {
  55535. this._elementToMonitor = elementToMonitor;
  55536. this._dragEnterHandler = function (e) { _this.drag(e); };
  55537. this._dragOverHandler = function (e) { _this.drag(e); };
  55538. this._dropHandler = function (e) { _this.drop(e); };
  55539. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  55540. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  55541. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  55542. }
  55543. };
  55544. FilesInput.prototype.dispose = function () {
  55545. if (!this._elementToMonitor) {
  55546. return;
  55547. }
  55548. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  55549. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  55550. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  55551. };
  55552. FilesInput.prototype.renderFunction = function () {
  55553. if (this._additionalRenderLoopLogicCallback) {
  55554. this._additionalRenderLoopLogicCallback();
  55555. }
  55556. if (this._currentScene) {
  55557. if (this._textureLoadingCallback) {
  55558. var remaining = this._currentScene.getWaitingItemsCount();
  55559. if (remaining > 0) {
  55560. this._textureLoadingCallback(remaining);
  55561. }
  55562. }
  55563. this._currentScene.render();
  55564. }
  55565. };
  55566. FilesInput.prototype.drag = function (e) {
  55567. e.stopPropagation();
  55568. e.preventDefault();
  55569. };
  55570. FilesInput.prototype.drop = function (eventDrop) {
  55571. eventDrop.stopPropagation();
  55572. eventDrop.preventDefault();
  55573. this.loadFiles(eventDrop);
  55574. };
  55575. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  55576. var _this = this;
  55577. var reader = folder.createReader();
  55578. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  55579. reader.readEntries(function (entries) {
  55580. remaining.count += entries.length;
  55581. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  55582. var entry = entries_1[_i];
  55583. if (entry.isFile) {
  55584. entry.file(function (file) {
  55585. file.correctName = relativePath + file.name;
  55586. files.push(file);
  55587. if (--remaining.count === 0) {
  55588. callback();
  55589. }
  55590. });
  55591. }
  55592. else if (entry.isDirectory) {
  55593. _this._traverseFolder(entry, files, remaining, callback);
  55594. }
  55595. }
  55596. if (--remaining.count) {
  55597. callback();
  55598. }
  55599. });
  55600. };
  55601. FilesInput.prototype._processFiles = function (files) {
  55602. for (var i = 0; i < files.length; i++) {
  55603. var name = files[i].correctName.toLowerCase();
  55604. var extension = name.split('.').pop();
  55605. if (!this.onProcessFileCallback(files[i], name, extension)) {
  55606. continue;
  55607. }
  55608. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  55609. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  55610. this._sceneFileToLoad = files[i];
  55611. }
  55612. else {
  55613. FilesInput.FilesToLoad[name] = files[i];
  55614. }
  55615. }
  55616. };
  55617. FilesInput.prototype.loadFiles = function (event) {
  55618. var _this = this;
  55619. if (this._startingProcessingFilesCallback)
  55620. this._startingProcessingFilesCallback();
  55621. // Handling data transfer via drag'n'drop
  55622. if (event && event.dataTransfer && event.dataTransfer.files) {
  55623. this._filesToLoad = event.dataTransfer.files;
  55624. }
  55625. // Handling files from input files
  55626. if (event && event.target && event.target.files) {
  55627. this._filesToLoad = event.target.files;
  55628. }
  55629. if (this._filesToLoad && this._filesToLoad.length > 0) {
  55630. var files_1 = new Array();
  55631. var folders = [];
  55632. var items = event.dataTransfer ? event.dataTransfer.items : null;
  55633. for (var i = 0; i < this._filesToLoad.length; i++) {
  55634. var fileToLoad = this._filesToLoad[i];
  55635. var name_1 = fileToLoad.name.toLowerCase();
  55636. var entry = void 0;
  55637. fileToLoad.correctName = name_1;
  55638. if (items) {
  55639. var item = items[i];
  55640. if (item.getAsEntry) {
  55641. entry = item.getAsEntry();
  55642. }
  55643. else if (item.webkitGetAsEntry) {
  55644. entry = item.webkitGetAsEntry();
  55645. }
  55646. }
  55647. if (!entry) {
  55648. files_1.push(fileToLoad);
  55649. }
  55650. else {
  55651. if (entry.isDirectory) {
  55652. folders.push(entry);
  55653. }
  55654. else {
  55655. files_1.push(fileToLoad);
  55656. }
  55657. }
  55658. }
  55659. if (folders.length === 0) {
  55660. this._processFiles(files_1);
  55661. this._processReload();
  55662. }
  55663. else {
  55664. var remaining = { count: folders.length };
  55665. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55666. var folder = folders_1[_i];
  55667. this._traverseFolder(folder, files_1, remaining, function () {
  55668. _this._processFiles(files_1);
  55669. if (remaining.count === 0) {
  55670. _this._processReload();
  55671. }
  55672. });
  55673. }
  55674. }
  55675. }
  55676. };
  55677. FilesInput.prototype._processReload = function () {
  55678. if (this._onReloadCallback) {
  55679. this._onReloadCallback(this._sceneFileToLoad);
  55680. }
  55681. else {
  55682. this.reload();
  55683. }
  55684. };
  55685. FilesInput.prototype.reload = function () {
  55686. var _this = this;
  55687. // If a scene file has been provided
  55688. if (this._sceneFileToLoad) {
  55689. if (this._currentScene) {
  55690. if (BABYLON.Tools.errorsCount > 0) {
  55691. BABYLON.Tools.ClearLogCache();
  55692. }
  55693. this._engine.stopRenderLoop();
  55694. this._currentScene.dispose();
  55695. }
  55696. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55697. _this._currentScene = newScene;
  55698. if (_this._sceneLoadedCallback) {
  55699. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55700. }
  55701. // Wait for textures and shaders to be ready
  55702. _this._currentScene.executeWhenReady(function () {
  55703. _this._engine.runRenderLoop(function () {
  55704. _this.renderFunction();
  55705. });
  55706. });
  55707. }, function (progress) {
  55708. if (_this._progressCallback) {
  55709. _this._progressCallback(progress);
  55710. }
  55711. }, function (scene, message) {
  55712. _this._currentScene = scene;
  55713. if (_this._errorCallback) {
  55714. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55715. }
  55716. });
  55717. }
  55718. else {
  55719. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55720. }
  55721. };
  55722. FilesInput.FilesToLoad = {};
  55723. return FilesInput;
  55724. }());
  55725. BABYLON.FilesInput = FilesInput;
  55726. })(BABYLON || (BABYLON = {}));
  55727. //# sourceMappingURL=babylon.filesInput.js.map
  55728. var BABYLON;
  55729. (function (BABYLON) {
  55730. /**
  55731. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55732. * The underlying implementation relies on an associative array to ensure the best performances.
  55733. * The value can be anything including 'null' but except 'undefined'
  55734. */
  55735. var StringDictionary = /** @class */ (function () {
  55736. function StringDictionary() {
  55737. this._count = 0;
  55738. this._data = {};
  55739. }
  55740. /**
  55741. * This will clear this dictionary and copy the content from the 'source' one.
  55742. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55743. * @param source the dictionary to take the content from and copy to this dictionary
  55744. */
  55745. StringDictionary.prototype.copyFrom = function (source) {
  55746. var _this = this;
  55747. this.clear();
  55748. source.forEach(function (t, v) { return _this.add(t, v); });
  55749. };
  55750. /**
  55751. * Get a value based from its key
  55752. * @param key the given key to get the matching value from
  55753. * @return the value if found, otherwise undefined is returned
  55754. */
  55755. StringDictionary.prototype.get = function (key) {
  55756. var val = this._data[key];
  55757. if (val !== undefined) {
  55758. return val;
  55759. }
  55760. return undefined;
  55761. };
  55762. /**
  55763. * Get a value from its key or add it if it doesn't exist.
  55764. * This method will ensure you that a given key/data will be present in the dictionary.
  55765. * @param key the given key to get the matching value from
  55766. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55767. * The factory will only be invoked if there's no data for the given key.
  55768. * @return the value corresponding to the key.
  55769. */
  55770. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55771. var val = this.get(key);
  55772. if (val !== undefined) {
  55773. return val;
  55774. }
  55775. val = factory(key);
  55776. if (val) {
  55777. this.add(key, val);
  55778. }
  55779. return val;
  55780. };
  55781. /**
  55782. * Get a value from its key if present in the dictionary otherwise add it
  55783. * @param key the key to get the value from
  55784. * @param val if there's no such key/value pair in the dictionary add it with this value
  55785. * @return the value corresponding to the key
  55786. */
  55787. StringDictionary.prototype.getOrAdd = function (key, val) {
  55788. var curVal = this.get(key);
  55789. if (curVal !== undefined) {
  55790. return curVal;
  55791. }
  55792. this.add(key, val);
  55793. return val;
  55794. };
  55795. /**
  55796. * Check if there's a given key in the dictionary
  55797. * @param key the key to check for
  55798. * @return true if the key is present, false otherwise
  55799. */
  55800. StringDictionary.prototype.contains = function (key) {
  55801. return this._data[key] !== undefined;
  55802. };
  55803. /**
  55804. * Add a new key and its corresponding value
  55805. * @param key the key to add
  55806. * @param value the value corresponding to the key
  55807. * @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
  55808. */
  55809. StringDictionary.prototype.add = function (key, value) {
  55810. if (this._data[key] !== undefined) {
  55811. return false;
  55812. }
  55813. this._data[key] = value;
  55814. ++this._count;
  55815. return true;
  55816. };
  55817. StringDictionary.prototype.set = function (key, value) {
  55818. if (this._data[key] === undefined) {
  55819. return false;
  55820. }
  55821. this._data[key] = value;
  55822. return true;
  55823. };
  55824. /**
  55825. * Get the element of the given key and remove it from the dictionary
  55826. * @param key
  55827. */
  55828. StringDictionary.prototype.getAndRemove = function (key) {
  55829. var val = this.get(key);
  55830. if (val !== undefined) {
  55831. delete this._data[key];
  55832. --this._count;
  55833. return val;
  55834. }
  55835. return null;
  55836. };
  55837. /**
  55838. * Remove a key/value from the dictionary.
  55839. * @param key the key to remove
  55840. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  55841. */
  55842. StringDictionary.prototype.remove = function (key) {
  55843. if (this.contains(key)) {
  55844. delete this._data[key];
  55845. --this._count;
  55846. return true;
  55847. }
  55848. return false;
  55849. };
  55850. /**
  55851. * Clear the whole content of the dictionary
  55852. */
  55853. StringDictionary.prototype.clear = function () {
  55854. this._data = {};
  55855. this._count = 0;
  55856. };
  55857. Object.defineProperty(StringDictionary.prototype, "count", {
  55858. get: function () {
  55859. return this._count;
  55860. },
  55861. enumerable: true,
  55862. configurable: true
  55863. });
  55864. /**
  55865. * Execute a callback on each key/val of the dictionary.
  55866. * Note that you can remove any element in this dictionary in the callback implementation
  55867. * @param callback the callback to execute on a given key/value pair
  55868. */
  55869. StringDictionary.prototype.forEach = function (callback) {
  55870. for (var cur in this._data) {
  55871. var val = this._data[cur];
  55872. callback(cur, val);
  55873. }
  55874. };
  55875. /**
  55876. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  55877. * If the callback returns null or undefined the method will iterate to the next key/value pair
  55878. * Note that you can remove any element in this dictionary in the callback implementation
  55879. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  55880. */
  55881. StringDictionary.prototype.first = function (callback) {
  55882. for (var cur in this._data) {
  55883. var val = this._data[cur];
  55884. var res = callback(cur, val);
  55885. if (res) {
  55886. return res;
  55887. }
  55888. }
  55889. return null;
  55890. };
  55891. return StringDictionary;
  55892. }());
  55893. BABYLON.StringDictionary = StringDictionary;
  55894. })(BABYLON || (BABYLON = {}));
  55895. //# sourceMappingURL=babylon.stringDictionary.js.map
  55896. var BABYLON;
  55897. (function (BABYLON) {
  55898. var Tags = /** @class */ (function () {
  55899. function Tags() {
  55900. }
  55901. Tags.EnableFor = function (obj) {
  55902. obj._tags = obj._tags || {};
  55903. obj.hasTags = function () {
  55904. return Tags.HasTags(obj);
  55905. };
  55906. obj.addTags = function (tagsString) {
  55907. return Tags.AddTagsTo(obj, tagsString);
  55908. };
  55909. obj.removeTags = function (tagsString) {
  55910. return Tags.RemoveTagsFrom(obj, tagsString);
  55911. };
  55912. obj.matchesTagsQuery = function (tagsQuery) {
  55913. return Tags.MatchesQuery(obj, tagsQuery);
  55914. };
  55915. };
  55916. Tags.DisableFor = function (obj) {
  55917. delete obj._tags;
  55918. delete obj.hasTags;
  55919. delete obj.addTags;
  55920. delete obj.removeTags;
  55921. delete obj.matchesTagsQuery;
  55922. };
  55923. Tags.HasTags = function (obj) {
  55924. if (!obj._tags) {
  55925. return false;
  55926. }
  55927. return !BABYLON.Tools.IsEmpty(obj._tags);
  55928. };
  55929. Tags.GetTags = function (obj, asString) {
  55930. if (asString === void 0) { asString = true; }
  55931. if (!obj._tags) {
  55932. return null;
  55933. }
  55934. if (asString) {
  55935. var tagsArray = [];
  55936. for (var tag in obj._tags) {
  55937. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  55938. tagsArray.push(tag);
  55939. }
  55940. }
  55941. return tagsArray.join(" ");
  55942. }
  55943. else {
  55944. return obj._tags;
  55945. }
  55946. };
  55947. // the tags 'true' and 'false' are reserved and cannot be used as tags
  55948. // a tag cannot start with '||', '&&', and '!'
  55949. // it cannot contain whitespaces
  55950. Tags.AddTagsTo = function (obj, tagsString) {
  55951. if (!tagsString) {
  55952. return;
  55953. }
  55954. if (typeof tagsString !== "string") {
  55955. return;
  55956. }
  55957. var tags = tagsString.split(" ");
  55958. tags.forEach(function (tag, index, array) {
  55959. Tags._AddTagTo(obj, tag);
  55960. });
  55961. };
  55962. Tags._AddTagTo = function (obj, tag) {
  55963. tag = tag.trim();
  55964. if (tag === "" || tag === "true" || tag === "false") {
  55965. return;
  55966. }
  55967. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  55968. return;
  55969. }
  55970. Tags.EnableFor(obj);
  55971. obj._tags[tag] = true;
  55972. };
  55973. Tags.RemoveTagsFrom = function (obj, tagsString) {
  55974. if (!Tags.HasTags(obj)) {
  55975. return;
  55976. }
  55977. var tags = tagsString.split(" ");
  55978. for (var t in tags) {
  55979. Tags._RemoveTagFrom(obj, tags[t]);
  55980. }
  55981. };
  55982. Tags._RemoveTagFrom = function (obj, tag) {
  55983. delete obj._tags[tag];
  55984. };
  55985. Tags.MatchesQuery = function (obj, tagsQuery) {
  55986. if (tagsQuery === undefined) {
  55987. return true;
  55988. }
  55989. if (tagsQuery === "") {
  55990. return Tags.HasTags(obj);
  55991. }
  55992. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  55993. };
  55994. return Tags;
  55995. }());
  55996. BABYLON.Tags = Tags;
  55997. })(BABYLON || (BABYLON = {}));
  55998. //# sourceMappingURL=babylon.tags.js.map
  55999. var BABYLON;
  56000. (function (BABYLON) {
  56001. var AndOrNotEvaluator = /** @class */ (function () {
  56002. function AndOrNotEvaluator() {
  56003. }
  56004. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  56005. if (!query.match(/\([^\(\)]*\)/g)) {
  56006. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  56007. }
  56008. else {
  56009. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  56010. // remove parenthesis
  56011. r = r.slice(1, r.length - 1);
  56012. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  56013. });
  56014. }
  56015. if (query === "true") {
  56016. return true;
  56017. }
  56018. if (query === "false") {
  56019. return false;
  56020. }
  56021. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  56022. };
  56023. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  56024. evaluateCallback = evaluateCallback || (function (r) {
  56025. return r === "true" ? true : false;
  56026. });
  56027. var result;
  56028. var or = parenthesisContent.split("||");
  56029. for (var i in or) {
  56030. if (or.hasOwnProperty(i)) {
  56031. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  56032. var and = ori.split("&&");
  56033. if (and.length > 1) {
  56034. for (var j = 0; j < and.length; ++j) {
  56035. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  56036. if (andj !== "true" && andj !== "false") {
  56037. if (andj[0] === "!") {
  56038. result = !evaluateCallback(andj.substring(1));
  56039. }
  56040. else {
  56041. result = evaluateCallback(andj);
  56042. }
  56043. }
  56044. else {
  56045. result = andj === "true" ? true : false;
  56046. }
  56047. if (!result) {
  56048. ori = "false";
  56049. break;
  56050. }
  56051. }
  56052. }
  56053. if (result || ori === "true") {
  56054. result = true;
  56055. break;
  56056. }
  56057. // result equals false (or undefined)
  56058. if (ori !== "true" && ori !== "false") {
  56059. if (ori[0] === "!") {
  56060. result = !evaluateCallback(ori.substring(1));
  56061. }
  56062. else {
  56063. result = evaluateCallback(ori);
  56064. }
  56065. }
  56066. else {
  56067. result = ori === "true" ? true : false;
  56068. }
  56069. }
  56070. }
  56071. // the whole parenthesis scope is replaced by 'true' or 'false'
  56072. return result ? "true" : "false";
  56073. };
  56074. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  56075. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  56076. // remove whitespaces
  56077. r = r.replace(/[\s]/g, function () { return ""; });
  56078. return r.length % 2 ? "!" : "";
  56079. });
  56080. booleanString = booleanString.trim();
  56081. if (booleanString === "!true") {
  56082. booleanString = "false";
  56083. }
  56084. else if (booleanString === "!false") {
  56085. booleanString = "true";
  56086. }
  56087. return booleanString;
  56088. };
  56089. return AndOrNotEvaluator;
  56090. }());
  56091. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  56092. })(BABYLON || (BABYLON = {}));
  56093. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  56094. var BABYLON;
  56095. (function (BABYLON) {
  56096. var Database = /** @class */ (function () {
  56097. function Database(urlToScene, callbackManifestChecked) {
  56098. // Handling various flavors of prefixed version of IndexedDB
  56099. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  56100. this.callbackManifestChecked = callbackManifestChecked;
  56101. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  56102. this.db = null;
  56103. this._enableSceneOffline = false;
  56104. this._enableTexturesOffline = false;
  56105. this.manifestVersionFound = 0;
  56106. this.mustUpdateRessources = false;
  56107. this.hasReachedQuota = false;
  56108. if (!Database.IDBStorageEnabled) {
  56109. this.callbackManifestChecked(true);
  56110. }
  56111. else {
  56112. this.checkManifestFile();
  56113. }
  56114. }
  56115. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  56116. get: function () {
  56117. return this._enableSceneOffline;
  56118. },
  56119. enumerable: true,
  56120. configurable: true
  56121. });
  56122. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  56123. get: function () {
  56124. return this._enableTexturesOffline;
  56125. },
  56126. enumerable: true,
  56127. configurable: true
  56128. });
  56129. Database.prototype.checkManifestFile = function () {
  56130. var _this = this;
  56131. var noManifestFile = function () {
  56132. _this._enableSceneOffline = false;
  56133. _this._enableTexturesOffline = false;
  56134. _this.callbackManifestChecked(false);
  56135. };
  56136. var timeStampUsed = false;
  56137. var manifestURL = this.currentSceneUrl + ".manifest";
  56138. var xhr = new XMLHttpRequest();
  56139. if (navigator.onLine) {
  56140. // Adding a timestamp to by-pass browsers' cache
  56141. timeStampUsed = true;
  56142. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  56143. }
  56144. xhr.open("GET", manifestURL, true);
  56145. xhr.addEventListener("load", function () {
  56146. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56147. try {
  56148. var manifestFile = JSON.parse(xhr.response);
  56149. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  56150. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  56151. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  56152. _this.manifestVersionFound = manifestFile.version;
  56153. }
  56154. if (_this.callbackManifestChecked) {
  56155. _this.callbackManifestChecked(true);
  56156. }
  56157. }
  56158. catch (ex) {
  56159. noManifestFile();
  56160. }
  56161. }
  56162. else {
  56163. noManifestFile();
  56164. }
  56165. }, false);
  56166. xhr.addEventListener("error", function (event) {
  56167. if (timeStampUsed) {
  56168. timeStampUsed = false;
  56169. // Let's retry without the timeStamp
  56170. // It could fail when coupled with HTML5 Offline API
  56171. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  56172. xhr.open("GET", retryManifestURL, true);
  56173. xhr.send();
  56174. }
  56175. else {
  56176. noManifestFile();
  56177. }
  56178. }, false);
  56179. try {
  56180. xhr.send();
  56181. }
  56182. catch (ex) {
  56183. BABYLON.Tools.Error("Error on XHR send request.");
  56184. this.callbackManifestChecked(false);
  56185. }
  56186. };
  56187. Database.prototype.openAsync = function (successCallback, errorCallback) {
  56188. var _this = this;
  56189. var handleError = function () {
  56190. _this.isSupported = false;
  56191. if (errorCallback)
  56192. errorCallback();
  56193. };
  56194. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  56195. // Your browser doesn't support IndexedDB
  56196. this.isSupported = false;
  56197. if (errorCallback)
  56198. errorCallback();
  56199. }
  56200. else {
  56201. // If the DB hasn't been opened or created yet
  56202. if (!this.db) {
  56203. this.hasReachedQuota = false;
  56204. this.isSupported = true;
  56205. var request = this.idbFactory.open("babylonjs", 1);
  56206. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  56207. request.onerror = function (event) {
  56208. handleError();
  56209. };
  56210. // executes when a version change transaction cannot complete due to other active transactions
  56211. request.onblocked = function (event) {
  56212. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  56213. handleError();
  56214. };
  56215. // DB has been opened successfully
  56216. request.onsuccess = function (event) {
  56217. _this.db = request.result;
  56218. successCallback();
  56219. };
  56220. // Initialization of the DB. Creating Scenes & Textures stores
  56221. request.onupgradeneeded = function (event) {
  56222. _this.db = (event.target).result;
  56223. if (_this.db) {
  56224. try {
  56225. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  56226. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  56227. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  56228. }
  56229. catch (ex) {
  56230. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  56231. handleError();
  56232. }
  56233. }
  56234. };
  56235. }
  56236. else {
  56237. if (successCallback)
  56238. successCallback();
  56239. }
  56240. }
  56241. };
  56242. Database.prototype.loadImageFromDB = function (url, image) {
  56243. var _this = this;
  56244. var completeURL = Database.ReturnFullUrlLocation(url);
  56245. var saveAndLoadImage = function () {
  56246. if (!_this.hasReachedQuota && _this.db !== null) {
  56247. // the texture is not yet in the DB, let's try to save it
  56248. _this._saveImageIntoDBAsync(completeURL, image);
  56249. }
  56250. else {
  56251. image.src = url;
  56252. }
  56253. };
  56254. if (!this.mustUpdateRessources) {
  56255. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  56256. }
  56257. else {
  56258. saveAndLoadImage();
  56259. }
  56260. };
  56261. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  56262. if (this.isSupported && this.db !== null) {
  56263. var texture;
  56264. var transaction = this.db.transaction(["textures"]);
  56265. transaction.onabort = function (event) {
  56266. image.src = url;
  56267. };
  56268. transaction.oncomplete = function (event) {
  56269. var blobTextureURL;
  56270. if (texture) {
  56271. var URL = window.URL || window.webkitURL;
  56272. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  56273. image.onerror = function () {
  56274. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  56275. image.src = url;
  56276. };
  56277. image.src = blobTextureURL;
  56278. }
  56279. else {
  56280. notInDBCallback();
  56281. }
  56282. };
  56283. var getRequest = transaction.objectStore("textures").get(url);
  56284. getRequest.onsuccess = function (event) {
  56285. texture = (event.target).result;
  56286. };
  56287. getRequest.onerror = function (event) {
  56288. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  56289. image.src = url;
  56290. };
  56291. }
  56292. else {
  56293. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56294. image.src = url;
  56295. }
  56296. };
  56297. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  56298. var _this = this;
  56299. if (this.isSupported) {
  56300. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  56301. var generateBlobUrl = function () {
  56302. var blobTextureURL;
  56303. if (blob) {
  56304. var URL = window.URL || window.webkitURL;
  56305. try {
  56306. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  56307. }
  56308. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  56309. catch (ex) {
  56310. blobTextureURL = URL.createObjectURL(blob);
  56311. }
  56312. }
  56313. if (blobTextureURL) {
  56314. image.src = blobTextureURL;
  56315. }
  56316. };
  56317. if (Database.IsUASupportingBlobStorage) {
  56318. var xhr = new XMLHttpRequest(), blob;
  56319. xhr.open("GET", url, true);
  56320. xhr.responseType = "blob";
  56321. xhr.addEventListener("load", function () {
  56322. if (xhr.status === 200 && _this.db) {
  56323. // Blob as response (XHR2)
  56324. blob = xhr.response;
  56325. var transaction = _this.db.transaction(["textures"], "readwrite");
  56326. // the transaction could abort because of a QuotaExceededError error
  56327. transaction.onabort = function (event) {
  56328. try {
  56329. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56330. var srcElement = (event.srcElement || event.target);
  56331. var error = srcElement.error;
  56332. if (error && error.name === "QuotaExceededError") {
  56333. _this.hasReachedQuota = true;
  56334. }
  56335. }
  56336. catch (ex) { }
  56337. generateBlobUrl();
  56338. };
  56339. transaction.oncomplete = function (event) {
  56340. generateBlobUrl();
  56341. };
  56342. var newTexture = { textureUrl: url, data: blob };
  56343. try {
  56344. // Put the blob into the dabase
  56345. var addRequest = transaction.objectStore("textures").put(newTexture);
  56346. addRequest.onsuccess = function (event) {
  56347. };
  56348. addRequest.onerror = function (event) {
  56349. generateBlobUrl();
  56350. };
  56351. }
  56352. catch (ex) {
  56353. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  56354. if (ex.code === 25) {
  56355. Database.IsUASupportingBlobStorage = false;
  56356. }
  56357. image.src = url;
  56358. }
  56359. }
  56360. else {
  56361. image.src = url;
  56362. }
  56363. }, false);
  56364. xhr.addEventListener("error", function (event) {
  56365. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  56366. image.src = url;
  56367. }, false);
  56368. xhr.send();
  56369. }
  56370. else {
  56371. image.src = url;
  56372. }
  56373. }
  56374. else {
  56375. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56376. image.src = url;
  56377. }
  56378. };
  56379. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  56380. var _this = this;
  56381. var updateVersion = function () {
  56382. // the version is not yet in the DB or we need to update it
  56383. _this._saveVersionIntoDBAsync(url, versionLoaded);
  56384. };
  56385. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  56386. };
  56387. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  56388. var _this = this;
  56389. if (this.isSupported && this.db) {
  56390. var version;
  56391. try {
  56392. var transaction = this.db.transaction(["versions"]);
  56393. transaction.oncomplete = function (event) {
  56394. if (version) {
  56395. // If the version in the JSON file is > than the version in DB
  56396. if (_this.manifestVersionFound > version.data) {
  56397. _this.mustUpdateRessources = true;
  56398. updateInDBCallback();
  56399. }
  56400. else {
  56401. callback(version.data);
  56402. }
  56403. }
  56404. else {
  56405. _this.mustUpdateRessources = true;
  56406. updateInDBCallback();
  56407. }
  56408. };
  56409. transaction.onabort = function (event) {
  56410. callback(-1);
  56411. };
  56412. var getRequest = transaction.objectStore("versions").get(url);
  56413. getRequest.onsuccess = function (event) {
  56414. version = (event.target).result;
  56415. };
  56416. getRequest.onerror = function (event) {
  56417. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  56418. callback(-1);
  56419. };
  56420. }
  56421. catch (ex) {
  56422. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  56423. callback(-1);
  56424. }
  56425. }
  56426. else {
  56427. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56428. callback(-1);
  56429. }
  56430. };
  56431. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  56432. var _this = this;
  56433. if (this.isSupported && !this.hasReachedQuota && this.db) {
  56434. try {
  56435. // Open a transaction to the database
  56436. var transaction = this.db.transaction(["versions"], "readwrite");
  56437. // the transaction could abort because of a QuotaExceededError error
  56438. transaction.onabort = function (event) {
  56439. try {
  56440. var error = event.srcElement['error'];
  56441. if (error && error.name === "QuotaExceededError") {
  56442. _this.hasReachedQuota = true;
  56443. }
  56444. }
  56445. catch (ex) { }
  56446. callback(-1);
  56447. };
  56448. transaction.oncomplete = function (event) {
  56449. callback(_this.manifestVersionFound);
  56450. };
  56451. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  56452. // Put the scene into the database
  56453. var addRequest = transaction.objectStore("versions").put(newVersion);
  56454. addRequest.onsuccess = function (event) {
  56455. };
  56456. addRequest.onerror = function (event) {
  56457. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  56458. };
  56459. }
  56460. catch (ex) {
  56461. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  56462. callback(-1);
  56463. }
  56464. }
  56465. else {
  56466. callback(-1);
  56467. }
  56468. };
  56469. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  56470. var _this = this;
  56471. var completeUrl = Database.ReturnFullUrlLocation(url);
  56472. var saveAndLoadFile = function () {
  56473. // the scene is not yet in the DB, let's try to save it
  56474. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  56475. };
  56476. this._checkVersionFromDB(completeUrl, function (version) {
  56477. if (version !== -1) {
  56478. if (!_this.mustUpdateRessources) {
  56479. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  56480. }
  56481. else {
  56482. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  56483. }
  56484. }
  56485. else {
  56486. if (errorCallback) {
  56487. errorCallback();
  56488. }
  56489. }
  56490. });
  56491. };
  56492. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  56493. if (this.isSupported && this.db) {
  56494. var targetStore;
  56495. if (url.indexOf(".babylon") !== -1) {
  56496. targetStore = "scenes";
  56497. }
  56498. else {
  56499. targetStore = "textures";
  56500. }
  56501. var file;
  56502. var transaction = this.db.transaction([targetStore]);
  56503. transaction.oncomplete = function (event) {
  56504. if (file) {
  56505. callback(file.data);
  56506. }
  56507. else {
  56508. notInDBCallback();
  56509. }
  56510. };
  56511. transaction.onabort = function (event) {
  56512. notInDBCallback();
  56513. };
  56514. var getRequest = transaction.objectStore(targetStore).get(url);
  56515. getRequest.onsuccess = function (event) {
  56516. file = (event.target).result;
  56517. };
  56518. getRequest.onerror = function (event) {
  56519. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  56520. notInDBCallback();
  56521. };
  56522. }
  56523. else {
  56524. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56525. callback();
  56526. }
  56527. };
  56528. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  56529. var _this = this;
  56530. if (this.isSupported) {
  56531. var targetStore;
  56532. if (url.indexOf(".babylon") !== -1) {
  56533. targetStore = "scenes";
  56534. }
  56535. else {
  56536. targetStore = "textures";
  56537. }
  56538. // Create XHR
  56539. var xhr = new XMLHttpRequest();
  56540. var fileData;
  56541. xhr.open("GET", url, true);
  56542. if (useArrayBuffer) {
  56543. xhr.responseType = "arraybuffer";
  56544. }
  56545. if (progressCallback) {
  56546. xhr.onprogress = progressCallback;
  56547. }
  56548. xhr.addEventListener("load", function () {
  56549. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  56550. // Blob as response (XHR2)
  56551. //fileData = xhr.responseText;
  56552. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  56553. if (!_this.hasReachedQuota && _this.db) {
  56554. // Open a transaction to the database
  56555. var transaction = _this.db.transaction([targetStore], "readwrite");
  56556. // the transaction could abort because of a QuotaExceededError error
  56557. transaction.onabort = function (event) {
  56558. try {
  56559. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  56560. var error = event.srcElement['error'];
  56561. if (error && error.name === "QuotaExceededError") {
  56562. _this.hasReachedQuota = true;
  56563. }
  56564. }
  56565. catch (ex) { }
  56566. callback(fileData);
  56567. };
  56568. transaction.oncomplete = function (event) {
  56569. callback(fileData);
  56570. };
  56571. var newFile;
  56572. if (targetStore === "scenes") {
  56573. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  56574. }
  56575. else {
  56576. newFile = { textureUrl: url, data: fileData };
  56577. }
  56578. try {
  56579. // Put the scene into the database
  56580. var addRequest = transaction.objectStore(targetStore).put(newFile);
  56581. addRequest.onsuccess = function (event) {
  56582. };
  56583. addRequest.onerror = function (event) {
  56584. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  56585. };
  56586. }
  56587. catch (ex) {
  56588. callback(fileData);
  56589. }
  56590. }
  56591. else {
  56592. callback(fileData);
  56593. }
  56594. }
  56595. else {
  56596. callback();
  56597. }
  56598. }, false);
  56599. xhr.addEventListener("error", function (event) {
  56600. BABYLON.Tools.Error("error on XHR request.");
  56601. callback();
  56602. }, false);
  56603. xhr.send();
  56604. }
  56605. else {
  56606. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  56607. callback();
  56608. }
  56609. };
  56610. Database.IsUASupportingBlobStorage = true;
  56611. Database.IDBStorageEnabled = true;
  56612. Database.parseURL = function (url) {
  56613. var a = document.createElement('a');
  56614. a.href = url;
  56615. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  56616. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  56617. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  56618. return absLocation;
  56619. };
  56620. Database.ReturnFullUrlLocation = function (url) {
  56621. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  56622. return (Database.parseURL(window.location.href) + url);
  56623. }
  56624. else {
  56625. return url;
  56626. }
  56627. };
  56628. return Database;
  56629. }());
  56630. BABYLON.Database = Database;
  56631. })(BABYLON || (BABYLON = {}));
  56632. //# sourceMappingURL=babylon.database.js.map
  56633. var BABYLON;
  56634. (function (BABYLON) {
  56635. var FresnelParameters = /** @class */ (function () {
  56636. function FresnelParameters() {
  56637. this._isEnabled = true;
  56638. this.leftColor = BABYLON.Color3.White();
  56639. this.rightColor = BABYLON.Color3.Black();
  56640. this.bias = 0;
  56641. this.power = 1;
  56642. }
  56643. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  56644. get: function () {
  56645. return this._isEnabled;
  56646. },
  56647. set: function (value) {
  56648. if (this._isEnabled === value) {
  56649. return;
  56650. }
  56651. this._isEnabled = value;
  56652. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  56653. },
  56654. enumerable: true,
  56655. configurable: true
  56656. });
  56657. FresnelParameters.prototype.clone = function () {
  56658. var newFresnelParameters = new FresnelParameters();
  56659. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  56660. return newFresnelParameters;
  56661. };
  56662. FresnelParameters.prototype.serialize = function () {
  56663. var serializationObject = {};
  56664. serializationObject.isEnabled = this.isEnabled;
  56665. serializationObject.leftColor = this.leftColor;
  56666. serializationObject.rightColor = this.rightColor;
  56667. serializationObject.bias = this.bias;
  56668. serializationObject.power = this.power;
  56669. return serializationObject;
  56670. };
  56671. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56672. var fresnelParameters = new FresnelParameters();
  56673. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56674. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56675. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56676. fresnelParameters.bias = parsedFresnelParameters.bias;
  56677. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56678. return fresnelParameters;
  56679. };
  56680. return FresnelParameters;
  56681. }());
  56682. BABYLON.FresnelParameters = FresnelParameters;
  56683. })(BABYLON || (BABYLON = {}));
  56684. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56685. var BABYLON;
  56686. (function (BABYLON) {
  56687. var MultiMaterial = /** @class */ (function (_super) {
  56688. __extends(MultiMaterial, _super);
  56689. function MultiMaterial(name, scene) {
  56690. var _this = _super.call(this, name, scene, true) || this;
  56691. scene.multiMaterials.push(_this);
  56692. _this.subMaterials = new Array();
  56693. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56694. return _this;
  56695. }
  56696. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56697. get: function () {
  56698. return this._subMaterials;
  56699. },
  56700. set: function (value) {
  56701. this._subMaterials = value;
  56702. this._hookArray(value);
  56703. },
  56704. enumerable: true,
  56705. configurable: true
  56706. });
  56707. MultiMaterial.prototype._hookArray = function (array) {
  56708. var _this = this;
  56709. var oldPush = array.push;
  56710. array.push = function () {
  56711. var items = [];
  56712. for (var _i = 0; _i < arguments.length; _i++) {
  56713. items[_i] = arguments[_i];
  56714. }
  56715. var result = oldPush.apply(array, items);
  56716. _this._markAllSubMeshesAsTexturesDirty();
  56717. return result;
  56718. };
  56719. var oldSplice = array.splice;
  56720. array.splice = function (index, deleteCount) {
  56721. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56722. _this._markAllSubMeshesAsTexturesDirty();
  56723. return deleted;
  56724. };
  56725. };
  56726. // Properties
  56727. MultiMaterial.prototype.getSubMaterial = function (index) {
  56728. if (index < 0 || index >= this.subMaterials.length) {
  56729. return this.getScene().defaultMaterial;
  56730. }
  56731. return this.subMaterials[index];
  56732. };
  56733. MultiMaterial.prototype.getActiveTextures = function () {
  56734. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56735. if (subMaterial) {
  56736. return subMaterial.getActiveTextures();
  56737. }
  56738. else {
  56739. return [];
  56740. }
  56741. }));
  56742. var _a;
  56743. };
  56744. // Methods
  56745. MultiMaterial.prototype.getClassName = function () {
  56746. return "MultiMaterial";
  56747. };
  56748. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56749. for (var index = 0; index < this.subMaterials.length; index++) {
  56750. var subMaterial = this.subMaterials[index];
  56751. if (subMaterial) {
  56752. if (subMaterial.storeEffectOnSubMeshes) {
  56753. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56754. return false;
  56755. }
  56756. continue;
  56757. }
  56758. if (!subMaterial.isReady(mesh)) {
  56759. return false;
  56760. }
  56761. }
  56762. }
  56763. return true;
  56764. };
  56765. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56766. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56767. for (var index = 0; index < this.subMaterials.length; index++) {
  56768. var subMaterial = null;
  56769. var current = this.subMaterials[index];
  56770. if (cloneChildren && current) {
  56771. subMaterial = current.clone(name + "-" + current.name);
  56772. }
  56773. else {
  56774. subMaterial = this.subMaterials[index];
  56775. }
  56776. newMultiMaterial.subMaterials.push(subMaterial);
  56777. }
  56778. return newMultiMaterial;
  56779. };
  56780. MultiMaterial.prototype.serialize = function () {
  56781. var serializationObject = {};
  56782. serializationObject.name = this.name;
  56783. serializationObject.id = this.id;
  56784. if (BABYLON.Tags) {
  56785. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56786. }
  56787. serializationObject.materials = [];
  56788. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56789. var subMat = this.subMaterials[matIndex];
  56790. if (subMat) {
  56791. serializationObject.materials.push(subMat.id);
  56792. }
  56793. else {
  56794. serializationObject.materials.push(null);
  56795. }
  56796. }
  56797. return serializationObject;
  56798. };
  56799. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56800. var scene = this.getScene();
  56801. if (!scene) {
  56802. return;
  56803. }
  56804. var index = scene.multiMaterials.indexOf(this);
  56805. if (index >= 0) {
  56806. scene.multiMaterials.splice(index, 1);
  56807. }
  56808. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56809. };
  56810. return MultiMaterial;
  56811. }(BABYLON.Material));
  56812. BABYLON.MultiMaterial = MultiMaterial;
  56813. })(BABYLON || (BABYLON = {}));
  56814. //# sourceMappingURL=babylon.multiMaterial.js.map
  56815. var BABYLON;
  56816. (function (BABYLON) {
  56817. var FreeCameraTouchInput = /** @class */ (function () {
  56818. function FreeCameraTouchInput() {
  56819. this._offsetX = null;
  56820. this._offsetY = null;
  56821. this._pointerPressed = new Array();
  56822. this.touchAngularSensibility = 200000.0;
  56823. this.touchMoveSensibility = 250.0;
  56824. }
  56825. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56826. var _this = this;
  56827. var previousPosition = null;
  56828. if (this._pointerInput === undefined) {
  56829. this._onLostFocus = function (evt) {
  56830. _this._offsetX = null;
  56831. _this._offsetY = null;
  56832. };
  56833. this._pointerInput = function (p, s) {
  56834. var evt = p.event;
  56835. if (evt.pointerType === "mouse") {
  56836. return;
  56837. }
  56838. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  56839. if (!noPreventDefault) {
  56840. evt.preventDefault();
  56841. }
  56842. _this._pointerPressed.push(evt.pointerId);
  56843. if (_this._pointerPressed.length !== 1) {
  56844. return;
  56845. }
  56846. previousPosition = {
  56847. x: evt.clientX,
  56848. y: evt.clientY
  56849. };
  56850. }
  56851. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  56852. if (!noPreventDefault) {
  56853. evt.preventDefault();
  56854. }
  56855. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56856. if (index === -1) {
  56857. return;
  56858. }
  56859. _this._pointerPressed.splice(index, 1);
  56860. if (index != 0) {
  56861. return;
  56862. }
  56863. previousPosition = null;
  56864. _this._offsetX = null;
  56865. _this._offsetY = null;
  56866. }
  56867. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  56868. if (!noPreventDefault) {
  56869. evt.preventDefault();
  56870. }
  56871. if (!previousPosition) {
  56872. return;
  56873. }
  56874. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56875. if (index != 0) {
  56876. return;
  56877. }
  56878. _this._offsetX = evt.clientX - previousPosition.x;
  56879. _this._offsetY = -(evt.clientY - previousPosition.y);
  56880. }
  56881. };
  56882. }
  56883. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  56884. if (this._onLostFocus) {
  56885. element.addEventListener("blur", this._onLostFocus);
  56886. }
  56887. };
  56888. FreeCameraTouchInput.prototype.detachControl = function (element) {
  56889. if (this._pointerInput && element) {
  56890. if (this._observer) {
  56891. this.camera.getScene().onPointerObservable.remove(this._observer);
  56892. this._observer = null;
  56893. }
  56894. if (this._onLostFocus) {
  56895. element.removeEventListener("blur", this._onLostFocus);
  56896. this._onLostFocus = null;
  56897. }
  56898. this._pointerPressed = [];
  56899. this._offsetX = null;
  56900. this._offsetY = null;
  56901. }
  56902. };
  56903. FreeCameraTouchInput.prototype.checkInputs = function () {
  56904. if (this._offsetX && this._offsetY) {
  56905. var camera = this.camera;
  56906. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  56907. if (this._pointerPressed.length > 1) {
  56908. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  56909. }
  56910. else {
  56911. var speed = camera._computeLocalCameraSpeed();
  56912. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  56913. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  56914. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  56915. }
  56916. }
  56917. };
  56918. FreeCameraTouchInput.prototype.getClassName = function () {
  56919. return "FreeCameraTouchInput";
  56920. };
  56921. FreeCameraTouchInput.prototype.getSimpleName = function () {
  56922. return "touch";
  56923. };
  56924. __decorate([
  56925. BABYLON.serialize()
  56926. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  56927. __decorate([
  56928. BABYLON.serialize()
  56929. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  56930. return FreeCameraTouchInput;
  56931. }());
  56932. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  56933. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  56934. })(BABYLON || (BABYLON = {}));
  56935. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  56936. var BABYLON;
  56937. (function (BABYLON) {
  56938. // We're mainly based on the logic defined into the FreeCamera code
  56939. var TouchCamera = /** @class */ (function (_super) {
  56940. __extends(TouchCamera, _super);
  56941. //-- end properties for backward compatibility for inputs
  56942. function TouchCamera(name, position, scene) {
  56943. var _this = _super.call(this, name, position, scene) || this;
  56944. _this.inputs.addTouch();
  56945. _this._setupInputs();
  56946. return _this;
  56947. }
  56948. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  56949. //-- Begin properties for backward compatibility for inputs
  56950. get: function () {
  56951. var touch = this.inputs.attached["touch"];
  56952. if (touch)
  56953. return touch.touchAngularSensibility;
  56954. return 0;
  56955. },
  56956. set: function (value) {
  56957. var touch = this.inputs.attached["touch"];
  56958. if (touch)
  56959. touch.touchAngularSensibility = value;
  56960. },
  56961. enumerable: true,
  56962. configurable: true
  56963. });
  56964. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  56965. get: function () {
  56966. var touch = this.inputs.attached["touch"];
  56967. if (touch)
  56968. return touch.touchMoveSensibility;
  56969. return 0;
  56970. },
  56971. set: function (value) {
  56972. var touch = this.inputs.attached["touch"];
  56973. if (touch)
  56974. touch.touchMoveSensibility = value;
  56975. },
  56976. enumerable: true,
  56977. configurable: true
  56978. });
  56979. TouchCamera.prototype.getClassName = function () {
  56980. return "TouchCamera";
  56981. };
  56982. TouchCamera.prototype._setupInputs = function () {
  56983. var mouse = this.inputs.attached["mouse"];
  56984. if (mouse) {
  56985. mouse.touchEnabled = false;
  56986. }
  56987. };
  56988. return TouchCamera;
  56989. }(BABYLON.FreeCamera));
  56990. BABYLON.TouchCamera = TouchCamera;
  56991. })(BABYLON || (BABYLON = {}));
  56992. //# sourceMappingURL=babylon.touchCamera.js.map
  56993. var BABYLON;
  56994. (function (BABYLON) {
  56995. var ProceduralTexture = /** @class */ (function (_super) {
  56996. __extends(ProceduralTexture, _super);
  56997. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  56998. if (fallbackTexture === void 0) { fallbackTexture = null; }
  56999. if (generateMipMaps === void 0) { generateMipMaps = true; }
  57000. if (isCube === void 0) { isCube = false; }
  57001. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57002. _this.isCube = isCube;
  57003. _this.isEnabled = true;
  57004. _this._currentRefreshId = -1;
  57005. _this._refreshRate = 1;
  57006. _this._vertexBuffers = {};
  57007. _this._uniforms = new Array();
  57008. _this._samplers = new Array();
  57009. _this._textures = {};
  57010. _this._floats = {};
  57011. _this._floatsArrays = {};
  57012. _this._colors3 = {};
  57013. _this._colors4 = {};
  57014. _this._vectors2 = {};
  57015. _this._vectors3 = {};
  57016. _this._matrices = {};
  57017. _this._fallbackTextureUsed = false;
  57018. scene._proceduralTextures.push(_this);
  57019. _this._engine = scene.getEngine();
  57020. _this.name = name;
  57021. _this.isRenderTarget = true;
  57022. _this._size = size;
  57023. _this._generateMipMaps = generateMipMaps;
  57024. _this.setFragment(fragment);
  57025. _this._fallbackTexture = fallbackTexture;
  57026. if (isCube) {
  57027. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  57028. _this.setFloat("face", 0);
  57029. }
  57030. else {
  57031. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  57032. }
  57033. // VBO
  57034. var vertices = [];
  57035. vertices.push(1, 1);
  57036. vertices.push(-1, 1);
  57037. vertices.push(-1, -1);
  57038. vertices.push(1, -1);
  57039. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  57040. _this._createIndexBuffer();
  57041. return _this;
  57042. }
  57043. ProceduralTexture.prototype._createIndexBuffer = function () {
  57044. var engine = this._engine;
  57045. // Indices
  57046. var indices = [];
  57047. indices.push(0);
  57048. indices.push(1);
  57049. indices.push(2);
  57050. indices.push(0);
  57051. indices.push(2);
  57052. indices.push(3);
  57053. this._indexBuffer = engine.createIndexBuffer(indices);
  57054. };
  57055. ProceduralTexture.prototype._rebuild = function () {
  57056. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57057. if (vb) {
  57058. vb._rebuild();
  57059. }
  57060. this._createIndexBuffer();
  57061. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57062. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57063. }
  57064. };
  57065. ProceduralTexture.prototype.reset = function () {
  57066. if (this._effect === undefined) {
  57067. return;
  57068. }
  57069. var engine = this._engine;
  57070. engine._releaseEffect(this._effect);
  57071. };
  57072. ProceduralTexture.prototype.isReady = function () {
  57073. var _this = this;
  57074. var engine = this._engine;
  57075. var shaders;
  57076. if (!this._fragment) {
  57077. return false;
  57078. }
  57079. if (this._fallbackTextureUsed) {
  57080. return true;
  57081. }
  57082. if (this._fragment.fragmentElement !== undefined) {
  57083. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  57084. }
  57085. else {
  57086. shaders = { vertex: "procedural", fragment: this._fragment };
  57087. }
  57088. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  57089. _this.releaseInternalTexture();
  57090. if (_this._fallbackTexture) {
  57091. _this._texture = _this._fallbackTexture._texture;
  57092. if (_this._texture) {
  57093. _this._texture.incrementReferences();
  57094. }
  57095. }
  57096. _this._fallbackTextureUsed = true;
  57097. });
  57098. return this._effect.isReady();
  57099. };
  57100. ProceduralTexture.prototype.resetRefreshCounter = function () {
  57101. this._currentRefreshId = -1;
  57102. };
  57103. ProceduralTexture.prototype.setFragment = function (fragment) {
  57104. this._fragment = fragment;
  57105. };
  57106. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  57107. get: function () {
  57108. return this._refreshRate;
  57109. },
  57110. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57111. set: function (value) {
  57112. this._refreshRate = value;
  57113. this.resetRefreshCounter();
  57114. },
  57115. enumerable: true,
  57116. configurable: true
  57117. });
  57118. ProceduralTexture.prototype._shouldRender = function () {
  57119. if (!this.isEnabled || !this.isReady() || !this._texture) {
  57120. return false;
  57121. }
  57122. if (this._fallbackTextureUsed) {
  57123. return false;
  57124. }
  57125. if (this._currentRefreshId === -1) {
  57126. this._currentRefreshId = 1;
  57127. return true;
  57128. }
  57129. if (this.refreshRate === this._currentRefreshId) {
  57130. this._currentRefreshId = 1;
  57131. return true;
  57132. }
  57133. this._currentRefreshId++;
  57134. return false;
  57135. };
  57136. ProceduralTexture.prototype.getRenderSize = function () {
  57137. return this._size;
  57138. };
  57139. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  57140. if (this._fallbackTextureUsed) {
  57141. return;
  57142. }
  57143. this.releaseInternalTexture();
  57144. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  57145. };
  57146. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  57147. if (this._uniforms.indexOf(uniformName) === -1) {
  57148. this._uniforms.push(uniformName);
  57149. }
  57150. };
  57151. ProceduralTexture.prototype.setTexture = function (name, texture) {
  57152. if (this._samplers.indexOf(name) === -1) {
  57153. this._samplers.push(name);
  57154. }
  57155. this._textures[name] = texture;
  57156. return this;
  57157. };
  57158. ProceduralTexture.prototype.setFloat = function (name, value) {
  57159. this._checkUniform(name);
  57160. this._floats[name] = value;
  57161. return this;
  57162. };
  57163. ProceduralTexture.prototype.setFloats = function (name, value) {
  57164. this._checkUniform(name);
  57165. this._floatsArrays[name] = value;
  57166. return this;
  57167. };
  57168. ProceduralTexture.prototype.setColor3 = function (name, value) {
  57169. this._checkUniform(name);
  57170. this._colors3[name] = value;
  57171. return this;
  57172. };
  57173. ProceduralTexture.prototype.setColor4 = function (name, value) {
  57174. this._checkUniform(name);
  57175. this._colors4[name] = value;
  57176. return this;
  57177. };
  57178. ProceduralTexture.prototype.setVector2 = function (name, value) {
  57179. this._checkUniform(name);
  57180. this._vectors2[name] = value;
  57181. return this;
  57182. };
  57183. ProceduralTexture.prototype.setVector3 = function (name, value) {
  57184. this._checkUniform(name);
  57185. this._vectors3[name] = value;
  57186. return this;
  57187. };
  57188. ProceduralTexture.prototype.setMatrix = function (name, value) {
  57189. this._checkUniform(name);
  57190. this._matrices[name] = value;
  57191. return this;
  57192. };
  57193. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57194. var scene = this.getScene();
  57195. if (!scene) {
  57196. return;
  57197. }
  57198. var engine = this._engine;
  57199. // Render
  57200. engine.enableEffect(this._effect);
  57201. engine.setState(false);
  57202. // Texture
  57203. for (var name in this._textures) {
  57204. this._effect.setTexture(name, this._textures[name]);
  57205. }
  57206. // Float
  57207. for (name in this._floats) {
  57208. this._effect.setFloat(name, this._floats[name]);
  57209. }
  57210. // Floats
  57211. for (name in this._floatsArrays) {
  57212. this._effect.setArray(name, this._floatsArrays[name]);
  57213. }
  57214. // Color3
  57215. for (name in this._colors3) {
  57216. this._effect.setColor3(name, this._colors3[name]);
  57217. }
  57218. // Color4
  57219. for (name in this._colors4) {
  57220. var color = this._colors4[name];
  57221. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  57222. }
  57223. // Vector2
  57224. for (name in this._vectors2) {
  57225. this._effect.setVector2(name, this._vectors2[name]);
  57226. }
  57227. // Vector3
  57228. for (name in this._vectors3) {
  57229. this._effect.setVector3(name, this._vectors3[name]);
  57230. }
  57231. // Matrix
  57232. for (name in this._matrices) {
  57233. this._effect.setMatrix(name, this._matrices[name]);
  57234. }
  57235. if (!this._texture) {
  57236. return;
  57237. }
  57238. if (this.isCube) {
  57239. for (var face = 0; face < 6; face++) {
  57240. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  57241. // VBOs
  57242. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57243. this._effect.setFloat("face", face);
  57244. // Clear
  57245. engine.clear(scene.clearColor, true, true, true);
  57246. // Draw order
  57247. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57248. // Mipmaps
  57249. if (face === 5) {
  57250. engine.generateMipMapsForCubemap(this._texture);
  57251. }
  57252. }
  57253. }
  57254. else {
  57255. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  57256. // VBOs
  57257. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  57258. // Clear
  57259. engine.clear(scene.clearColor, true, true, true);
  57260. // Draw order
  57261. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  57262. }
  57263. // Unbind
  57264. engine.unBindFramebuffer(this._texture, this.isCube);
  57265. if (this.onGenerated) {
  57266. this.onGenerated();
  57267. }
  57268. };
  57269. ProceduralTexture.prototype.clone = function () {
  57270. var textureSize = this.getSize();
  57271. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  57272. // Base texture
  57273. newTexture.hasAlpha = this.hasAlpha;
  57274. newTexture.level = this.level;
  57275. // RenderTarget Texture
  57276. newTexture.coordinatesMode = this.coordinatesMode;
  57277. return newTexture;
  57278. };
  57279. ProceduralTexture.prototype.dispose = function () {
  57280. var scene = this.getScene();
  57281. if (!scene) {
  57282. return;
  57283. }
  57284. var index = scene._proceduralTextures.indexOf(this);
  57285. if (index >= 0) {
  57286. scene._proceduralTextures.splice(index, 1);
  57287. }
  57288. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  57289. if (vertexBuffer) {
  57290. vertexBuffer.dispose();
  57291. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  57292. }
  57293. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  57294. this._indexBuffer = null;
  57295. }
  57296. _super.prototype.dispose.call(this);
  57297. };
  57298. return ProceduralTexture;
  57299. }(BABYLON.Texture));
  57300. BABYLON.ProceduralTexture = ProceduralTexture;
  57301. })(BABYLON || (BABYLON = {}));
  57302. //# sourceMappingURL=babylon.proceduralTexture.js.map
  57303. var BABYLON;
  57304. (function (BABYLON) {
  57305. var CustomProceduralTexture = /** @class */ (function (_super) {
  57306. __extends(CustomProceduralTexture, _super);
  57307. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  57308. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  57309. _this._animate = true;
  57310. _this._time = 0;
  57311. _this._texturePath = texturePath;
  57312. //Try to load json
  57313. _this.loadJson(texturePath);
  57314. _this.refreshRate = 1;
  57315. return _this;
  57316. }
  57317. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  57318. var _this = this;
  57319. var noConfigFile = function () {
  57320. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  57321. try {
  57322. _this.setFragment(_this._texturePath);
  57323. }
  57324. catch (ex) {
  57325. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  57326. }
  57327. };
  57328. var configFileUrl = jsonUrl + "/config.json";
  57329. var xhr = new XMLHttpRequest();
  57330. xhr.open("GET", configFileUrl, true);
  57331. xhr.addEventListener("load", function () {
  57332. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  57333. try {
  57334. _this._config = JSON.parse(xhr.response);
  57335. _this.updateShaderUniforms();
  57336. _this.updateTextures();
  57337. _this.setFragment(_this._texturePath + "/custom");
  57338. _this._animate = _this._config.animate;
  57339. _this.refreshRate = _this._config.refreshrate;
  57340. }
  57341. catch (ex) {
  57342. noConfigFile();
  57343. }
  57344. }
  57345. else {
  57346. noConfigFile();
  57347. }
  57348. }, false);
  57349. xhr.addEventListener("error", function () {
  57350. noConfigFile();
  57351. }, false);
  57352. try {
  57353. xhr.send();
  57354. }
  57355. catch (ex) {
  57356. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  57357. }
  57358. };
  57359. CustomProceduralTexture.prototype.isReady = function () {
  57360. if (!_super.prototype.isReady.call(this)) {
  57361. return false;
  57362. }
  57363. for (var name in this._textures) {
  57364. var texture = this._textures[name];
  57365. if (!texture.isReady()) {
  57366. return false;
  57367. }
  57368. }
  57369. return true;
  57370. };
  57371. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  57372. var scene = this.getScene();
  57373. if (this._animate && scene) {
  57374. this._time += scene.getAnimationRatio() * 0.03;
  57375. this.updateShaderUniforms();
  57376. }
  57377. _super.prototype.render.call(this, useCameraPostProcess);
  57378. };
  57379. CustomProceduralTexture.prototype.updateTextures = function () {
  57380. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  57381. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  57382. }
  57383. };
  57384. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  57385. if (this._config) {
  57386. for (var j = 0; j < this._config.uniforms.length; j++) {
  57387. var uniform = this._config.uniforms[j];
  57388. switch (uniform.type) {
  57389. case "float":
  57390. this.setFloat(uniform.name, uniform.value);
  57391. break;
  57392. case "color3":
  57393. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  57394. break;
  57395. case "color4":
  57396. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  57397. break;
  57398. case "vector2":
  57399. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  57400. break;
  57401. case "vector3":
  57402. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  57403. break;
  57404. }
  57405. }
  57406. }
  57407. this.setFloat("time", this._time);
  57408. };
  57409. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  57410. get: function () {
  57411. return this._animate;
  57412. },
  57413. set: function (value) {
  57414. this._animate = value;
  57415. },
  57416. enumerable: true,
  57417. configurable: true
  57418. });
  57419. return CustomProceduralTexture;
  57420. }(BABYLON.ProceduralTexture));
  57421. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  57422. })(BABYLON || (BABYLON = {}));
  57423. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  57424. var BABYLON;
  57425. (function (BABYLON) {
  57426. var FreeCameraGamepadInput = /** @class */ (function () {
  57427. function FreeCameraGamepadInput() {
  57428. this.gamepadAngularSensibility = 200;
  57429. this.gamepadMoveSensibility = 40;
  57430. // private members
  57431. this._cameraTransform = BABYLON.Matrix.Identity();
  57432. this._deltaTransform = BABYLON.Vector3.Zero();
  57433. this._vector3 = BABYLON.Vector3.Zero();
  57434. this._vector2 = BABYLON.Vector2.Zero();
  57435. }
  57436. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57437. var _this = this;
  57438. var manager = this.camera.getScene().gamepadManager;
  57439. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57440. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57441. // prioritize XBOX gamepads.
  57442. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57443. _this.gamepad = gamepad;
  57444. }
  57445. }
  57446. });
  57447. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57448. if (_this.gamepad === gamepad) {
  57449. _this.gamepad = null;
  57450. }
  57451. });
  57452. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57453. };
  57454. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  57455. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57456. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57457. this.gamepad = null;
  57458. };
  57459. FreeCameraGamepadInput.prototype.checkInputs = function () {
  57460. if (this.gamepad && this.gamepad.leftStick) {
  57461. var camera = this.camera;
  57462. var LSValues = this.gamepad.leftStick;
  57463. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  57464. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57465. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  57466. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  57467. var RSValues = this.gamepad.rightStick;
  57468. if (RSValues) {
  57469. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  57470. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  57471. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  57472. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  57473. }
  57474. else {
  57475. RSValues = { x: 0, y: 0 };
  57476. }
  57477. if (!camera.rotationQuaternion) {
  57478. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  57479. }
  57480. else {
  57481. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  57482. }
  57483. var speed = camera._computeLocalCameraSpeed() * 50.0;
  57484. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  57485. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  57486. camera.cameraDirection.addInPlace(this._deltaTransform);
  57487. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  57488. camera.cameraRotation.addInPlace(this._vector2);
  57489. }
  57490. };
  57491. FreeCameraGamepadInput.prototype.getClassName = function () {
  57492. return "FreeCameraGamepadInput";
  57493. };
  57494. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  57495. return "gamepad";
  57496. };
  57497. __decorate([
  57498. BABYLON.serialize()
  57499. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  57500. __decorate([
  57501. BABYLON.serialize()
  57502. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57503. return FreeCameraGamepadInput;
  57504. }());
  57505. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  57506. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  57507. })(BABYLON || (BABYLON = {}));
  57508. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  57509. var BABYLON;
  57510. (function (BABYLON) {
  57511. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  57512. function ArcRotateCameraGamepadInput() {
  57513. this.gamepadRotationSensibility = 80;
  57514. this.gamepadMoveSensibility = 40;
  57515. }
  57516. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  57517. var _this = this;
  57518. var manager = this.camera.getScene().gamepadManager;
  57519. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  57520. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  57521. // prioritize XBOX gamepads.
  57522. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  57523. _this.gamepad = gamepad;
  57524. }
  57525. }
  57526. });
  57527. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  57528. if (_this.gamepad === gamepad) {
  57529. _this.gamepad = null;
  57530. }
  57531. });
  57532. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  57533. };
  57534. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  57535. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  57536. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  57537. this.gamepad = null;
  57538. };
  57539. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  57540. if (this.gamepad) {
  57541. var camera = this.camera;
  57542. var RSValues = this.gamepad.rightStick;
  57543. if (RSValues) {
  57544. if (RSValues.x != 0) {
  57545. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  57546. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  57547. camera.inertialAlphaOffset += normalizedRX;
  57548. }
  57549. }
  57550. if (RSValues.y != 0) {
  57551. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  57552. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  57553. camera.inertialBetaOffset += normalizedRY;
  57554. }
  57555. }
  57556. }
  57557. var LSValues = this.gamepad.leftStick;
  57558. if (LSValues && LSValues.y != 0) {
  57559. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  57560. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  57561. this.camera.inertialRadiusOffset -= normalizedLY;
  57562. }
  57563. }
  57564. }
  57565. };
  57566. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  57567. return "ArcRotateCameraGamepadInput";
  57568. };
  57569. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  57570. return "gamepad";
  57571. };
  57572. __decorate([
  57573. BABYLON.serialize()
  57574. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  57575. __decorate([
  57576. BABYLON.serialize()
  57577. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  57578. return ArcRotateCameraGamepadInput;
  57579. }());
  57580. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  57581. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  57582. })(BABYLON || (BABYLON = {}));
  57583. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  57584. var BABYLON;
  57585. (function (BABYLON) {
  57586. var GamepadManager = /** @class */ (function () {
  57587. function GamepadManager(_scene) {
  57588. var _this = this;
  57589. this._scene = _scene;
  57590. this._babylonGamepads = [];
  57591. this._oneGamepadConnected = false;
  57592. this._isMonitoring = false;
  57593. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  57594. if (!BABYLON.Tools.IsWindowObjectExist()) {
  57595. this._gamepadEventSupported = false;
  57596. }
  57597. else {
  57598. this._gamepadEventSupported = 'GamepadEvent' in window;
  57599. this._gamepadSupport = (navigator.getGamepads ||
  57600. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  57601. }
  57602. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  57603. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  57604. for (var i in _this._babylonGamepads) {
  57605. var gamepad = _this._babylonGamepads[i];
  57606. if (gamepad && gamepad._isConnected) {
  57607. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  57608. }
  57609. }
  57610. });
  57611. this._onGamepadConnectedEvent = function (evt) {
  57612. var gamepad = evt.gamepad;
  57613. if (gamepad.index in _this._babylonGamepads) {
  57614. if (_this._babylonGamepads[gamepad.index].isConnected) {
  57615. return;
  57616. }
  57617. }
  57618. var newGamepad;
  57619. if (_this._babylonGamepads[gamepad.index]) {
  57620. newGamepad = _this._babylonGamepads[gamepad.index];
  57621. newGamepad.browserGamepad = gamepad;
  57622. newGamepad._isConnected = true;
  57623. }
  57624. else {
  57625. newGamepad = _this._addNewGamepad(gamepad);
  57626. }
  57627. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57628. _this._startMonitoringGamepads();
  57629. };
  57630. this._onGamepadDisconnectedEvent = function (evt) {
  57631. var gamepad = evt.gamepad;
  57632. // Remove the gamepad from the list of gamepads to monitor.
  57633. for (var i in _this._babylonGamepads) {
  57634. if (_this._babylonGamepads[i].index === gamepad.index) {
  57635. var disconnectedGamepad = _this._babylonGamepads[i];
  57636. disconnectedGamepad._isConnected = false;
  57637. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  57638. break;
  57639. }
  57640. }
  57641. };
  57642. if (this._gamepadSupport) {
  57643. //first add already-connected gamepads
  57644. this._updateGamepadObjects();
  57645. if (this._babylonGamepads.length) {
  57646. this._startMonitoringGamepads();
  57647. }
  57648. // Checking if the gamepad connected event is supported (like in Firefox)
  57649. if (this._gamepadEventSupported) {
  57650. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  57651. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  57652. }
  57653. else {
  57654. this._startMonitoringGamepads();
  57655. }
  57656. }
  57657. }
  57658. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  57659. get: function () {
  57660. return this._babylonGamepads;
  57661. },
  57662. enumerable: true,
  57663. configurable: true
  57664. });
  57665. GamepadManager.prototype.getGamepadByType = function (type) {
  57666. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57667. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57668. var gamepad = _a[_i];
  57669. if (gamepad && gamepad.type === type) {
  57670. return gamepad;
  57671. }
  57672. }
  57673. return null;
  57674. };
  57675. GamepadManager.prototype.dispose = function () {
  57676. if (this._gamepadEventSupported) {
  57677. if (this._onGamepadConnectedEvent) {
  57678. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57679. }
  57680. if (this._onGamepadDisconnectedEvent) {
  57681. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57682. }
  57683. this._onGamepadConnectedEvent = null;
  57684. this._onGamepadDisconnectedEvent = null;
  57685. }
  57686. this._babylonGamepads.forEach(function (gamepad) {
  57687. gamepad.dispose();
  57688. });
  57689. this.onGamepadConnectedObservable.clear();
  57690. this.onGamepadDisconnectedObservable.clear();
  57691. this._oneGamepadConnected = false;
  57692. this._stopMonitoringGamepads();
  57693. this._babylonGamepads = [];
  57694. };
  57695. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57696. if (!this._oneGamepadConnected) {
  57697. this._oneGamepadConnected = true;
  57698. }
  57699. var newGamepad;
  57700. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57701. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57702. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57703. }
  57704. else if (gamepad.pose) {
  57705. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57706. }
  57707. else {
  57708. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57709. }
  57710. this._babylonGamepads[newGamepad.index] = newGamepad;
  57711. return newGamepad;
  57712. };
  57713. GamepadManager.prototype._startMonitoringGamepads = function () {
  57714. if (!this._isMonitoring) {
  57715. this._isMonitoring = true;
  57716. //back-comp
  57717. if (!this._scene) {
  57718. this._checkGamepadsStatus();
  57719. }
  57720. }
  57721. };
  57722. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57723. this._isMonitoring = false;
  57724. };
  57725. GamepadManager.prototype._checkGamepadsStatus = function () {
  57726. var _this = this;
  57727. // Hack to be compatible Chrome
  57728. this._updateGamepadObjects();
  57729. for (var i in this._babylonGamepads) {
  57730. var gamepad = this._babylonGamepads[i];
  57731. if (!gamepad || !gamepad.isConnected) {
  57732. continue;
  57733. }
  57734. gamepad.update();
  57735. }
  57736. if (this._isMonitoring && !this._scene) {
  57737. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57738. }
  57739. };
  57740. // This function is called only on Chrome, which does not properly support
  57741. // connection/disconnection events and forces you to recopy again the gamepad object
  57742. GamepadManager.prototype._updateGamepadObjects = function () {
  57743. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57744. for (var i = 0; i < gamepads.length; i++) {
  57745. if (gamepads[i]) {
  57746. if (!this._babylonGamepads[gamepads[i].index]) {
  57747. var newGamepad = this._addNewGamepad(gamepads[i]);
  57748. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57749. }
  57750. else {
  57751. // Forced to copy again this object for Chrome for unknown reason
  57752. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57753. if (!this._babylonGamepads[i].isConnected) {
  57754. this._babylonGamepads[i]._isConnected = true;
  57755. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57756. }
  57757. }
  57758. }
  57759. }
  57760. };
  57761. return GamepadManager;
  57762. }());
  57763. BABYLON.GamepadManager = GamepadManager;
  57764. })(BABYLON || (BABYLON = {}));
  57765. //# sourceMappingURL=babylon.gamepadManager.js.map
  57766. var BABYLON;
  57767. (function (BABYLON) {
  57768. var StickValues = /** @class */ (function () {
  57769. function StickValues(x, y) {
  57770. this.x = x;
  57771. this.y = y;
  57772. }
  57773. return StickValues;
  57774. }());
  57775. BABYLON.StickValues = StickValues;
  57776. var Gamepad = /** @class */ (function () {
  57777. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57778. if (leftStickX === void 0) { leftStickX = 0; }
  57779. if (leftStickY === void 0) { leftStickY = 1; }
  57780. if (rightStickX === void 0) { rightStickX = 2; }
  57781. if (rightStickY === void 0) { rightStickY = 3; }
  57782. this.id = id;
  57783. this.index = index;
  57784. this.browserGamepad = browserGamepad;
  57785. this._isConnected = true;
  57786. this._invertLeftStickY = false;
  57787. this.type = Gamepad.GAMEPAD;
  57788. this._leftStickAxisX = leftStickX;
  57789. this._leftStickAxisY = leftStickY;
  57790. this._rightStickAxisX = rightStickX;
  57791. this._rightStickAxisY = rightStickY;
  57792. if (this.browserGamepad.axes.length >= 2) {
  57793. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57794. }
  57795. if (this.browserGamepad.axes.length >= 4) {
  57796. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57797. }
  57798. }
  57799. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57800. get: function () {
  57801. return this._isConnected;
  57802. },
  57803. enumerable: true,
  57804. configurable: true
  57805. });
  57806. Gamepad.prototype.onleftstickchanged = function (callback) {
  57807. this._onleftstickchanged = callback;
  57808. };
  57809. Gamepad.prototype.onrightstickchanged = function (callback) {
  57810. this._onrightstickchanged = callback;
  57811. };
  57812. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57813. get: function () {
  57814. return this._leftStick;
  57815. },
  57816. set: function (newValues) {
  57817. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57818. this._onleftstickchanged(newValues);
  57819. }
  57820. this._leftStick = newValues;
  57821. },
  57822. enumerable: true,
  57823. configurable: true
  57824. });
  57825. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57826. get: function () {
  57827. return this._rightStick;
  57828. },
  57829. set: function (newValues) {
  57830. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57831. this._onrightstickchanged(newValues);
  57832. }
  57833. this._rightStick = newValues;
  57834. },
  57835. enumerable: true,
  57836. configurable: true
  57837. });
  57838. Gamepad.prototype.update = function () {
  57839. if (this._leftStick) {
  57840. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57841. if (this._invertLeftStickY) {
  57842. this.leftStick.y *= -1;
  57843. }
  57844. }
  57845. if (this._rightStick) {
  57846. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57847. }
  57848. };
  57849. Gamepad.prototype.dispose = function () {
  57850. };
  57851. Gamepad.GAMEPAD = 0;
  57852. Gamepad.GENERIC = 1;
  57853. Gamepad.XBOX = 2;
  57854. Gamepad.POSE_ENABLED = 3;
  57855. return Gamepad;
  57856. }());
  57857. BABYLON.Gamepad = Gamepad;
  57858. var GenericPad = /** @class */ (function (_super) {
  57859. __extends(GenericPad, _super);
  57860. function GenericPad(id, index, browserGamepad) {
  57861. var _this = _super.call(this, id, index, browserGamepad) || this;
  57862. _this.onButtonDownObservable = new BABYLON.Observable();
  57863. _this.onButtonUpObservable = new BABYLON.Observable();
  57864. _this.type = Gamepad.GENERIC;
  57865. _this._buttons = new Array(browserGamepad.buttons.length);
  57866. return _this;
  57867. }
  57868. GenericPad.prototype.onbuttondown = function (callback) {
  57869. this._onbuttondown = callback;
  57870. };
  57871. GenericPad.prototype.onbuttonup = function (callback) {
  57872. this._onbuttonup = callback;
  57873. };
  57874. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  57875. if (newValue !== currentValue) {
  57876. if (newValue === 1) {
  57877. if (this._onbuttondown) {
  57878. this._onbuttondown(buttonIndex);
  57879. }
  57880. this.onButtonDownObservable.notifyObservers(buttonIndex);
  57881. }
  57882. if (newValue === 0) {
  57883. if (this._onbuttonup) {
  57884. this._onbuttonup(buttonIndex);
  57885. }
  57886. this.onButtonUpObservable.notifyObservers(buttonIndex);
  57887. }
  57888. }
  57889. return newValue;
  57890. };
  57891. GenericPad.prototype.update = function () {
  57892. _super.prototype.update.call(this);
  57893. for (var index = 0; index < this._buttons.length; index++) {
  57894. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  57895. }
  57896. };
  57897. GenericPad.prototype.dispose = function () {
  57898. _super.prototype.dispose.call(this);
  57899. this.onButtonDownObservable.clear();
  57900. this.onButtonUpObservable.clear();
  57901. };
  57902. return GenericPad;
  57903. }(Gamepad));
  57904. BABYLON.GenericPad = GenericPad;
  57905. })(BABYLON || (BABYLON = {}));
  57906. //# sourceMappingURL=babylon.gamepad.js.map
  57907. var BABYLON;
  57908. (function (BABYLON) {
  57909. var Xbox360Button;
  57910. (function (Xbox360Button) {
  57911. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  57912. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  57913. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  57914. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  57915. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  57916. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  57917. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  57918. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  57919. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  57920. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  57921. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  57922. var Xbox360Dpad;
  57923. (function (Xbox360Dpad) {
  57924. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  57925. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  57926. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  57927. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  57928. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  57929. var Xbox360Pad = /** @class */ (function (_super) {
  57930. __extends(Xbox360Pad, _super);
  57931. function Xbox360Pad(id, index, gamepad, xboxOne) {
  57932. if (xboxOne === void 0) { xboxOne = false; }
  57933. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  57934. _this._leftTrigger = 0;
  57935. _this._rightTrigger = 0;
  57936. _this.onButtonDownObservable = new BABYLON.Observable();
  57937. _this.onButtonUpObservable = new BABYLON.Observable();
  57938. _this.onPadDownObservable = new BABYLON.Observable();
  57939. _this.onPadUpObservable = new BABYLON.Observable();
  57940. _this._buttonA = 0;
  57941. _this._buttonB = 0;
  57942. _this._buttonX = 0;
  57943. _this._buttonY = 0;
  57944. _this._buttonBack = 0;
  57945. _this._buttonStart = 0;
  57946. _this._buttonLB = 0;
  57947. _this._buttonRB = 0;
  57948. _this._buttonLeftStick = 0;
  57949. _this._buttonRightStick = 0;
  57950. _this._dPadUp = 0;
  57951. _this._dPadDown = 0;
  57952. _this._dPadLeft = 0;
  57953. _this._dPadRight = 0;
  57954. _this._isXboxOnePad = false;
  57955. _this.type = BABYLON.Gamepad.XBOX;
  57956. _this._isXboxOnePad = xboxOne;
  57957. return _this;
  57958. }
  57959. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  57960. this._onlefttriggerchanged = callback;
  57961. };
  57962. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  57963. this._onrighttriggerchanged = callback;
  57964. };
  57965. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  57966. get: function () {
  57967. return this._leftTrigger;
  57968. },
  57969. set: function (newValue) {
  57970. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  57971. this._onlefttriggerchanged(newValue);
  57972. }
  57973. this._leftTrigger = newValue;
  57974. },
  57975. enumerable: true,
  57976. configurable: true
  57977. });
  57978. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  57979. get: function () {
  57980. return this._rightTrigger;
  57981. },
  57982. set: function (newValue) {
  57983. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  57984. this._onrighttriggerchanged(newValue);
  57985. }
  57986. this._rightTrigger = newValue;
  57987. },
  57988. enumerable: true,
  57989. configurable: true
  57990. });
  57991. Xbox360Pad.prototype.onbuttondown = function (callback) {
  57992. this._onbuttondown = callback;
  57993. };
  57994. Xbox360Pad.prototype.onbuttonup = function (callback) {
  57995. this._onbuttonup = callback;
  57996. };
  57997. Xbox360Pad.prototype.ondpaddown = function (callback) {
  57998. this._ondpaddown = callback;
  57999. };
  58000. Xbox360Pad.prototype.ondpadup = function (callback) {
  58001. this._ondpadup = callback;
  58002. };
  58003. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  58004. if (newValue !== currentValue) {
  58005. if (newValue === 1) {
  58006. if (this._onbuttondown) {
  58007. this._onbuttondown(buttonType);
  58008. }
  58009. this.onButtonDownObservable.notifyObservers(buttonType);
  58010. }
  58011. if (newValue === 0) {
  58012. if (this._onbuttonup) {
  58013. this._onbuttonup(buttonType);
  58014. }
  58015. this.onButtonUpObservable.notifyObservers(buttonType);
  58016. }
  58017. }
  58018. return newValue;
  58019. };
  58020. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  58021. if (newValue !== currentValue) {
  58022. if (newValue === 1) {
  58023. if (this._ondpaddown) {
  58024. this._ondpaddown(buttonType);
  58025. }
  58026. this.onPadDownObservable.notifyObservers(buttonType);
  58027. }
  58028. if (newValue === 0) {
  58029. if (this._ondpadup) {
  58030. this._ondpadup(buttonType);
  58031. }
  58032. this.onPadUpObservable.notifyObservers(buttonType);
  58033. }
  58034. }
  58035. return newValue;
  58036. };
  58037. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  58038. get: function () {
  58039. return this._buttonA;
  58040. },
  58041. set: function (value) {
  58042. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  58043. },
  58044. enumerable: true,
  58045. configurable: true
  58046. });
  58047. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  58048. get: function () {
  58049. return this._buttonB;
  58050. },
  58051. set: function (value) {
  58052. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  58053. },
  58054. enumerable: true,
  58055. configurable: true
  58056. });
  58057. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  58058. get: function () {
  58059. return this._buttonX;
  58060. },
  58061. set: function (value) {
  58062. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  58063. },
  58064. enumerable: true,
  58065. configurable: true
  58066. });
  58067. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  58068. get: function () {
  58069. return this._buttonY;
  58070. },
  58071. set: function (value) {
  58072. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  58073. },
  58074. enumerable: true,
  58075. configurable: true
  58076. });
  58077. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  58078. get: function () {
  58079. return this._buttonStart;
  58080. },
  58081. set: function (value) {
  58082. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  58083. },
  58084. enumerable: true,
  58085. configurable: true
  58086. });
  58087. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  58088. get: function () {
  58089. return this._buttonBack;
  58090. },
  58091. set: function (value) {
  58092. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  58093. },
  58094. enumerable: true,
  58095. configurable: true
  58096. });
  58097. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  58098. get: function () {
  58099. return this._buttonLB;
  58100. },
  58101. set: function (value) {
  58102. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  58103. },
  58104. enumerable: true,
  58105. configurable: true
  58106. });
  58107. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  58108. get: function () {
  58109. return this._buttonRB;
  58110. },
  58111. set: function (value) {
  58112. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  58113. },
  58114. enumerable: true,
  58115. configurable: true
  58116. });
  58117. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  58118. get: function () {
  58119. return this._buttonLeftStick;
  58120. },
  58121. set: function (value) {
  58122. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  58123. },
  58124. enumerable: true,
  58125. configurable: true
  58126. });
  58127. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  58128. get: function () {
  58129. return this._buttonRightStick;
  58130. },
  58131. set: function (value) {
  58132. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  58133. },
  58134. enumerable: true,
  58135. configurable: true
  58136. });
  58137. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  58138. get: function () {
  58139. return this._dPadUp;
  58140. },
  58141. set: function (value) {
  58142. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  58143. },
  58144. enumerable: true,
  58145. configurable: true
  58146. });
  58147. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  58148. get: function () {
  58149. return this._dPadDown;
  58150. },
  58151. set: function (value) {
  58152. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  58153. },
  58154. enumerable: true,
  58155. configurable: true
  58156. });
  58157. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  58158. get: function () {
  58159. return this._dPadLeft;
  58160. },
  58161. set: function (value) {
  58162. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  58163. },
  58164. enumerable: true,
  58165. configurable: true
  58166. });
  58167. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  58168. get: function () {
  58169. return this._dPadRight;
  58170. },
  58171. set: function (value) {
  58172. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  58173. },
  58174. enumerable: true,
  58175. configurable: true
  58176. });
  58177. Xbox360Pad.prototype.update = function () {
  58178. _super.prototype.update.call(this);
  58179. if (this._isXboxOnePad) {
  58180. this.buttonA = this.browserGamepad.buttons[0].value;
  58181. this.buttonB = this.browserGamepad.buttons[1].value;
  58182. this.buttonX = this.browserGamepad.buttons[2].value;
  58183. this.buttonY = this.browserGamepad.buttons[3].value;
  58184. this.buttonLB = this.browserGamepad.buttons[4].value;
  58185. this.buttonRB = this.browserGamepad.buttons[5].value;
  58186. this.leftTrigger = this.browserGamepad.axes[2];
  58187. this.rightTrigger = this.browserGamepad.axes[5];
  58188. this.buttonBack = this.browserGamepad.buttons[9].value;
  58189. this.buttonStart = this.browserGamepad.buttons[8].value;
  58190. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  58191. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  58192. this.dPadUp = this.browserGamepad.buttons[11].value;
  58193. this.dPadDown = this.browserGamepad.buttons[12].value;
  58194. this.dPadLeft = this.browserGamepad.buttons[13].value;
  58195. this.dPadRight = this.browserGamepad.buttons[14].value;
  58196. }
  58197. else {
  58198. this.buttonA = this.browserGamepad.buttons[0].value;
  58199. this.buttonB = this.browserGamepad.buttons[1].value;
  58200. this.buttonX = this.browserGamepad.buttons[2].value;
  58201. this.buttonY = this.browserGamepad.buttons[3].value;
  58202. this.buttonLB = this.browserGamepad.buttons[4].value;
  58203. this.buttonRB = this.browserGamepad.buttons[5].value;
  58204. this.leftTrigger = this.browserGamepad.buttons[6].value;
  58205. this.rightTrigger = this.browserGamepad.buttons[7].value;
  58206. this.buttonBack = this.browserGamepad.buttons[8].value;
  58207. this.buttonStart = this.browserGamepad.buttons[9].value;
  58208. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  58209. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  58210. this.dPadUp = this.browserGamepad.buttons[12].value;
  58211. this.dPadDown = this.browserGamepad.buttons[13].value;
  58212. this.dPadLeft = this.browserGamepad.buttons[14].value;
  58213. this.dPadRight = this.browserGamepad.buttons[15].value;
  58214. }
  58215. };
  58216. Xbox360Pad.prototype.dispose = function () {
  58217. _super.prototype.dispose.call(this);
  58218. this.onButtonDownObservable.clear();
  58219. this.onButtonUpObservable.clear();
  58220. this.onPadDownObservable.clear();
  58221. this.onPadUpObservable.clear();
  58222. };
  58223. return Xbox360Pad;
  58224. }(BABYLON.Gamepad));
  58225. BABYLON.Xbox360Pad = Xbox360Pad;
  58226. })(BABYLON || (BABYLON = {}));
  58227. //# sourceMappingURL=babylon.xboxGamepad.js.map
  58228. var BABYLON;
  58229. (function (BABYLON) {
  58230. var PoseEnabledControllerType;
  58231. (function (PoseEnabledControllerType) {
  58232. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  58233. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  58234. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  58235. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  58236. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  58237. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  58238. var PoseEnabledControllerHelper = /** @class */ (function () {
  58239. function PoseEnabledControllerHelper() {
  58240. }
  58241. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  58242. // Oculus Touch
  58243. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  58244. return new BABYLON.OculusTouchController(vrGamepad);
  58245. }
  58246. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  58247. return new BABYLON.WindowsMotionController(vrGamepad);
  58248. }
  58249. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  58250. return new BABYLON.ViveController(vrGamepad);
  58251. }
  58252. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  58253. return new BABYLON.GearVRController(vrGamepad);
  58254. }
  58255. else {
  58256. return new BABYLON.GenericController(vrGamepad);
  58257. }
  58258. };
  58259. return PoseEnabledControllerHelper;
  58260. }());
  58261. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  58262. var PoseEnabledController = /** @class */ (function (_super) {
  58263. __extends(PoseEnabledController, _super);
  58264. function PoseEnabledController(browserGamepad) {
  58265. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  58266. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  58267. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  58268. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  58269. // Represents device position and rotation in babylon space
  58270. _this.devicePosition = BABYLON.Vector3.Zero();
  58271. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  58272. _this.deviceScaleFactor = 1;
  58273. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  58274. _this._deviceToWorld = BABYLON.Matrix.Identity();
  58275. _this._workingMatrix = BABYLON.Matrix.Identity();
  58276. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  58277. _this.controllerType = PoseEnabledControllerType.GENERIC;
  58278. _this.position = BABYLON.Vector3.Zero();
  58279. _this.rotationQuaternion = new BABYLON.Quaternion();
  58280. _this._calculatedPosition = BABYLON.Vector3.Zero();
  58281. _this._calculatedRotation = new BABYLON.Quaternion();
  58282. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  58283. return _this;
  58284. }
  58285. PoseEnabledController.prototype.update = function () {
  58286. _super.prototype.update.call(this);
  58287. var pose = this.browserGamepad.pose;
  58288. this.updateFromDevice(pose);
  58289. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  58290. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  58291. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  58292. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  58293. if (this._mesh) {
  58294. this._mesh.position.copyFrom(this.devicePosition);
  58295. if (this._mesh.rotationQuaternion) {
  58296. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  58297. }
  58298. }
  58299. };
  58300. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  58301. if (poseData) {
  58302. this.rawPose = poseData;
  58303. if (poseData.position) {
  58304. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  58305. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  58306. this._deviceRoomPosition.z *= -1;
  58307. }
  58308. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  58309. this._calculatedPosition.addInPlace(this.position);
  58310. }
  58311. var pose = this.rawPose;
  58312. if (poseData.orientation && pose.orientation) {
  58313. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  58314. if (this._mesh) {
  58315. if (this._mesh.getScene().useRightHandedSystem) {
  58316. this._deviceRoomRotationQuaternion.z *= -1;
  58317. this._deviceRoomRotationQuaternion.w *= -1;
  58318. }
  58319. else {
  58320. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  58321. }
  58322. }
  58323. // if the camera is set, rotate to the camera's rotation
  58324. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  58325. }
  58326. }
  58327. };
  58328. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  58329. if (this._mesh) {
  58330. this._mesh.parent = null;
  58331. }
  58332. this._mesh = mesh;
  58333. if (this._poseControlledCamera) {
  58334. this._mesh.parent = this._poseControlledCamera;
  58335. }
  58336. if (!this._mesh.rotationQuaternion) {
  58337. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  58338. }
  58339. };
  58340. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  58341. this._poseControlledCamera = camera;
  58342. if (this._mesh) {
  58343. this._mesh.parent = this._poseControlledCamera;
  58344. }
  58345. };
  58346. PoseEnabledController.prototype.dispose = function () {
  58347. if (this._mesh) {
  58348. this._mesh.dispose();
  58349. }
  58350. this._mesh = null;
  58351. _super.prototype.dispose.call(this);
  58352. };
  58353. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  58354. get: function () {
  58355. return this._mesh;
  58356. },
  58357. enumerable: true,
  58358. configurable: true
  58359. });
  58360. PoseEnabledController.prototype.getForwardRay = function (length) {
  58361. if (length === void 0) { length = 100; }
  58362. if (!this.mesh) {
  58363. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  58364. }
  58365. var m = this.mesh.getWorldMatrix();
  58366. var origin = m.getTranslation();
  58367. var forward = new BABYLON.Vector3(0, 0, -1);
  58368. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58369. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58370. return new BABYLON.Ray(origin, direction, length);
  58371. };
  58372. return PoseEnabledController;
  58373. }(BABYLON.Gamepad));
  58374. BABYLON.PoseEnabledController = PoseEnabledController;
  58375. })(BABYLON || (BABYLON = {}));
  58376. //# sourceMappingURL=babylon.poseEnabledController.js.map
  58377. var BABYLON;
  58378. (function (BABYLON) {
  58379. var WebVRController = /** @class */ (function (_super) {
  58380. __extends(WebVRController, _super);
  58381. function WebVRController(vrGamepad) {
  58382. var _this = _super.call(this, vrGamepad) || this;
  58383. // Observables
  58384. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  58385. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  58386. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  58387. _this.onPadStateChangedObservable = new BABYLON.Observable();
  58388. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  58389. _this.pad = { x: 0, y: 0 };
  58390. // avoid GC, store state in a tmp object
  58391. _this._changes = {
  58392. pressChanged: false,
  58393. touchChanged: false,
  58394. valueChanged: false,
  58395. changed: false
  58396. };
  58397. _this._buttons = new Array(vrGamepad.buttons.length);
  58398. _this.hand = vrGamepad.hand;
  58399. return _this;
  58400. }
  58401. WebVRController.prototype.onButtonStateChange = function (callback) {
  58402. this._onButtonStateChange = callback;
  58403. };
  58404. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  58405. get: function () {
  58406. return this._defaultModel;
  58407. },
  58408. enumerable: true,
  58409. configurable: true
  58410. });
  58411. WebVRController.prototype.update = function () {
  58412. _super.prototype.update.call(this);
  58413. for (var index = 0; index < this._buttons.length; index++) {
  58414. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  58415. }
  58416. ;
  58417. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  58418. this.pad.x = this.leftStick.x;
  58419. this.pad.y = this.leftStick.y;
  58420. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  58421. }
  58422. };
  58423. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  58424. if (!newState) {
  58425. newState = {
  58426. pressed: false,
  58427. touched: false,
  58428. value: 0
  58429. };
  58430. }
  58431. if (!currentState) {
  58432. this._buttons[buttonIndex] = {
  58433. pressed: newState.pressed,
  58434. touched: newState.touched,
  58435. value: newState.value
  58436. };
  58437. return;
  58438. }
  58439. this._checkChanges(newState, currentState);
  58440. if (this._changes.changed) {
  58441. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  58442. this.handleButtonChange(buttonIndex, newState, this._changes);
  58443. }
  58444. this._buttons[buttonIndex].pressed = newState.pressed;
  58445. this._buttons[buttonIndex].touched = newState.touched;
  58446. // oculus triggers are never 0, thou not touched.
  58447. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  58448. };
  58449. WebVRController.prototype._checkChanges = function (newState, currentState) {
  58450. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  58451. this._changes.touchChanged = newState.touched !== currentState.touched;
  58452. this._changes.valueChanged = newState.value !== currentState.value;
  58453. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  58454. return this._changes;
  58455. };
  58456. WebVRController.prototype.dispose = function () {
  58457. _super.prototype.dispose.call(this);
  58458. this.onTriggerStateChangedObservable.clear();
  58459. this.onMainButtonStateChangedObservable.clear();
  58460. this.onSecondaryButtonStateChangedObservable.clear();
  58461. this.onPadStateChangedObservable.clear();
  58462. this.onPadValuesChangedObservable.clear();
  58463. };
  58464. return WebVRController;
  58465. }(BABYLON.PoseEnabledController));
  58466. BABYLON.WebVRController = WebVRController;
  58467. })(BABYLON || (BABYLON = {}));
  58468. //# sourceMappingURL=babylon.webVRController.js.map
  58469. var BABYLON;
  58470. (function (BABYLON) {
  58471. var OculusTouchController = /** @class */ (function (_super) {
  58472. __extends(OculusTouchController, _super);
  58473. function OculusTouchController(vrGamepad) {
  58474. var _this = _super.call(this, vrGamepad) || this;
  58475. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  58476. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  58477. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  58478. return _this;
  58479. }
  58480. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58481. var _this = this;
  58482. var meshName;
  58483. // Hand
  58484. if (this.hand === 'left') {
  58485. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  58486. }
  58487. else {
  58488. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  58489. }
  58490. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  58491. /*
  58492. Parent Mesh name: oculus_touch_left
  58493. - body
  58494. - trigger
  58495. - thumbstick
  58496. - grip
  58497. - button_y
  58498. - button_x
  58499. - button_enter
  58500. */
  58501. _this._defaultModel = newMeshes[1];
  58502. _this.attachToMesh(_this._defaultModel);
  58503. if (meshLoaded) {
  58504. meshLoaded(_this._defaultModel);
  58505. }
  58506. });
  58507. };
  58508. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  58509. // helper getters for left and right hand.
  58510. get: function () {
  58511. if (this.hand === 'right') {
  58512. return this.onMainButtonStateChangedObservable;
  58513. }
  58514. else {
  58515. throw new Error('No A button on left hand');
  58516. }
  58517. },
  58518. enumerable: true,
  58519. configurable: true
  58520. });
  58521. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  58522. get: function () {
  58523. if (this.hand === 'right') {
  58524. return this.onSecondaryButtonStateChangedObservable;
  58525. }
  58526. else {
  58527. throw new Error('No B button on left hand');
  58528. }
  58529. },
  58530. enumerable: true,
  58531. configurable: true
  58532. });
  58533. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  58534. get: function () {
  58535. if (this.hand === 'left') {
  58536. return this.onMainButtonStateChangedObservable;
  58537. }
  58538. else {
  58539. throw new Error('No X button on right hand');
  58540. }
  58541. },
  58542. enumerable: true,
  58543. configurable: true
  58544. });
  58545. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  58546. get: function () {
  58547. if (this.hand === 'left') {
  58548. return this.onSecondaryButtonStateChangedObservable;
  58549. }
  58550. else {
  58551. throw new Error('No Y button on right hand');
  58552. }
  58553. },
  58554. enumerable: true,
  58555. configurable: true
  58556. });
  58557. /*
  58558. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  58559. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  58560. 2) secondary trigger (same)
  58561. 3) A (right) X (left), touch, pressed = value
  58562. 4) B / Y
  58563. 5) thumb rest
  58564. */
  58565. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58566. var notifyObject = state; //{ state: state, changes: changes };
  58567. var triggerDirection = this.hand === 'right' ? -1 : 1;
  58568. switch (buttonIdx) {
  58569. case 0:
  58570. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58571. return;
  58572. case 1:// index trigger
  58573. if (this._defaultModel) {
  58574. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  58575. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  58576. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  58577. }
  58578. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58579. return;
  58580. case 2:// secondary trigger
  58581. if (this._defaultModel) {
  58582. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  58583. }
  58584. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  58585. return;
  58586. case 3:
  58587. if (this._defaultModel) {
  58588. if (notifyObject.pressed) {
  58589. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  58590. }
  58591. else {
  58592. (this._defaultModel.getChildren()[1]).position.y = 0;
  58593. }
  58594. }
  58595. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58596. return;
  58597. case 4:
  58598. if (this._defaultModel) {
  58599. if (notifyObject.pressed) {
  58600. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58601. }
  58602. else {
  58603. (this._defaultModel.getChildren()[2]).position.y = 0;
  58604. }
  58605. }
  58606. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58607. return;
  58608. case 5:
  58609. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  58610. return;
  58611. }
  58612. };
  58613. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  58614. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  58615. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  58616. return OculusTouchController;
  58617. }(BABYLON.WebVRController));
  58618. BABYLON.OculusTouchController = OculusTouchController;
  58619. })(BABYLON || (BABYLON = {}));
  58620. //# sourceMappingURL=babylon.oculusTouchController.js.map
  58621. var BABYLON;
  58622. (function (BABYLON) {
  58623. var ViveController = /** @class */ (function (_super) {
  58624. __extends(ViveController, _super);
  58625. function ViveController(vrGamepad) {
  58626. var _this = _super.call(this, vrGamepad) || this;
  58627. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  58628. _this._invertLeftStickY = true;
  58629. return _this;
  58630. }
  58631. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58632. var _this = this;
  58633. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  58634. /*
  58635. Parent Mesh name: ViveWand
  58636. - body
  58637. - r_gripper
  58638. - l_gripper
  58639. - menu_button
  58640. - system_button
  58641. - trackpad
  58642. - trigger
  58643. - LED
  58644. */
  58645. _this._defaultModel = newMeshes[1];
  58646. _this.attachToMesh(_this._defaultModel);
  58647. if (meshLoaded) {
  58648. meshLoaded(_this._defaultModel);
  58649. }
  58650. });
  58651. };
  58652. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  58653. get: function () {
  58654. return this.onMainButtonStateChangedObservable;
  58655. },
  58656. enumerable: true,
  58657. configurable: true
  58658. });
  58659. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  58660. get: function () {
  58661. return this.onMainButtonStateChangedObservable;
  58662. },
  58663. enumerable: true,
  58664. configurable: true
  58665. });
  58666. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58667. get: function () {
  58668. return this.onSecondaryButtonStateChangedObservable;
  58669. },
  58670. enumerable: true,
  58671. configurable: true
  58672. });
  58673. /**
  58674. * Vive mapping:
  58675. * 0: touchpad
  58676. * 1: trigger
  58677. * 2: left AND right buttons
  58678. * 3: menu button
  58679. */
  58680. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58681. var notifyObject = state; //{ state: state, changes: changes };
  58682. switch (buttonIdx) {
  58683. case 0:
  58684. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58685. return;
  58686. case 1:// index trigger
  58687. if (this._defaultModel) {
  58688. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58689. }
  58690. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58691. return;
  58692. case 2:// left AND right button
  58693. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58694. return;
  58695. case 3:
  58696. if (this._defaultModel) {
  58697. if (notifyObject.pressed) {
  58698. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58699. }
  58700. else {
  58701. (this._defaultModel.getChildren()[2]).position.y = 0;
  58702. }
  58703. }
  58704. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58705. return;
  58706. }
  58707. };
  58708. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58709. ViveController.MODEL_FILENAME = 'wand.babylon';
  58710. return ViveController;
  58711. }(BABYLON.WebVRController));
  58712. BABYLON.ViveController = ViveController;
  58713. })(BABYLON || (BABYLON = {}));
  58714. //# sourceMappingURL=babylon.viveController.js.map
  58715. var BABYLON;
  58716. (function (BABYLON) {
  58717. var GenericController = /** @class */ (function (_super) {
  58718. __extends(GenericController, _super);
  58719. function GenericController(vrGamepad) {
  58720. return _super.call(this, vrGamepad) || this;
  58721. }
  58722. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58723. var _this = this;
  58724. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58725. _this._defaultModel = newMeshes[1];
  58726. _this.attachToMesh(_this._defaultModel);
  58727. if (meshLoaded) {
  58728. meshLoaded(_this._defaultModel);
  58729. }
  58730. });
  58731. };
  58732. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58733. console.log("Button id: " + buttonIdx + "state: ");
  58734. console.dir(state);
  58735. };
  58736. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58737. GenericController.MODEL_FILENAME = 'generic.babylon';
  58738. return GenericController;
  58739. }(BABYLON.WebVRController));
  58740. BABYLON.GenericController = GenericController;
  58741. })(BABYLON || (BABYLON = {}));
  58742. //# sourceMappingURL=babylon.genericController.js.map
  58743. var BABYLON;
  58744. (function (BABYLON) {
  58745. var LoadedMeshInfo = /** @class */ (function () {
  58746. function LoadedMeshInfo() {
  58747. this.buttonMeshes = {};
  58748. this.axisMeshes = {};
  58749. }
  58750. return LoadedMeshInfo;
  58751. }());
  58752. var WindowsMotionController = /** @class */ (function (_super) {
  58753. __extends(WindowsMotionController, _super);
  58754. function WindowsMotionController(vrGamepad) {
  58755. var _this = _super.call(this, vrGamepad) || this;
  58756. _this._mapping = {
  58757. // Semantic button names
  58758. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58759. // A mapping of the button name to glTF model node name
  58760. // that should be transformed by button value.
  58761. buttonMeshNames: {
  58762. 'trigger': 'SELECT',
  58763. 'menu': 'MENU',
  58764. 'grip': 'GRASP',
  58765. 'thumbstick': 'THUMBSTICK_PRESS',
  58766. 'trackpad': 'TOUCHPAD_PRESS'
  58767. },
  58768. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58769. buttonObservableNames: {
  58770. 'trigger': 'onTriggerStateChangedObservable',
  58771. 'menu': 'onSecondaryButtonStateChangedObservable',
  58772. 'grip': 'onMainButtonStateChangedObservable',
  58773. 'thumbstick': 'onPadStateChangedObservable',
  58774. 'trackpad': 'onTrackpadChangedObservable'
  58775. },
  58776. // A mapping of the axis name to glTF model node name
  58777. // that should be transformed by axis value.
  58778. // This array mirrors the browserGamepad.axes array, such that
  58779. // the mesh corresponding to axis 0 is in this array index 0.
  58780. axisMeshNames: [
  58781. 'THUMBSTICK_X',
  58782. 'THUMBSTICK_Y',
  58783. 'TOUCHPAD_TOUCH_X',
  58784. 'TOUCHPAD_TOUCH_Y'
  58785. ],
  58786. pointingPoseMeshName: 'POINTING_POSE'
  58787. };
  58788. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58789. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58790. _this.trackpad = { x: 0, y: 0 };
  58791. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58792. _this._loadedMeshInfo = null;
  58793. return _this;
  58794. }
  58795. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58796. get: function () {
  58797. return this.onTriggerStateChangedObservable;
  58798. },
  58799. enumerable: true,
  58800. configurable: true
  58801. });
  58802. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58803. get: function () {
  58804. return this.onSecondaryButtonStateChangedObservable;
  58805. },
  58806. enumerable: true,
  58807. configurable: true
  58808. });
  58809. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58810. get: function () {
  58811. return this.onMainButtonStateChangedObservable;
  58812. },
  58813. enumerable: true,
  58814. configurable: true
  58815. });
  58816. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58817. get: function () {
  58818. return this.onPadStateChangedObservable;
  58819. },
  58820. enumerable: true,
  58821. configurable: true
  58822. });
  58823. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58824. get: function () {
  58825. return this.onTrackpadChangedObservable;
  58826. },
  58827. enumerable: true,
  58828. configurable: true
  58829. });
  58830. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58831. get: function () {
  58832. return this.onTrackpadValuesChangedObservable;
  58833. },
  58834. enumerable: true,
  58835. configurable: true
  58836. });
  58837. /**
  58838. * Called once per frame by the engine.
  58839. */
  58840. WindowsMotionController.prototype.update = function () {
  58841. _super.prototype.update.call(this);
  58842. // Only need to animate axes if there is a loaded mesh
  58843. if (this._loadedMeshInfo) {
  58844. if (this.browserGamepad.axes) {
  58845. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  58846. this.trackpad.x = this.browserGamepad["axes"][2];
  58847. this.trackpad.y = this.browserGamepad["axes"][3];
  58848. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  58849. }
  58850. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  58851. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  58852. }
  58853. }
  58854. }
  58855. };
  58856. /**
  58857. * Called once for each button that changed state since the last frame
  58858. * @param buttonIdx Which button index changed
  58859. * @param state New state of the button
  58860. * @param changes Which properties on the state changed since last frame
  58861. */
  58862. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58863. var buttonName = this._mapping.buttons[buttonIdx];
  58864. if (!buttonName) {
  58865. return;
  58866. }
  58867. // Only emit events for buttons that we know how to map from index to name
  58868. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  58869. if (observable) {
  58870. observable.notifyObservers(state);
  58871. }
  58872. this.lerpButtonTransform(buttonName, state.value);
  58873. };
  58874. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  58875. // If there is no loaded mesh, there is nothing to transform.
  58876. if (!this._loadedMeshInfo) {
  58877. return;
  58878. }
  58879. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  58880. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58881. return;
  58882. }
  58883. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  58884. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  58885. };
  58886. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  58887. if (!this._loadedMeshInfo) {
  58888. return;
  58889. }
  58890. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  58891. if (!meshInfo) {
  58892. return;
  58893. }
  58894. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58895. return;
  58896. }
  58897. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  58898. var lerpValue = axisValue * 0.5 + 0.5;
  58899. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  58900. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  58901. };
  58902. /**
  58903. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  58904. * @param scene scene in which to add meshes
  58905. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  58906. */
  58907. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  58908. var _this = this;
  58909. if (forceDefault === void 0) { forceDefault = false; }
  58910. var path;
  58911. var filename;
  58912. // Checking if GLB loader is present
  58913. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  58914. // Determine the device specific folder based on the ID suffix
  58915. var device = 'default';
  58916. if (this.id && !forceDefault) {
  58917. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  58918. device = ((match && match[0]) || device);
  58919. }
  58920. // Hand
  58921. if (this.hand === 'left') {
  58922. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  58923. }
  58924. else {
  58925. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  58926. }
  58927. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  58928. }
  58929. else {
  58930. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  58931. path = BABYLON.GenericController.MODEL_BASE_URL;
  58932. filename = BABYLON.GenericController.MODEL_FILENAME;
  58933. }
  58934. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  58935. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  58936. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  58937. if (!_this._loadedMeshInfo) {
  58938. return;
  58939. }
  58940. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  58941. _this.attachToMesh(_this._defaultModel);
  58942. if (meshLoaded) {
  58943. meshLoaded(_this._defaultModel);
  58944. }
  58945. }, null, function (scene, message) {
  58946. BABYLON.Tools.Log(message);
  58947. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  58948. if (!forceDefault) {
  58949. _this.initControllerMesh(scene, meshLoaded, true);
  58950. }
  58951. });
  58952. };
  58953. /**
  58954. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  58955. * can be transformed by button presses and axes values, based on this._mapping.
  58956. *
  58957. * @param scene scene in which the meshes exist
  58958. * @param meshes list of meshes that make up the controller model to process
  58959. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  58960. */
  58961. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  58962. var loadedMeshInfo = null;
  58963. // Create a new mesh to contain the glTF hierarchy
  58964. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  58965. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  58966. var childMesh = null;
  58967. for (var i = 0; i < meshes.length; i++) {
  58968. var mesh = meshes[i];
  58969. if (!mesh.parent) {
  58970. // Exclude controller meshes from picking results
  58971. mesh.isPickable = false;
  58972. // Handle root node, attach to the new parentMesh
  58973. childMesh = mesh;
  58974. break;
  58975. }
  58976. }
  58977. if (childMesh) {
  58978. childMesh.setParent(parentMesh);
  58979. // Create our mesh info. Note that this method will always return non-null.
  58980. loadedMeshInfo = this.createMeshInfo(parentMesh);
  58981. }
  58982. else {
  58983. BABYLON.Tools.Warn('Could not find root node in model file.');
  58984. }
  58985. return loadedMeshInfo;
  58986. };
  58987. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  58988. var loadedMeshInfo = new LoadedMeshInfo();
  58989. var i;
  58990. loadedMeshInfo.rootNode = rootNode;
  58991. // Reset the caches
  58992. loadedMeshInfo.buttonMeshes = {};
  58993. loadedMeshInfo.axisMeshes = {};
  58994. // Button Meshes
  58995. for (i = 0; i < this._mapping.buttons.length; i++) {
  58996. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  58997. if (!buttonMeshName) {
  58998. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  58999. continue;
  59000. }
  59001. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  59002. if (!buttonMesh) {
  59003. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  59004. continue;
  59005. }
  59006. var buttonMeshInfo = {
  59007. index: i,
  59008. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  59009. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  59010. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  59011. };
  59012. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  59013. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  59014. }
  59015. else {
  59016. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  59017. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  59018. '(VALUE: ' + !!buttonMeshInfo.value +
  59019. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  59020. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  59021. ')');
  59022. }
  59023. }
  59024. // Axis Meshes
  59025. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  59026. var axisMeshName = this._mapping.axisMeshNames[i];
  59027. if (!axisMeshName) {
  59028. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  59029. continue;
  59030. }
  59031. var axisMesh = getChildByName(rootNode, axisMeshName);
  59032. if (!axisMesh) {
  59033. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  59034. continue;
  59035. }
  59036. var axisMeshInfo = {
  59037. index: i,
  59038. value: getImmediateChildByName(axisMesh, 'VALUE'),
  59039. min: getImmediateChildByName(axisMesh, 'MIN'),
  59040. max: getImmediateChildByName(axisMesh, 'MAX')
  59041. };
  59042. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  59043. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  59044. }
  59045. else {
  59046. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  59047. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  59048. '(VALUE: ' + !!axisMeshInfo.value +
  59049. ', MIN: ' + !!axisMeshInfo.min +
  59050. ', MAX:' + !!axisMeshInfo.max +
  59051. ')');
  59052. }
  59053. }
  59054. // Pointing Ray
  59055. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  59056. if (!loadedMeshInfo.pointingPoseNode) {
  59057. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  59058. }
  59059. return loadedMeshInfo;
  59060. // Look through all children recursively. This will return null if no mesh exists with the given name.
  59061. function getChildByName(node, name) {
  59062. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  59063. }
  59064. // Look through only immediate children. This will return null if no mesh exists with the given name.
  59065. function getImmediateChildByName(node, name) {
  59066. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  59067. }
  59068. };
  59069. WindowsMotionController.prototype.getForwardRay = function (length) {
  59070. if (length === void 0) { length = 100; }
  59071. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  59072. return _super.prototype.getForwardRay.call(this, length);
  59073. }
  59074. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  59075. var origin = m.getTranslation();
  59076. var forward = new BABYLON.Vector3(0, 0, -1);
  59077. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  59078. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  59079. return new BABYLON.Ray(origin, direction, length);
  59080. };
  59081. WindowsMotionController.prototype.dispose = function () {
  59082. _super.prototype.dispose.call(this);
  59083. this.onTrackpadChangedObservable.clear();
  59084. };
  59085. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  59086. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  59087. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  59088. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  59089. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  59090. return WindowsMotionController;
  59091. }(BABYLON.WebVRController));
  59092. BABYLON.WindowsMotionController = WindowsMotionController;
  59093. })(BABYLON || (BABYLON = {}));
  59094. //# sourceMappingURL=babylon.windowsMotionController.js.map
  59095. var BABYLON;
  59096. (function (BABYLON) {
  59097. var GearVRController = /** @class */ (function (_super) {
  59098. __extends(GearVRController, _super);
  59099. function GearVRController(vrGamepad) {
  59100. var _this = _super.call(this, vrGamepad) || this;
  59101. _this._buttonIndexToObservableNameMap = [
  59102. 'onTrackpadChangedObservable',
  59103. 'onTriggerStateChangedObservable' // Trigger
  59104. ];
  59105. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  59106. return _this;
  59107. }
  59108. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  59109. var _this = this;
  59110. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  59111. _this._defaultModel = newMeshes[1];
  59112. _this.attachToMesh(_this._defaultModel);
  59113. if (meshLoaded) {
  59114. meshLoaded(_this._defaultModel);
  59115. }
  59116. });
  59117. };
  59118. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  59119. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  59120. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  59121. // Only emit events for buttons that we know how to map from index to observable
  59122. var observable = this[observableName];
  59123. if (observable) {
  59124. observable.notifyObservers(state);
  59125. }
  59126. }
  59127. };
  59128. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  59129. GearVRController.MODEL_FILENAME = 'generic.babylon';
  59130. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  59131. return GearVRController;
  59132. }(BABYLON.WebVRController));
  59133. BABYLON.GearVRController = GearVRController;
  59134. })(BABYLON || (BABYLON = {}));
  59135. //# sourceMappingURL=babylon.gearVRController.js.map
  59136. var BABYLON;
  59137. (function (BABYLON) {
  59138. var FollowCamera = /** @class */ (function (_super) {
  59139. __extends(FollowCamera, _super);
  59140. function FollowCamera(name, position, scene, lockedTarget) {
  59141. if (lockedTarget === void 0) { lockedTarget = null; }
  59142. var _this = _super.call(this, name, position, scene) || this;
  59143. _this.radius = 12;
  59144. _this.rotationOffset = 0;
  59145. _this.heightOffset = 4;
  59146. _this.cameraAcceleration = 0.05;
  59147. _this.maxCameraSpeed = 20;
  59148. _this.lockedTarget = lockedTarget;
  59149. return _this;
  59150. }
  59151. FollowCamera.prototype.getRadians = function (degrees) {
  59152. return degrees * Math.PI / 180;
  59153. };
  59154. FollowCamera.prototype.follow = function (cameraTarget) {
  59155. if (!cameraTarget)
  59156. return;
  59157. var yRotation;
  59158. if (cameraTarget.rotationQuaternion) {
  59159. var rotMatrix = new BABYLON.Matrix();
  59160. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  59161. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  59162. }
  59163. else {
  59164. yRotation = cameraTarget.rotation.y;
  59165. }
  59166. var radians = this.getRadians(this.rotationOffset) + yRotation;
  59167. var targetPosition = cameraTarget.getAbsolutePosition();
  59168. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  59169. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  59170. var dx = targetX - this.position.x;
  59171. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  59172. var dz = (targetZ) - this.position.z;
  59173. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  59174. var vy = dy * this.cameraAcceleration;
  59175. var vz = dz * this.cameraAcceleration * 2;
  59176. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  59177. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59178. }
  59179. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  59180. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59181. }
  59182. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  59183. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  59184. }
  59185. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  59186. this.setTarget(targetPosition);
  59187. };
  59188. FollowCamera.prototype._checkInputs = function () {
  59189. _super.prototype._checkInputs.call(this);
  59190. if (this.lockedTarget) {
  59191. this.follow(this.lockedTarget);
  59192. }
  59193. };
  59194. FollowCamera.prototype.getClassName = function () {
  59195. return "FollowCamera";
  59196. };
  59197. __decorate([
  59198. BABYLON.serialize()
  59199. ], FollowCamera.prototype, "radius", void 0);
  59200. __decorate([
  59201. BABYLON.serialize()
  59202. ], FollowCamera.prototype, "rotationOffset", void 0);
  59203. __decorate([
  59204. BABYLON.serialize()
  59205. ], FollowCamera.prototype, "heightOffset", void 0);
  59206. __decorate([
  59207. BABYLON.serialize()
  59208. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  59209. __decorate([
  59210. BABYLON.serialize()
  59211. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  59212. __decorate([
  59213. BABYLON.serializeAsMeshReference("lockedTargetId")
  59214. ], FollowCamera.prototype, "lockedTarget", void 0);
  59215. return FollowCamera;
  59216. }(BABYLON.TargetCamera));
  59217. BABYLON.FollowCamera = FollowCamera;
  59218. var ArcFollowCamera = /** @class */ (function (_super) {
  59219. __extends(ArcFollowCamera, _super);
  59220. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  59221. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  59222. _this.alpha = alpha;
  59223. _this.beta = beta;
  59224. _this.radius = radius;
  59225. _this.target = target;
  59226. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  59227. _this.follow();
  59228. return _this;
  59229. }
  59230. ArcFollowCamera.prototype.follow = function () {
  59231. if (!this.target) {
  59232. return;
  59233. }
  59234. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  59235. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  59236. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  59237. var targetPosition = this.target.getAbsolutePosition();
  59238. this.position = targetPosition.add(this._cartesianCoordinates);
  59239. this.setTarget(targetPosition);
  59240. };
  59241. ArcFollowCamera.prototype._checkInputs = function () {
  59242. _super.prototype._checkInputs.call(this);
  59243. this.follow();
  59244. };
  59245. ArcFollowCamera.prototype.getClassName = function () {
  59246. return "ArcFollowCamera";
  59247. };
  59248. return ArcFollowCamera;
  59249. }(BABYLON.TargetCamera));
  59250. BABYLON.ArcFollowCamera = ArcFollowCamera;
  59251. })(BABYLON || (BABYLON = {}));
  59252. //# sourceMappingURL=babylon.followCamera.js.map
  59253. var BABYLON;
  59254. (function (BABYLON) {
  59255. // We're mainly based on the logic defined into the FreeCamera code
  59256. var UniversalCamera = /** @class */ (function (_super) {
  59257. __extends(UniversalCamera, _super);
  59258. //-- end properties for backward compatibility for inputs
  59259. function UniversalCamera(name, position, scene) {
  59260. var _this = _super.call(this, name, position, scene) || this;
  59261. _this.inputs.addGamepad();
  59262. return _this;
  59263. }
  59264. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  59265. //-- Begin properties for backward compatibility for inputs
  59266. get: function () {
  59267. var gamepad = this.inputs.attached["gamepad"];
  59268. if (gamepad)
  59269. return gamepad.gamepadAngularSensibility;
  59270. return 0;
  59271. },
  59272. set: function (value) {
  59273. var gamepad = this.inputs.attached["gamepad"];
  59274. if (gamepad)
  59275. gamepad.gamepadAngularSensibility = value;
  59276. },
  59277. enumerable: true,
  59278. configurable: true
  59279. });
  59280. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  59281. get: function () {
  59282. var gamepad = this.inputs.attached["gamepad"];
  59283. if (gamepad)
  59284. return gamepad.gamepadMoveSensibility;
  59285. return 0;
  59286. },
  59287. set: function (value) {
  59288. var gamepad = this.inputs.attached["gamepad"];
  59289. if (gamepad)
  59290. gamepad.gamepadMoveSensibility = value;
  59291. },
  59292. enumerable: true,
  59293. configurable: true
  59294. });
  59295. UniversalCamera.prototype.getClassName = function () {
  59296. return "UniversalCamera";
  59297. };
  59298. return UniversalCamera;
  59299. }(BABYLON.TouchCamera));
  59300. BABYLON.UniversalCamera = UniversalCamera;
  59301. })(BABYLON || (BABYLON = {}));
  59302. //# sourceMappingURL=babylon.universalCamera.js.map
  59303. var BABYLON;
  59304. (function (BABYLON) {
  59305. // We're mainly based on the logic defined into the FreeCamera code
  59306. var GamepadCamera = /** @class */ (function (_super) {
  59307. __extends(GamepadCamera, _super);
  59308. //-- end properties for backward compatibility for inputs
  59309. function GamepadCamera(name, position, scene) {
  59310. return _super.call(this, name, position, scene) || this;
  59311. }
  59312. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  59313. //-- Begin properties for backward compatibility for inputs
  59314. get: function () {
  59315. var gamepad = this.inputs.attached["gamepad"];
  59316. if (gamepad)
  59317. return gamepad.gamepadAngularSensibility;
  59318. return 0;
  59319. },
  59320. set: function (value) {
  59321. var gamepad = this.inputs.attached["gamepad"];
  59322. if (gamepad)
  59323. gamepad.gamepadAngularSensibility = value;
  59324. },
  59325. enumerable: true,
  59326. configurable: true
  59327. });
  59328. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  59329. get: function () {
  59330. var gamepad = this.inputs.attached["gamepad"];
  59331. if (gamepad)
  59332. return gamepad.gamepadMoveSensibility;
  59333. return 0;
  59334. },
  59335. set: function (value) {
  59336. var gamepad = this.inputs.attached["gamepad"];
  59337. if (gamepad)
  59338. gamepad.gamepadMoveSensibility = value;
  59339. },
  59340. enumerable: true,
  59341. configurable: true
  59342. });
  59343. GamepadCamera.prototype.getClassName = function () {
  59344. return "GamepadCamera";
  59345. };
  59346. return GamepadCamera;
  59347. }(BABYLON.UniversalCamera));
  59348. BABYLON.GamepadCamera = GamepadCamera;
  59349. })(BABYLON || (BABYLON = {}));
  59350. //# sourceMappingURL=babylon.gamepadCamera.js.map
  59351. var BABYLON;
  59352. (function (BABYLON) {
  59353. var PostProcessRenderPipelineManager = /** @class */ (function () {
  59354. function PostProcessRenderPipelineManager() {
  59355. this._renderPipelines = {};
  59356. }
  59357. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  59358. this._renderPipelines[renderPipeline._name] = renderPipeline;
  59359. };
  59360. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  59361. if (unique === void 0) { unique = false; }
  59362. var renderPipeline = this._renderPipelines[renderPipelineName];
  59363. if (!renderPipeline) {
  59364. return;
  59365. }
  59366. renderPipeline._attachCameras(cameras, unique);
  59367. };
  59368. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  59369. var renderPipeline = this._renderPipelines[renderPipelineName];
  59370. if (!renderPipeline) {
  59371. return;
  59372. }
  59373. renderPipeline._detachCameras(cameras);
  59374. };
  59375. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59376. var renderPipeline = this._renderPipelines[renderPipelineName];
  59377. if (!renderPipeline) {
  59378. return;
  59379. }
  59380. renderPipeline._enableEffect(renderEffectName, cameras);
  59381. };
  59382. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  59383. var renderPipeline = this._renderPipelines[renderPipelineName];
  59384. if (!renderPipeline) {
  59385. return;
  59386. }
  59387. renderPipeline._disableEffect(renderEffectName, cameras);
  59388. };
  59389. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  59390. var renderPipeline = this._renderPipelines[renderPipelineName];
  59391. if (!renderPipeline) {
  59392. return;
  59393. }
  59394. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  59395. };
  59396. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  59397. var renderPipeline = this._renderPipelines[renderPipelineName];
  59398. if (!renderPipeline) {
  59399. return;
  59400. }
  59401. renderPipeline._disableDisplayOnlyPass(cameras);
  59402. };
  59403. PostProcessRenderPipelineManager.prototype.update = function () {
  59404. for (var renderPipelineName in this._renderPipelines) {
  59405. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59406. var pipeline = this._renderPipelines[renderPipelineName];
  59407. if (!pipeline.isSupported) {
  59408. pipeline.dispose();
  59409. delete this._renderPipelines[renderPipelineName];
  59410. }
  59411. else {
  59412. pipeline._update();
  59413. }
  59414. }
  59415. }
  59416. };
  59417. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  59418. for (var renderPipelineName in this._renderPipelines) {
  59419. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59420. var pipeline = this._renderPipelines[renderPipelineName];
  59421. pipeline._rebuild();
  59422. }
  59423. }
  59424. };
  59425. PostProcessRenderPipelineManager.prototype.dispose = function () {
  59426. for (var renderPipelineName in this._renderPipelines) {
  59427. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  59428. var pipeline = this._renderPipelines[renderPipelineName];
  59429. pipeline.dispose();
  59430. }
  59431. }
  59432. };
  59433. return PostProcessRenderPipelineManager;
  59434. }());
  59435. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  59436. })(BABYLON || (BABYLON = {}));
  59437. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  59438. var BABYLON;
  59439. (function (BABYLON) {
  59440. var PostProcessRenderPass = /** @class */ (function () {
  59441. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  59442. this._refCount = 0;
  59443. this._name = name;
  59444. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  59445. this.setRenderList(renderList);
  59446. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  59447. this._renderTexture.onAfterRenderObservable.add(afterRender);
  59448. this._scene = scene;
  59449. this._renderList = renderList;
  59450. }
  59451. // private
  59452. PostProcessRenderPass.prototype._incRefCount = function () {
  59453. if (this._refCount === 0) {
  59454. this._scene.customRenderTargets.push(this._renderTexture);
  59455. }
  59456. return ++this._refCount;
  59457. };
  59458. PostProcessRenderPass.prototype._decRefCount = function () {
  59459. this._refCount--;
  59460. if (this._refCount <= 0) {
  59461. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  59462. }
  59463. return this._refCount;
  59464. };
  59465. PostProcessRenderPass.prototype._update = function () {
  59466. this.setRenderList(this._renderList);
  59467. };
  59468. // public
  59469. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  59470. this._renderTexture.renderList = renderList;
  59471. };
  59472. PostProcessRenderPass.prototype.getRenderTexture = function () {
  59473. return this._renderTexture;
  59474. };
  59475. return PostProcessRenderPass;
  59476. }());
  59477. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  59478. })(BABYLON || (BABYLON = {}));
  59479. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  59480. var BABYLON;
  59481. (function (BABYLON) {
  59482. var PostProcessRenderEffect = /** @class */ (function () {
  59483. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  59484. this._name = name;
  59485. this._singleInstance = singleInstance || true;
  59486. this._getPostProcess = getPostProcess;
  59487. this._cameras = {};
  59488. this._indicesForCamera = {};
  59489. this._postProcesses = {};
  59490. this._renderPasses = {};
  59491. this._renderEffectAsPasses = {};
  59492. }
  59493. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  59494. get: function () {
  59495. for (var index in this._postProcesses) {
  59496. if (!this._postProcesses[index].isSupported) {
  59497. return false;
  59498. }
  59499. }
  59500. return true;
  59501. },
  59502. enumerable: true,
  59503. configurable: true
  59504. });
  59505. PostProcessRenderEffect.prototype._update = function () {
  59506. for (var renderPassName in this._renderPasses) {
  59507. this._renderPasses[renderPassName]._update();
  59508. }
  59509. };
  59510. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  59511. this._renderPasses[renderPass._name] = renderPass;
  59512. this._linkParameters();
  59513. };
  59514. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  59515. delete this._renderPasses[renderPass._name];
  59516. this._linkParameters();
  59517. };
  59518. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  59519. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  59520. this._linkParameters();
  59521. };
  59522. PostProcessRenderEffect.prototype.getPass = function (passName) {
  59523. for (var renderPassName in this._renderPasses) {
  59524. if (renderPassName === passName) {
  59525. return this._renderPasses[passName];
  59526. }
  59527. }
  59528. return null;
  59529. };
  59530. PostProcessRenderEffect.prototype.emptyPasses = function () {
  59531. this._renderPasses = {};
  59532. this._linkParameters();
  59533. };
  59534. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  59535. var cameraKey;
  59536. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59537. if (!cams) {
  59538. return;
  59539. }
  59540. for (var i = 0; i < cams.length; i++) {
  59541. var camera = cams[i];
  59542. var cameraName = camera.name;
  59543. if (this._singleInstance) {
  59544. cameraKey = 0;
  59545. }
  59546. else {
  59547. cameraKey = cameraName;
  59548. }
  59549. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  59550. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  59551. if (!this._indicesForCamera[cameraName]) {
  59552. this._indicesForCamera[cameraName] = [];
  59553. }
  59554. this._indicesForCamera[cameraName].push(index);
  59555. if (!this._cameras[cameraName]) {
  59556. this._cameras[cameraName] = camera;
  59557. }
  59558. for (var passName in this._renderPasses) {
  59559. this._renderPasses[passName]._incRefCount();
  59560. }
  59561. }
  59562. this._linkParameters();
  59563. };
  59564. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  59565. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59566. if (!cams) {
  59567. return;
  59568. }
  59569. for (var i = 0; i < cams.length; i++) {
  59570. var camera = cams[i];
  59571. var cameraName = camera.name;
  59572. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59573. if (this._cameras[cameraName]) {
  59574. //this._indicesForCamera.splice(index, 1);
  59575. this._cameras[cameraName] = null;
  59576. }
  59577. for (var passName in this._renderPasses) {
  59578. this._renderPasses[passName]._decRefCount();
  59579. }
  59580. }
  59581. };
  59582. PostProcessRenderEffect.prototype._enable = function (cameras) {
  59583. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59584. if (!cams) {
  59585. return;
  59586. }
  59587. for (var i = 0; i < cams.length; i++) {
  59588. var camera = cams[i];
  59589. var cameraName = camera.name;
  59590. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  59591. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  59592. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  59593. }
  59594. }
  59595. for (var passName in this._renderPasses) {
  59596. this._renderPasses[passName]._incRefCount();
  59597. }
  59598. }
  59599. };
  59600. PostProcessRenderEffect.prototype._disable = function (cameras) {
  59601. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59602. if (!cams) {
  59603. return;
  59604. }
  59605. for (var i = 0; i < cams.length; i++) {
  59606. var camera = cams[i];
  59607. var cameraName = camera.Name;
  59608. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  59609. for (var passName in this._renderPasses) {
  59610. this._renderPasses[passName]._decRefCount();
  59611. }
  59612. }
  59613. };
  59614. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  59615. if (this._singleInstance) {
  59616. return this._postProcesses[0];
  59617. }
  59618. else {
  59619. if (!camera) {
  59620. return null;
  59621. }
  59622. return this._postProcesses[camera.name];
  59623. }
  59624. };
  59625. PostProcessRenderEffect.prototype._linkParameters = function () {
  59626. var _this = this;
  59627. for (var index in this._postProcesses) {
  59628. if (this.applyParameters) {
  59629. this.applyParameters(this._postProcesses[index]);
  59630. }
  59631. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  59632. _this._linkTextures(effect);
  59633. });
  59634. }
  59635. };
  59636. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  59637. for (var renderPassName in this._renderPasses) {
  59638. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  59639. }
  59640. for (var renderEffectName in this._renderEffectAsPasses) {
  59641. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  59642. }
  59643. };
  59644. return PostProcessRenderEffect;
  59645. }());
  59646. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  59647. })(BABYLON || (BABYLON = {}));
  59648. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  59649. var BABYLON;
  59650. (function (BABYLON) {
  59651. var PostProcessRenderPipeline = /** @class */ (function () {
  59652. function PostProcessRenderPipeline(engine, name) {
  59653. this._engine = engine;
  59654. this._name = name;
  59655. this._renderEffects = {};
  59656. this._renderEffectsForIsolatedPass = new Array();
  59657. this._cameras = [];
  59658. }
  59659. PostProcessRenderPipeline.prototype.getClassName = function () {
  59660. return "PostProcessRenderPipeline";
  59661. };
  59662. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  59663. get: function () {
  59664. for (var renderEffectName in this._renderEffects) {
  59665. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59666. if (!this._renderEffects[renderEffectName].isSupported) {
  59667. return false;
  59668. }
  59669. }
  59670. }
  59671. return true;
  59672. },
  59673. enumerable: true,
  59674. configurable: true
  59675. });
  59676. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  59677. this._renderEffects[renderEffect._name] = renderEffect;
  59678. };
  59679. // private
  59680. PostProcessRenderPipeline.prototype._rebuild = function () {
  59681. };
  59682. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  59683. var renderEffects = this._renderEffects[renderEffectName];
  59684. if (!renderEffects) {
  59685. return;
  59686. }
  59687. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59688. };
  59689. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  59690. var renderEffects = this._renderEffects[renderEffectName];
  59691. if (!renderEffects) {
  59692. return;
  59693. }
  59694. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  59695. };
  59696. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  59697. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59698. if (!cams) {
  59699. return;
  59700. }
  59701. var indicesToDelete = [];
  59702. var i;
  59703. for (i = 0; i < cams.length; i++) {
  59704. var camera = cams[i];
  59705. var cameraName = camera.name;
  59706. if (this._cameras.indexOf(camera) === -1) {
  59707. this._cameras[cameraName] = camera;
  59708. }
  59709. else if (unique) {
  59710. indicesToDelete.push(i);
  59711. }
  59712. }
  59713. for (i = 0; i < indicesToDelete.length; i++) {
  59714. cameras.splice(indicesToDelete[i], 1);
  59715. }
  59716. for (var renderEffectName in this._renderEffects) {
  59717. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59718. this._renderEffects[renderEffectName]._attachCameras(cams);
  59719. }
  59720. }
  59721. };
  59722. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59723. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59724. if (!cams) {
  59725. return;
  59726. }
  59727. for (var renderEffectName in this._renderEffects) {
  59728. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59729. this._renderEffects[renderEffectName]._detachCameras(cams);
  59730. }
  59731. }
  59732. for (var i = 0; i < cams.length; i++) {
  59733. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59734. }
  59735. };
  59736. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59737. var _this = this;
  59738. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59739. if (!cams) {
  59740. return;
  59741. }
  59742. var pass = null;
  59743. var renderEffectName;
  59744. for (renderEffectName in this._renderEffects) {
  59745. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59746. pass = this._renderEffects[renderEffectName].getPass(passName);
  59747. if (pass != null) {
  59748. break;
  59749. }
  59750. }
  59751. }
  59752. if (pass === null) {
  59753. return;
  59754. }
  59755. for (renderEffectName in this._renderEffects) {
  59756. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59757. this._renderEffects[renderEffectName]._disable(cams);
  59758. }
  59759. }
  59760. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59761. for (var i = 0; i < cams.length; i++) {
  59762. var camera = cams[i];
  59763. var cameraName = camera.name;
  59764. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59765. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59766. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59767. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59768. }
  59769. };
  59770. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59771. var _this = this;
  59772. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59773. if (!cams) {
  59774. return;
  59775. }
  59776. for (var i = 0; i < cams.length; i++) {
  59777. var camera = cams[i];
  59778. var cameraName = camera.name;
  59779. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59780. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59781. }
  59782. for (var renderEffectName in this._renderEffects) {
  59783. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59784. this._renderEffects[renderEffectName]._enable(cams);
  59785. }
  59786. }
  59787. };
  59788. PostProcessRenderPipeline.prototype._update = function () {
  59789. for (var renderEffectName in this._renderEffects) {
  59790. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59791. this._renderEffects[renderEffectName]._update();
  59792. }
  59793. }
  59794. for (var i = 0; i < this._cameras.length; i++) {
  59795. var cameraName = this._cameras[i].name;
  59796. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59797. this._renderEffectsForIsolatedPass[cameraName]._update();
  59798. }
  59799. }
  59800. };
  59801. PostProcessRenderPipeline.prototype._reset = function () {
  59802. this._renderEffects = {};
  59803. this._renderEffectsForIsolatedPass = new Array();
  59804. };
  59805. PostProcessRenderPipeline.prototype.dispose = function () {
  59806. // Must be implemented by children
  59807. };
  59808. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59809. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59810. __decorate([
  59811. BABYLON.serialize()
  59812. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59813. return PostProcessRenderPipeline;
  59814. }());
  59815. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59816. })(BABYLON || (BABYLON = {}));
  59817. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59818. var BABYLON;
  59819. (function (BABYLON) {
  59820. var DepthRenderer = /** @class */ (function () {
  59821. function DepthRenderer(scene, type) {
  59822. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59823. var _this = this;
  59824. this._scene = scene;
  59825. var engine = scene.getEngine();
  59826. // Render target
  59827. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59828. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59829. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59830. this._depthMap.refreshRate = 1;
  59831. this._depthMap.renderParticles = false;
  59832. this._depthMap.renderList = null;
  59833. // set default depth value to 1.0 (far away)
  59834. this._depthMap.onClearObservable.add(function (engine) {
  59835. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59836. });
  59837. // Custom render function
  59838. var renderSubMesh = function (subMesh) {
  59839. var mesh = subMesh.getRenderingMesh();
  59840. var scene = _this._scene;
  59841. var engine = scene.getEngine();
  59842. var material = subMesh.getMaterial();
  59843. if (!material) {
  59844. return;
  59845. }
  59846. // Culling and reverse (right handed system)
  59847. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  59848. // Managing instances
  59849. var batch = mesh._getInstancesRenderList(subMesh._id);
  59850. if (batch.mustReturn) {
  59851. return;
  59852. }
  59853. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59854. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  59855. engine.enableEffect(_this._effect);
  59856. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59857. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59858. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  59859. // Alpha test
  59860. if (material && material.needAlphaTesting()) {
  59861. var alphaTexture = material.getAlphaTestTexture();
  59862. if (alphaTexture) {
  59863. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59864. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59865. }
  59866. }
  59867. // Bones
  59868. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59869. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59870. }
  59871. // Draw
  59872. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59873. }
  59874. };
  59875. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59876. var index;
  59877. if (depthOnlySubMeshes.length) {
  59878. engine.setColorWrite(false);
  59879. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59880. renderSubMesh(depthOnlySubMeshes.data[index]);
  59881. }
  59882. engine.setColorWrite(true);
  59883. }
  59884. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59885. renderSubMesh(opaqueSubMeshes.data[index]);
  59886. }
  59887. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59888. renderSubMesh(alphaTestSubMeshes.data[index]);
  59889. }
  59890. };
  59891. }
  59892. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  59893. var material = subMesh.getMaterial();
  59894. if (material.disableDepthWrite) {
  59895. return false;
  59896. }
  59897. var defines = [];
  59898. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59899. var mesh = subMesh.getMesh();
  59900. // Alpha test
  59901. if (material && material.needAlphaTesting()) {
  59902. defines.push("#define ALPHATEST");
  59903. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59904. attribs.push(BABYLON.VertexBuffer.UVKind);
  59905. defines.push("#define UV1");
  59906. }
  59907. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59908. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59909. defines.push("#define UV2");
  59910. }
  59911. }
  59912. // Bones
  59913. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59914. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59915. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59916. if (mesh.numBoneInfluencers > 4) {
  59917. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59918. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59919. }
  59920. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59921. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59922. }
  59923. else {
  59924. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59925. }
  59926. // Instances
  59927. if (useInstances) {
  59928. defines.push("#define INSTANCES");
  59929. attribs.push("world0");
  59930. attribs.push("world1");
  59931. attribs.push("world2");
  59932. attribs.push("world3");
  59933. }
  59934. // Get correct effect
  59935. var join = defines.join("\n");
  59936. if (this._cachedDefines !== join) {
  59937. this._cachedDefines = join;
  59938. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  59939. }
  59940. return this._effect.isReady();
  59941. };
  59942. DepthRenderer.prototype.getDepthMap = function () {
  59943. return this._depthMap;
  59944. };
  59945. // Methods
  59946. DepthRenderer.prototype.dispose = function () {
  59947. this._depthMap.dispose();
  59948. };
  59949. return DepthRenderer;
  59950. }());
  59951. BABYLON.DepthRenderer = DepthRenderer;
  59952. })(BABYLON || (BABYLON = {}));
  59953. //# sourceMappingURL=babylon.depthRenderer.js.map
  59954. var BABYLON;
  59955. (function (BABYLON) {
  59956. var SSAORenderingPipeline = /** @class */ (function (_super) {
  59957. __extends(SSAORenderingPipeline, _super);
  59958. /**
  59959. * @constructor
  59960. * @param {string} name - The rendering pipeline name
  59961. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59962. * @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 }
  59963. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59964. */
  59965. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  59966. var _this = _super.call(this, scene.getEngine(), name) || this;
  59967. // Members
  59968. /**
  59969. * The PassPostProcess id in the pipeline that contains the original scene color
  59970. * @type {string}
  59971. */
  59972. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59973. /**
  59974. * The SSAO PostProcess id in the pipeline
  59975. * @type {string}
  59976. */
  59977. _this.SSAORenderEffect = "SSAORenderEffect";
  59978. /**
  59979. * The horizontal blur PostProcess id in the pipeline
  59980. * @type {string}
  59981. */
  59982. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59983. /**
  59984. * The vertical blur PostProcess id in the pipeline
  59985. * @type {string}
  59986. */
  59987. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59988. /**
  59989. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59990. * @type {string}
  59991. */
  59992. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59993. /**
  59994. * The output strength of the SSAO post-process. Default value is 1.0.
  59995. * @type {number}
  59996. */
  59997. _this.totalStrength = 1.0;
  59998. /**
  59999. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  60000. * @type {number}
  60001. */
  60002. _this.radius = 0.0001;
  60003. /**
  60004. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  60005. * Must not be equal to fallOff and superior to fallOff.
  60006. * Default value is 0.975
  60007. * @type {number}
  60008. */
  60009. _this.area = 0.0075;
  60010. /**
  60011. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  60012. * Must not be equal to area and inferior to area.
  60013. * Default value is 0.0
  60014. * @type {number}
  60015. */
  60016. _this.fallOff = 0.000001;
  60017. /**
  60018. * The base color of the SSAO post-process
  60019. * The final result is "base + ssao" between [0, 1]
  60020. * @type {number}
  60021. */
  60022. _this.base = 0.5;
  60023. _this._firstUpdate = true;
  60024. _this._scene = scene;
  60025. // Set up assets
  60026. _this._createRandomTexture();
  60027. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60028. var ssaoRatio = ratio.ssaoRatio || ratio;
  60029. var combineRatio = ratio.combineRatio || ratio;
  60030. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60031. _this._createSSAOPostProcess(ssaoRatio);
  60032. _this._createBlurPostProcess(ssaoRatio);
  60033. _this._createSSAOCombinePostProcess(combineRatio);
  60034. // Set up pipeline
  60035. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60036. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60037. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60038. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60039. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60040. // Finish
  60041. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60042. if (cameras)
  60043. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60044. return _this;
  60045. }
  60046. // Public Methods
  60047. /**
  60048. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60049. */
  60050. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60051. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60052. for (var i = 0; i < this._scene.cameras.length; i++) {
  60053. var camera = this._scene.cameras[i];
  60054. this._originalColorPostProcess.dispose(camera);
  60055. this._ssaoPostProcess.dispose(camera);
  60056. this._blurHPostProcess.dispose(camera);
  60057. this._blurVPostProcess.dispose(camera);
  60058. this._ssaoCombinePostProcess.dispose(camera);
  60059. }
  60060. this._randomTexture.dispose();
  60061. if (disableDepthRender)
  60062. this._scene.disableDepthRenderer();
  60063. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60064. _super.prototype.dispose.call(this);
  60065. };
  60066. // Private Methods
  60067. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  60068. var _this = this;
  60069. var size = 16;
  60070. 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);
  60071. 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);
  60072. this._blurHPostProcess.onActivateObservable.add(function () {
  60073. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  60074. _this._blurHPostProcess.kernel = size * dw;
  60075. });
  60076. this._blurVPostProcess.onActivateObservable.add(function () {
  60077. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  60078. _this._blurVPostProcess.kernel = size * dw;
  60079. });
  60080. };
  60081. SSAORenderingPipeline.prototype._rebuild = function () {
  60082. this._firstUpdate = true;
  60083. _super.prototype._rebuild.call(this);
  60084. };
  60085. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60086. var _this = this;
  60087. var numSamples = 16;
  60088. var sampleSphere = [
  60089. 0.5381, 0.1856, -0.4319,
  60090. 0.1379, 0.2486, 0.4430,
  60091. 0.3371, 0.5679, -0.0057,
  60092. -0.6999, -0.0451, -0.0019,
  60093. 0.0689, -0.1598, -0.8547,
  60094. 0.0560, 0.0069, -0.1843,
  60095. -0.0146, 0.1402, 0.0762,
  60096. 0.0100, -0.1924, -0.0344,
  60097. -0.3577, -0.5301, -0.4358,
  60098. -0.3169, 0.1063, 0.0158,
  60099. 0.0103, -0.5869, 0.0046,
  60100. -0.0897, -0.4940, 0.3287,
  60101. 0.7119, -0.0154, -0.0918,
  60102. -0.0533, 0.0596, -0.5411,
  60103. 0.0352, -0.0631, 0.5460,
  60104. -0.4776, 0.2847, -0.0271
  60105. ];
  60106. var samplesFactor = 1.0 / numSamples;
  60107. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  60108. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60109. "area", "fallOff", "base", "range", "viewport"
  60110. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60111. this._ssaoPostProcess.onApply = function (effect) {
  60112. if (_this._firstUpdate) {
  60113. effect.setArray3("sampleSphere", sampleSphere);
  60114. effect.setFloat("samplesFactor", samplesFactor);
  60115. effect.setFloat("randTextureTiles", 4.0);
  60116. }
  60117. effect.setFloat("totalStrength", _this.totalStrength);
  60118. effect.setFloat("radius", _this.radius);
  60119. effect.setFloat("area", _this.area);
  60120. effect.setFloat("fallOff", _this.fallOff);
  60121. effect.setFloat("base", _this.base);
  60122. effect.setTexture("textureSampler", _this._depthTexture);
  60123. effect.setTexture("randomSampler", _this._randomTexture);
  60124. };
  60125. };
  60126. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60127. var _this = this;
  60128. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60129. this._ssaoCombinePostProcess.onApply = function (effect) {
  60130. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60131. };
  60132. };
  60133. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  60134. var size = 512;
  60135. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60136. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60137. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60138. var context = this._randomTexture.getContext();
  60139. var rand = function (min, max) {
  60140. return Math.random() * (max - min) + min;
  60141. };
  60142. var randVector = BABYLON.Vector3.Zero();
  60143. for (var x = 0; x < size; x++) {
  60144. for (var y = 0; y < size; y++) {
  60145. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  60146. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  60147. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  60148. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60149. context.fillRect(x, y, 1, 1);
  60150. }
  60151. }
  60152. this._randomTexture.update(false);
  60153. };
  60154. __decorate([
  60155. BABYLON.serialize()
  60156. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  60157. __decorate([
  60158. BABYLON.serialize()
  60159. ], SSAORenderingPipeline.prototype, "radius", void 0);
  60160. __decorate([
  60161. BABYLON.serialize()
  60162. ], SSAORenderingPipeline.prototype, "area", void 0);
  60163. __decorate([
  60164. BABYLON.serialize()
  60165. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  60166. __decorate([
  60167. BABYLON.serialize()
  60168. ], SSAORenderingPipeline.prototype, "base", void 0);
  60169. return SSAORenderingPipeline;
  60170. }(BABYLON.PostProcessRenderPipeline));
  60171. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  60172. })(BABYLON || (BABYLON = {}));
  60173. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  60174. var BABYLON;
  60175. (function (BABYLON) {
  60176. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  60177. __extends(SSAO2RenderingPipeline, _super);
  60178. /**
  60179. * @constructor
  60180. * @param {string} name - The rendering pipeline name
  60181. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60182. * @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 }
  60183. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60184. */
  60185. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  60186. var _this = _super.call(this, scene.getEngine(), name) || this;
  60187. // Members
  60188. /**
  60189. * The PassPostProcess id in the pipeline that contains the original scene color
  60190. * @type {string}
  60191. */
  60192. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  60193. /**
  60194. * The SSAO PostProcess id in the pipeline
  60195. * @type {string}
  60196. */
  60197. _this.SSAORenderEffect = "SSAORenderEffect";
  60198. /**
  60199. * The horizontal blur PostProcess id in the pipeline
  60200. * @type {string}
  60201. */
  60202. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  60203. /**
  60204. * The vertical blur PostProcess id in the pipeline
  60205. * @type {string}
  60206. */
  60207. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  60208. /**
  60209. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  60210. * @type {string}
  60211. */
  60212. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  60213. /**
  60214. * The output strength of the SSAO post-process. Default value is 1.0.
  60215. * @type {number}
  60216. */
  60217. _this.totalStrength = 1.0;
  60218. /**
  60219. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  60220. * @type {number}
  60221. */
  60222. _this.maxZ = 100.0;
  60223. /**
  60224. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  60225. * @type {number}
  60226. */
  60227. _this.minZAspect = 0.2;
  60228. /**
  60229. * Number of samples used for the SSAO calculations. Default value is 8
  60230. * @type {number}
  60231. */
  60232. _this._samples = 8;
  60233. /**
  60234. * Are we using bilateral blur ?
  60235. * @type {boolean}
  60236. */
  60237. _this._expensiveBlur = true;
  60238. /**
  60239. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  60240. * @type {number}
  60241. */
  60242. _this.radius = 2.0;
  60243. /**
  60244. * The base color of the SSAO post-process
  60245. * The final result is "base + ssao" between [0, 1]
  60246. * @type {number}
  60247. */
  60248. _this.base = 0.1;
  60249. _this._firstUpdate = true;
  60250. _this._scene = scene;
  60251. if (!_this.isSupported) {
  60252. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  60253. return _this;
  60254. }
  60255. var ssaoRatio = ratio.ssaoRatio || ratio;
  60256. var blurRatio = ratio.blurRatio || ratio;
  60257. // Set up assets
  60258. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  60259. _this._createRandomTexture();
  60260. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  60261. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  60262. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  60263. _this._createSSAOPostProcess(1.0);
  60264. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  60265. _this._createSSAOCombinePostProcess(blurRatio);
  60266. // Set up pipeline
  60267. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  60268. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  60269. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  60270. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  60271. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  60272. // Finish
  60273. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60274. if (cameras)
  60275. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60276. return _this;
  60277. }
  60278. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  60279. get: function () {
  60280. return this._samples;
  60281. },
  60282. set: function (n) {
  60283. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  60284. this._samples = n;
  60285. this._sampleSphere = this._generateHemisphere();
  60286. this._firstUpdate = true;
  60287. },
  60288. enumerable: true,
  60289. configurable: true
  60290. });
  60291. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  60292. get: function () {
  60293. return this._expensiveBlur;
  60294. },
  60295. set: function (b) {
  60296. 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"]);
  60297. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  60298. this._expensiveBlur = b;
  60299. this._firstUpdate = true;
  60300. },
  60301. enumerable: true,
  60302. configurable: true
  60303. });
  60304. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  60305. /**
  60306. * Support test.
  60307. * @type {boolean}
  60308. */
  60309. get: function () {
  60310. var engine = BABYLON.Engine.LastCreatedEngine;
  60311. if (!engine) {
  60312. return false;
  60313. }
  60314. return engine.getCaps().drawBuffersExtension;
  60315. },
  60316. enumerable: true,
  60317. configurable: true
  60318. });
  60319. // Public Methods
  60320. /**
  60321. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  60322. */
  60323. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  60324. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  60325. for (var i = 0; i < this._scene.cameras.length; i++) {
  60326. var camera = this._scene.cameras[i];
  60327. this._originalColorPostProcess.dispose(camera);
  60328. this._ssaoPostProcess.dispose(camera);
  60329. this._blurHPostProcess.dispose(camera);
  60330. this._blurVPostProcess.dispose(camera);
  60331. this._ssaoCombinePostProcess.dispose(camera);
  60332. }
  60333. this._randomTexture.dispose();
  60334. if (disableGeometryBufferRenderer)
  60335. this._scene.disableGeometryBufferRenderer();
  60336. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60337. _super.prototype.dispose.call(this);
  60338. };
  60339. // Private Methods
  60340. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  60341. var _this = this;
  60342. this._samplerOffsets = [];
  60343. var expensive = this.expensiveBlur;
  60344. for (var i = -8; i < 8; i++) {
  60345. this._samplerOffsets.push(i * 2 + 0.5);
  60346. }
  60347. 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");
  60348. this._blurHPostProcess.onApply = function (effect) {
  60349. if (!_this._scene.activeCamera) {
  60350. return;
  60351. }
  60352. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  60353. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60354. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60355. effect.setFloat("radius", _this.radius);
  60356. effect.setTexture("depthSampler", _this._depthTexture);
  60357. if (_this._firstUpdate) {
  60358. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60359. }
  60360. };
  60361. 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");
  60362. this._blurVPostProcess.onApply = function (effect) {
  60363. if (!_this._scene.activeCamera) {
  60364. return;
  60365. }
  60366. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  60367. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60368. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60369. effect.setFloat("radius", _this.radius);
  60370. effect.setTexture("depthSampler", _this._depthTexture);
  60371. if (_this._firstUpdate) {
  60372. effect.setArray("samplerOffsets", _this._samplerOffsets);
  60373. _this._firstUpdate = false;
  60374. }
  60375. };
  60376. };
  60377. SSAO2RenderingPipeline.prototype._rebuild = function () {
  60378. this._firstUpdate = true;
  60379. _super.prototype._rebuild.call(this);
  60380. };
  60381. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  60382. var numSamples = this.samples;
  60383. var result = [];
  60384. var vector, scale;
  60385. var rand = function (min, max) {
  60386. return Math.random() * (max - min) + min;
  60387. };
  60388. var i = 0;
  60389. while (i < numSamples) {
  60390. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  60391. vector.normalize();
  60392. scale = i / numSamples;
  60393. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  60394. vector.scaleInPlace(scale);
  60395. result.push(vector.x, vector.y, vector.z);
  60396. i++;
  60397. }
  60398. return result;
  60399. };
  60400. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  60401. var _this = this;
  60402. var numSamples = this.samples;
  60403. this._sampleSphere = this._generateHemisphere();
  60404. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  60405. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  60406. "base", "range", "projection", "near", "far", "texelSize",
  60407. "xViewport", "yViewport", "maxZ", "minZAspect"
  60408. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  60409. this._ssaoPostProcess.onApply = function (effect) {
  60410. if (_this._firstUpdate) {
  60411. effect.setArray3("sampleSphere", _this._sampleSphere);
  60412. effect.setFloat("randTextureTiles", 4.0);
  60413. }
  60414. if (!_this._scene.activeCamera) {
  60415. return;
  60416. }
  60417. effect.setFloat("samplesFactor", 1 / _this.samples);
  60418. effect.setFloat("totalStrength", _this.totalStrength);
  60419. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  60420. effect.setFloat("radius", _this.radius);
  60421. effect.setFloat("maxZ", _this.maxZ);
  60422. effect.setFloat("minZAspect", _this.minZAspect);
  60423. effect.setFloat("base", _this.base);
  60424. effect.setFloat("near", _this._scene.activeCamera.minZ);
  60425. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  60426. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  60427. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  60428. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  60429. effect.setTexture("textureSampler", _this._depthTexture);
  60430. effect.setTexture("normalSampler", _this._normalTexture);
  60431. effect.setTexture("randomSampler", _this._randomTexture);
  60432. };
  60433. };
  60434. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  60435. var _this = this;
  60436. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60437. this._ssaoCombinePostProcess.onApply = function (effect) {
  60438. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  60439. };
  60440. };
  60441. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  60442. var size = 512;
  60443. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  60444. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60445. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60446. var context = this._randomTexture.getContext();
  60447. var rand = function (min, max) {
  60448. return Math.random() * (max - min) + min;
  60449. };
  60450. var randVector = BABYLON.Vector3.Zero();
  60451. for (var x = 0; x < size; x++) {
  60452. for (var y = 0; y < size; y++) {
  60453. randVector.x = rand(0.0, 1.0);
  60454. randVector.y = rand(0.0, 1.0);
  60455. randVector.z = 0.0;
  60456. randVector.normalize();
  60457. randVector.scaleInPlace(255);
  60458. randVector.x = Math.floor(randVector.x);
  60459. randVector.y = Math.floor(randVector.y);
  60460. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  60461. context.fillRect(x, y, 1, 1);
  60462. }
  60463. }
  60464. this._randomTexture.update(false);
  60465. };
  60466. __decorate([
  60467. BABYLON.serialize()
  60468. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  60469. __decorate([
  60470. BABYLON.serialize()
  60471. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  60472. __decorate([
  60473. BABYLON.serialize()
  60474. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  60475. __decorate([
  60476. BABYLON.serialize("samples")
  60477. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  60478. __decorate([
  60479. BABYLON.serialize("expensiveBlur")
  60480. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  60481. __decorate([
  60482. BABYLON.serialize()
  60483. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  60484. __decorate([
  60485. BABYLON.serialize()
  60486. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  60487. return SSAO2RenderingPipeline;
  60488. }(BABYLON.PostProcessRenderPipeline));
  60489. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  60490. })(BABYLON || (BABYLON = {}));
  60491. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  60492. // BABYLON.JS Chromatic Aberration GLSL Shader
  60493. // Author: Olivier Guyot
  60494. // Separates very slightly R, G and B colors on the edges of the screen
  60495. // Inspired by Francois Tarlier & Martins Upitis
  60496. var BABYLON;
  60497. (function (BABYLON) {
  60498. var LensRenderingPipeline = /** @class */ (function (_super) {
  60499. __extends(LensRenderingPipeline, _super);
  60500. /**
  60501. * @constructor
  60502. *
  60503. * Effect parameters are as follow:
  60504. * {
  60505. * chromatic_aberration: number; // from 0 to x (1 for realism)
  60506. * edge_blur: number; // from 0 to x (1 for realism)
  60507. * distortion: number; // from 0 to x (1 for realism)
  60508. * grain_amount: number; // from 0 to 1
  60509. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  60510. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  60511. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  60512. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  60513. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  60514. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  60515. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  60516. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  60517. * }
  60518. * Note: if an effect parameter is unset, effect is disabled
  60519. *
  60520. * @param {string} name - The rendering pipeline name
  60521. * @param {object} parameters - An object containing all parameters (see above)
  60522. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60523. * @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)
  60524. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60525. */
  60526. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  60527. if (ratio === void 0) { ratio = 1.0; }
  60528. var _this = _super.call(this, scene.getEngine(), name) || this;
  60529. // Lens effects can be of the following:
  60530. // - chromatic aberration (slight shift of RGB colors)
  60531. // - blur on the edge of the lens
  60532. // - lens distortion
  60533. // - depth-of-field blur & highlights enhancing
  60534. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  60535. // - grain effect (noise or custom texture)
  60536. // Two additional texture samplers are needed:
  60537. // - depth map (for depth-of-field)
  60538. // - grain texture
  60539. /**
  60540. * The chromatic aberration PostProcess id in the pipeline
  60541. * @type {string}
  60542. */
  60543. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  60544. /**
  60545. * The highlights enhancing PostProcess id in the pipeline
  60546. * @type {string}
  60547. */
  60548. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  60549. /**
  60550. * The depth-of-field PostProcess id in the pipeline
  60551. * @type {string}
  60552. */
  60553. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  60554. _this._scene = scene;
  60555. // Fetch texture samplers
  60556. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  60557. if (parameters.grain_texture) {
  60558. _this._grainTexture = parameters.grain_texture;
  60559. }
  60560. else {
  60561. _this._createGrainTexture();
  60562. }
  60563. // save parameters
  60564. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  60565. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  60566. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  60567. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  60568. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  60569. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  60570. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  60571. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  60572. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  60573. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  60574. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  60575. // Create effects
  60576. _this._createChromaticAberrationPostProcess(ratio);
  60577. _this._createHighlightsPostProcess(ratio);
  60578. _this._createDepthOfFieldPostProcess(ratio / 4);
  60579. // Set up pipeline
  60580. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  60581. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  60582. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  60583. if (_this._highlightsGain === -1) {
  60584. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  60585. }
  60586. // Finish
  60587. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60588. if (cameras) {
  60589. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  60590. }
  60591. return _this;
  60592. }
  60593. // public methods (self explanatory)
  60594. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  60595. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  60596. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  60597. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  60598. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  60599. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  60600. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  60601. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  60602. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  60603. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  60604. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  60605. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  60606. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  60607. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  60608. };
  60609. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  60610. this._highlightsPostProcess.updateEffect();
  60611. };
  60612. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  60613. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  60614. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  60615. this._highlightsGain = amount;
  60616. };
  60617. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  60618. if (this._highlightsGain === -1) {
  60619. this._highlightsGain = 1.0;
  60620. }
  60621. this._highlightsThreshold = amount;
  60622. };
  60623. LensRenderingPipeline.prototype.disableHighlights = function () {
  60624. this._highlightsGain = -1;
  60625. };
  60626. /**
  60627. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  60628. */
  60629. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  60630. if (disableDepthRender === void 0) { disableDepthRender = false; }
  60631. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  60632. this._chromaticAberrationPostProcess = null;
  60633. this._highlightsPostProcess = null;
  60634. this._depthOfFieldPostProcess = null;
  60635. this._grainTexture.dispose();
  60636. if (disableDepthRender)
  60637. this._scene.disableDepthRenderer();
  60638. };
  60639. // colors shifting and distortion
  60640. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  60641. var _this = this;
  60642. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  60643. [], // samplers
  60644. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60645. this._chromaticAberrationPostProcess.onApply = function (effect) {
  60646. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  60647. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60648. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60649. };
  60650. };
  60651. // highlights enhancing
  60652. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  60653. var _this = this;
  60654. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  60655. [], // samplers
  60656. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  60657. this._highlightsPostProcess.onApply = function (effect) {
  60658. effect.setFloat('gain', _this._highlightsGain);
  60659. effect.setFloat('threshold', _this._highlightsThreshold);
  60660. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  60661. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60662. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60663. };
  60664. };
  60665. // colors shifting and distortion
  60666. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  60667. var _this = this;
  60668. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  60669. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  60670. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  60671. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  60672. this._depthOfFieldPostProcess.onApply = function (effect) {
  60673. effect.setTexture("depthSampler", _this._depthTexture);
  60674. effect.setTexture("grainSampler", _this._grainTexture);
  60675. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  60676. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  60677. effect.setFloat('grain_amount', _this._grainAmount);
  60678. effect.setBool('blur_noise', _this._blurNoise);
  60679. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  60680. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  60681. effect.setFloat('distortion', _this._distortion);
  60682. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  60683. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  60684. effect.setFloat('aperture', _this._dofAperture);
  60685. effect.setFloat('darken', _this._dofDarken);
  60686. effect.setFloat('edge_blur', _this._edgeBlur);
  60687. effect.setBool('highlights', (_this._highlightsGain !== -1));
  60688. if (_this._scene.activeCamera) {
  60689. effect.setFloat('near', _this._scene.activeCamera.minZ);
  60690. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  60691. }
  60692. };
  60693. };
  60694. // creates a black and white random noise texture, 512x512
  60695. LensRenderingPipeline.prototype._createGrainTexture = function () {
  60696. var size = 512;
  60697. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60698. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60699. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60700. var context = this._grainTexture.getContext();
  60701. var rand = function (min, max) {
  60702. return Math.random() * (max - min) + min;
  60703. };
  60704. var value;
  60705. for (var x = 0; x < size; x++) {
  60706. for (var y = 0; y < size; y++) {
  60707. value = Math.floor(rand(0.42, 0.58) * 255);
  60708. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60709. context.fillRect(x, y, 1, 1);
  60710. }
  60711. }
  60712. this._grainTexture.update(false);
  60713. };
  60714. return LensRenderingPipeline;
  60715. }(BABYLON.PostProcessRenderPipeline));
  60716. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60717. })(BABYLON || (BABYLON = {}));
  60718. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60719. var BABYLON;
  60720. (function (BABYLON) {
  60721. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60722. __extends(StandardRenderingPipeline, _super);
  60723. /**
  60724. * @constructor
  60725. * @param {string} name - The rendering pipeline name
  60726. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60727. * @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)
  60728. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60729. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60730. */
  60731. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60732. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60733. var _this = _super.call(this, scene.getEngine(), name) || this;
  60734. _this.downSampleX4PostProcess = null;
  60735. _this.brightPassPostProcess = null;
  60736. _this.blurHPostProcesses = [];
  60737. _this.blurVPostProcesses = [];
  60738. _this.textureAdderPostProcess = null;
  60739. _this.volumetricLightPostProcess = null;
  60740. _this.volumetricLightSmoothXPostProcess = null;
  60741. _this.volumetricLightSmoothYPostProcess = null;
  60742. _this.volumetricLightMergePostProces = null;
  60743. _this.volumetricLightFinalPostProcess = null;
  60744. _this.luminancePostProcess = null;
  60745. _this.luminanceDownSamplePostProcesses = [];
  60746. _this.hdrPostProcess = null;
  60747. _this.textureAdderFinalPostProcess = null;
  60748. _this.lensFlareFinalPostProcess = null;
  60749. _this.hdrFinalPostProcess = null;
  60750. _this.lensFlarePostProcess = null;
  60751. _this.lensFlareComposePostProcess = null;
  60752. _this.motionBlurPostProcess = null;
  60753. _this.depthOfFieldPostProcess = null;
  60754. // Values
  60755. _this.brightThreshold = 1.0;
  60756. _this.blurWidth = 512.0;
  60757. _this.horizontalBlur = false;
  60758. _this.exposure = 1.0;
  60759. _this.lensTexture = null;
  60760. _this.volumetricLightCoefficient = 0.2;
  60761. _this.volumetricLightPower = 4.0;
  60762. _this.volumetricLightBlurScale = 64.0;
  60763. _this.sourceLight = null;
  60764. _this.hdrMinimumLuminance = 1.0;
  60765. _this.hdrDecreaseRate = 0.5;
  60766. _this.hdrIncreaseRate = 0.5;
  60767. _this.lensColorTexture = null;
  60768. _this.lensFlareStrength = 20.0;
  60769. _this.lensFlareGhostDispersal = 1.4;
  60770. _this.lensFlareHaloWidth = 0.7;
  60771. _this.lensFlareDistortionStrength = 16.0;
  60772. _this.lensStarTexture = null;
  60773. _this.lensFlareDirtTexture = null;
  60774. _this.depthOfFieldDistance = 10.0;
  60775. _this.depthOfFieldBlurWidth = 64.0;
  60776. _this.motionStrength = 1.0;
  60777. // IAnimatable
  60778. _this.animations = [];
  60779. _this._currentDepthOfFieldSource = null;
  60780. _this._hdrCurrentLuminance = 1.0;
  60781. // Getters and setters
  60782. _this._bloomEnabled = true;
  60783. _this._depthOfFieldEnabled = false;
  60784. _this._vlsEnabled = false;
  60785. _this._lensFlareEnabled = false;
  60786. _this._hdrEnabled = false;
  60787. _this._motionBlurEnabled = false;
  60788. _this._motionBlurSamples = 64.0;
  60789. _this._volumetricLightStepsCount = 50.0;
  60790. _this._cameras = cameras || [];
  60791. // Initialize
  60792. _this._scene = scene;
  60793. _this._basePostProcess = originalPostProcess;
  60794. _this._ratio = ratio;
  60795. // Misc
  60796. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60797. // Finish
  60798. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60799. _this._buildPipeline();
  60800. return _this;
  60801. }
  60802. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60803. get: function () {
  60804. return this._bloomEnabled;
  60805. },
  60806. set: function (enabled) {
  60807. if (this._bloomEnabled === enabled) {
  60808. return;
  60809. }
  60810. this._bloomEnabled = enabled;
  60811. this._buildPipeline();
  60812. },
  60813. enumerable: true,
  60814. configurable: true
  60815. });
  60816. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60817. get: function () {
  60818. return this._depthOfFieldEnabled;
  60819. },
  60820. set: function (enabled) {
  60821. if (this._depthOfFieldEnabled === enabled) {
  60822. return;
  60823. }
  60824. this._depthOfFieldEnabled = enabled;
  60825. this._buildPipeline();
  60826. },
  60827. enumerable: true,
  60828. configurable: true
  60829. });
  60830. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60831. get: function () {
  60832. return this._lensFlareEnabled;
  60833. },
  60834. set: function (enabled) {
  60835. if (this._lensFlareEnabled === enabled) {
  60836. return;
  60837. }
  60838. this._lensFlareEnabled = enabled;
  60839. this._buildPipeline();
  60840. },
  60841. enumerable: true,
  60842. configurable: true
  60843. });
  60844. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  60845. get: function () {
  60846. return this._hdrEnabled;
  60847. },
  60848. set: function (enabled) {
  60849. if (this._hdrEnabled === enabled) {
  60850. return;
  60851. }
  60852. this._hdrEnabled = enabled;
  60853. this._buildPipeline();
  60854. },
  60855. enumerable: true,
  60856. configurable: true
  60857. });
  60858. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  60859. get: function () {
  60860. return this._vlsEnabled;
  60861. },
  60862. set: function (enabled) {
  60863. if (this._vlsEnabled === enabled) {
  60864. return;
  60865. }
  60866. if (enabled) {
  60867. var geometry = this._scene.enableGeometryBufferRenderer();
  60868. if (!geometry) {
  60869. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  60870. return;
  60871. }
  60872. }
  60873. this._vlsEnabled = enabled;
  60874. this._buildPipeline();
  60875. },
  60876. enumerable: true,
  60877. configurable: true
  60878. });
  60879. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  60880. get: function () {
  60881. return this._motionBlurEnabled;
  60882. },
  60883. set: function (enabled) {
  60884. if (this._motionBlurEnabled === enabled) {
  60885. return;
  60886. }
  60887. this._motionBlurEnabled = enabled;
  60888. this._buildPipeline();
  60889. },
  60890. enumerable: true,
  60891. configurable: true
  60892. });
  60893. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  60894. get: function () {
  60895. return this._volumetricLightStepsCount;
  60896. },
  60897. set: function (count) {
  60898. if (this.volumetricLightPostProcess) {
  60899. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  60900. }
  60901. this._volumetricLightStepsCount = count;
  60902. },
  60903. enumerable: true,
  60904. configurable: true
  60905. });
  60906. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  60907. get: function () {
  60908. return this._motionBlurSamples;
  60909. },
  60910. set: function (samples) {
  60911. if (this.motionBlurPostProcess) {
  60912. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  60913. }
  60914. this._motionBlurSamples = samples;
  60915. },
  60916. enumerable: true,
  60917. configurable: true
  60918. });
  60919. StandardRenderingPipeline.prototype._buildPipeline = function () {
  60920. var _this = this;
  60921. var ratio = this._ratio;
  60922. var scene = this._scene;
  60923. this._disposePostProcesses();
  60924. this._reset();
  60925. // Create pass post-process
  60926. if (!this._basePostProcess) {
  60927. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  60928. this.originalPostProcess.onApply = function (effect) {
  60929. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  60930. };
  60931. }
  60932. else {
  60933. this.originalPostProcess = this._basePostProcess;
  60934. }
  60935. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60936. this._currentDepthOfFieldSource = this.originalPostProcess;
  60937. if (this._vlsEnabled) {
  60938. // Create volumetric light
  60939. this._createVolumetricLightPostProcess(scene, ratio);
  60940. // Create volumetric light final post-process
  60941. 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);
  60942. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  60943. }
  60944. if (this._bloomEnabled) {
  60945. // Create down sample X4 post-process
  60946. this._createDownSampleX4PostProcess(scene, ratio / 2);
  60947. // Create bright pass post-process
  60948. this._createBrightPassPostProcess(scene, ratio / 2);
  60949. // Create gaussian blur post-processes (down sampling blurs)
  60950. this._createBlurPostProcesses(scene, ratio / 4, 1);
  60951. // Create texture adder post-process
  60952. this._createTextureAdderPostProcess(scene, ratio);
  60953. // Create depth-of-field source post-process
  60954. 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);
  60955. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60956. }
  60957. if (this._lensFlareEnabled) {
  60958. // Create lens flare post-process
  60959. this._createLensFlarePostProcess(scene, ratio);
  60960. // Create depth-of-field source post-process post lens-flare and disable it now
  60961. 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);
  60962. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60963. }
  60964. if (this._hdrEnabled) {
  60965. // Create luminance
  60966. this._createLuminancePostProcesses(scene, this._floatTextureType);
  60967. // Create HDR
  60968. this._createHdrPostProcess(scene, ratio);
  60969. // Create depth-of-field source post-process post hdr and disable it now
  60970. 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);
  60971. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  60972. }
  60973. if (this._depthOfFieldEnabled) {
  60974. // Create gaussian blur used by depth-of-field
  60975. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  60976. // Create depth-of-field post-process
  60977. this._createDepthOfFieldPostProcess(scene, ratio);
  60978. }
  60979. if (this._motionBlurEnabled) {
  60980. // Create motion blur post-process
  60981. this._createMotionBlurPostProcess(scene, ratio);
  60982. }
  60983. if (this._cameras !== null) {
  60984. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60985. }
  60986. };
  60987. // Down Sample X4 Post-Processs
  60988. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  60989. var _this = this;
  60990. var downSampleX4Offsets = new Array(32);
  60991. 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);
  60992. this.downSampleX4PostProcess.onApply = function (effect) {
  60993. var id = 0;
  60994. var width = _this.downSampleX4PostProcess.width;
  60995. var height = _this.downSampleX4PostProcess.height;
  60996. for (var i = -2; i < 2; i++) {
  60997. for (var j = -2; j < 2; j++) {
  60998. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  60999. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  61000. id += 2;
  61001. }
  61002. }
  61003. effect.setArray2("dsOffsets", downSampleX4Offsets);
  61004. };
  61005. // Add to pipeline
  61006. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  61007. };
  61008. // Brightpass Post-Process
  61009. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  61010. var _this = this;
  61011. var brightOffsets = new Array(8);
  61012. 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);
  61013. this.brightPassPostProcess.onApply = function (effect) {
  61014. var sU = (1.0 / _this.brightPassPostProcess.width);
  61015. var sV = (1.0 / _this.brightPassPostProcess.height);
  61016. brightOffsets[0] = -0.5 * sU;
  61017. brightOffsets[1] = 0.5 * sV;
  61018. brightOffsets[2] = 0.5 * sU;
  61019. brightOffsets[3] = 0.5 * sV;
  61020. brightOffsets[4] = -0.5 * sU;
  61021. brightOffsets[5] = -0.5 * sV;
  61022. brightOffsets[6] = 0.5 * sU;
  61023. brightOffsets[7] = -0.5 * sV;
  61024. effect.setArray2("dsOffsets", brightOffsets);
  61025. effect.setFloat("brightThreshold", _this.brightThreshold);
  61026. };
  61027. // Add to pipeline
  61028. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  61029. };
  61030. // Create blur H&V post-processes
  61031. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  61032. var _this = this;
  61033. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  61034. var engine = scene.getEngine();
  61035. 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);
  61036. 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);
  61037. blurX.onActivateObservable.add(function () {
  61038. var dw = blurX.width / engine.getRenderWidth();
  61039. blurX.kernel = _this[blurWidthKey] * dw;
  61040. });
  61041. blurY.onActivateObservable.add(function () {
  61042. var dw = blurY.height / engine.getRenderHeight();
  61043. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  61044. });
  61045. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  61046. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  61047. this.blurHPostProcesses.push(blurX);
  61048. this.blurVPostProcesses.push(blurY);
  61049. };
  61050. // Create texture adder post-process
  61051. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  61052. var _this = this;
  61053. 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);
  61054. this.textureAdderPostProcess.onApply = function (effect) {
  61055. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  61056. effect.setTexture("lensSampler", _this.lensTexture);
  61057. effect.setFloat("exposure", _this.exposure);
  61058. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  61059. };
  61060. // Add to pipeline
  61061. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  61062. };
  61063. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  61064. var _this = this;
  61065. var geometryRenderer = scene.enableGeometryBufferRenderer();
  61066. geometryRenderer.enablePosition = true;
  61067. var geometry = geometryRenderer.getGBuffer();
  61068. // Base post-process
  61069. 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));
  61070. var depthValues = BABYLON.Vector2.Zero();
  61071. this.volumetricLightPostProcess.onApply = function (effect) {
  61072. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  61073. var generator = _this.sourceLight.getShadowGenerator();
  61074. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  61075. effect.setTexture("positionSampler", geometry.textures[2]);
  61076. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  61077. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  61078. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  61079. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  61080. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  61081. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  61082. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  61083. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  61084. effect.setVector2("depthValues", depthValues);
  61085. }
  61086. };
  61087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  61088. // Smooth
  61089. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  61090. // Merge
  61091. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  61092. this.volumetricLightMergePostProces.onApply = function (effect) {
  61093. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  61094. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  61095. };
  61096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  61097. };
  61098. // Create luminance
  61099. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  61100. var _this = this;
  61101. // Create luminance
  61102. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  61103. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  61104. var offsets = [];
  61105. this.luminancePostProcess.onApply = function (effect) {
  61106. var sU = (1.0 / _this.luminancePostProcess.width);
  61107. var sV = (1.0 / _this.luminancePostProcess.height);
  61108. offsets[0] = -0.5 * sU;
  61109. offsets[1] = 0.5 * sV;
  61110. offsets[2] = 0.5 * sU;
  61111. offsets[3] = 0.5 * sV;
  61112. offsets[4] = -0.5 * sU;
  61113. offsets[5] = -0.5 * sV;
  61114. offsets[6] = 0.5 * sU;
  61115. offsets[7] = -0.5 * sV;
  61116. effect.setArray2("lumOffsets", offsets);
  61117. };
  61118. // Add to pipeline
  61119. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  61120. // Create down sample luminance
  61121. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  61122. var size = Math.pow(3, i);
  61123. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  61124. if (i === 0) {
  61125. defines += "#define FINAL_DOWN_SAMPLER";
  61126. }
  61127. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  61128. this.luminanceDownSamplePostProcesses.push(postProcess);
  61129. }
  61130. // Create callbacks and add effects
  61131. var lastLuminance = this.luminancePostProcess;
  61132. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  61133. var downSampleOffsets = new Array(18);
  61134. pp.onApply = function (effect) {
  61135. if (!lastLuminance) {
  61136. return;
  61137. }
  61138. var id = 0;
  61139. for (var x = -1; x < 2; x++) {
  61140. for (var y = -1; y < 2; y++) {
  61141. downSampleOffsets[id] = x / lastLuminance.width;
  61142. downSampleOffsets[id + 1] = y / lastLuminance.height;
  61143. id += 2;
  61144. }
  61145. }
  61146. effect.setArray2("dsOffsets", downSampleOffsets);
  61147. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  61148. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61149. lastLuminance = _this.luminancePostProcess;
  61150. }
  61151. else {
  61152. lastLuminance = pp;
  61153. }
  61154. };
  61155. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  61156. pp.onAfterRender = function (effect) {
  61157. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  61158. 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);
  61159. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  61160. };
  61161. }
  61162. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  61163. });
  61164. };
  61165. // Create HDR post-process
  61166. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  61167. var _this = this;
  61168. 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);
  61169. var outputLiminance = 1;
  61170. var time = 0;
  61171. var lastTime = 0;
  61172. this.hdrPostProcess.onApply = function (effect) {
  61173. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  61174. time += scene.getEngine().getDeltaTime();
  61175. if (outputLiminance < 0) {
  61176. outputLiminance = _this._hdrCurrentLuminance;
  61177. }
  61178. else {
  61179. var dt = (lastTime - time) / 1000.0;
  61180. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  61181. outputLiminance += _this.hdrDecreaseRate * dt;
  61182. }
  61183. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  61184. outputLiminance -= _this.hdrIncreaseRate * dt;
  61185. }
  61186. else {
  61187. outputLiminance = _this._hdrCurrentLuminance;
  61188. }
  61189. }
  61190. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  61191. effect.setFloat("averageLuminance", outputLiminance);
  61192. lastTime = time;
  61193. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  61194. };
  61195. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  61196. };
  61197. // Create lens flare post-process
  61198. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  61199. var _this = this;
  61200. 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);
  61201. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  61202. this._createBlurPostProcesses(scene, ratio / 4, 2);
  61203. 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);
  61204. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  61205. var resolution = new BABYLON.Vector2(0, 0);
  61206. // Lens flare
  61207. this.lensFlarePostProcess.onApply = function (effect) {
  61208. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  61209. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  61210. effect.setFloat("strength", _this.lensFlareStrength);
  61211. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  61212. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  61213. // Shift
  61214. resolution.x = _this.lensFlarePostProcess.width;
  61215. resolution.y = _this.lensFlarePostProcess.height;
  61216. effect.setVector2("resolution", resolution);
  61217. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  61218. };
  61219. // Compose
  61220. 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);
  61221. 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);
  61222. this.lensFlareComposePostProcess.onApply = function (effect) {
  61223. if (!_this._scene.activeCamera) {
  61224. return;
  61225. }
  61226. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61227. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  61228. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  61229. // Lens start rotation matrix
  61230. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  61231. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  61232. 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));
  61233. camRot *= 4.0;
  61234. 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);
  61235. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  61236. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  61237. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  61238. };
  61239. };
  61240. // Create depth-of-field post-process
  61241. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  61242. var _this = this;
  61243. 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);
  61244. this.depthOfFieldPostProcess.onApply = function (effect) {
  61245. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  61246. effect.setTexture("depthSampler", _this._getDepthTexture());
  61247. effect.setFloat("distance", _this.depthOfFieldDistance);
  61248. };
  61249. // Add to pipeline
  61250. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  61251. };
  61252. // Create motion blur post-process
  61253. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  61254. var _this = this;
  61255. 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);
  61256. var motionScale = 0;
  61257. var prevViewProjection = BABYLON.Matrix.Identity();
  61258. var invViewProjection = BABYLON.Matrix.Identity();
  61259. var viewProjection = BABYLON.Matrix.Identity();
  61260. var screenSize = BABYLON.Vector2.Zero();
  61261. this.motionBlurPostProcess.onApply = function (effect) {
  61262. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  61263. viewProjection.invertToRef(invViewProjection);
  61264. effect.setMatrix("inverseViewProjection", invViewProjection);
  61265. effect.setMatrix("prevViewProjection", prevViewProjection);
  61266. prevViewProjection = viewProjection;
  61267. screenSize.x = _this.motionBlurPostProcess.width;
  61268. screenSize.y = _this.motionBlurPostProcess.height;
  61269. effect.setVector2("screenSize", screenSize);
  61270. motionScale = scene.getEngine().getFps() / 60.0;
  61271. effect.setFloat("motionScale", motionScale);
  61272. effect.setFloat("motionStrength", _this.motionStrength);
  61273. effect.setTexture("depthSampler", _this._getDepthTexture());
  61274. };
  61275. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  61276. };
  61277. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  61278. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  61279. var renderer = this._scene.enableGeometryBufferRenderer();
  61280. return renderer.getGBuffer().textures[0];
  61281. }
  61282. return this._scene.enableDepthRenderer().getDepthMap();
  61283. };
  61284. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  61285. for (var i = 0; i < this._cameras.length; i++) {
  61286. var camera = this._cameras[i];
  61287. if (this.originalPostProcess) {
  61288. this.originalPostProcess.dispose(camera);
  61289. }
  61290. if (this.downSampleX4PostProcess) {
  61291. this.downSampleX4PostProcess.dispose(camera);
  61292. }
  61293. if (this.brightPassPostProcess) {
  61294. this.brightPassPostProcess.dispose(camera);
  61295. }
  61296. if (this.textureAdderPostProcess) {
  61297. this.textureAdderPostProcess.dispose(camera);
  61298. }
  61299. if (this.textureAdderFinalPostProcess) {
  61300. this.textureAdderFinalPostProcess.dispose(camera);
  61301. }
  61302. if (this.volumetricLightPostProcess) {
  61303. this.volumetricLightPostProcess.dispose(camera);
  61304. }
  61305. if (this.volumetricLightSmoothXPostProcess) {
  61306. this.volumetricLightSmoothXPostProcess.dispose(camera);
  61307. }
  61308. if (this.volumetricLightSmoothYPostProcess) {
  61309. this.volumetricLightSmoothYPostProcess.dispose(camera);
  61310. }
  61311. if (this.volumetricLightMergePostProces) {
  61312. this.volumetricLightMergePostProces.dispose(camera);
  61313. }
  61314. if (this.volumetricLightFinalPostProcess) {
  61315. this.volumetricLightFinalPostProcess.dispose(camera);
  61316. }
  61317. if (this.lensFlarePostProcess) {
  61318. this.lensFlarePostProcess.dispose(camera);
  61319. }
  61320. if (this.lensFlareComposePostProcess) {
  61321. this.lensFlareComposePostProcess.dispose(camera);
  61322. }
  61323. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  61324. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  61325. }
  61326. if (this.luminancePostProcess) {
  61327. this.luminancePostProcess.dispose(camera);
  61328. }
  61329. if (this.hdrPostProcess) {
  61330. this.hdrPostProcess.dispose(camera);
  61331. }
  61332. if (this.hdrFinalPostProcess) {
  61333. this.hdrFinalPostProcess.dispose(camera);
  61334. }
  61335. if (this.depthOfFieldPostProcess) {
  61336. this.depthOfFieldPostProcess.dispose(camera);
  61337. }
  61338. if (this.motionBlurPostProcess) {
  61339. this.motionBlurPostProcess.dispose(camera);
  61340. }
  61341. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  61342. this.blurHPostProcesses[j].dispose(camera);
  61343. }
  61344. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  61345. this.blurVPostProcesses[j].dispose(camera);
  61346. }
  61347. }
  61348. this.originalPostProcess = null;
  61349. this.downSampleX4PostProcess = null;
  61350. this.brightPassPostProcess = null;
  61351. this.textureAdderPostProcess = null;
  61352. this.textureAdderFinalPostProcess = null;
  61353. this.volumetricLightPostProcess = null;
  61354. this.volumetricLightSmoothXPostProcess = null;
  61355. this.volumetricLightSmoothYPostProcess = null;
  61356. this.volumetricLightMergePostProces = null;
  61357. this.volumetricLightFinalPostProcess = null;
  61358. this.lensFlarePostProcess = null;
  61359. this.lensFlareComposePostProcess = null;
  61360. this.luminancePostProcess = null;
  61361. this.hdrPostProcess = null;
  61362. this.hdrFinalPostProcess = null;
  61363. this.depthOfFieldPostProcess = null;
  61364. this.motionBlurPostProcess = null;
  61365. this.luminanceDownSamplePostProcesses = [];
  61366. this.blurHPostProcesses = [];
  61367. this.blurVPostProcesses = [];
  61368. };
  61369. // Dispose
  61370. StandardRenderingPipeline.prototype.dispose = function () {
  61371. this._disposePostProcesses();
  61372. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61373. _super.prototype.dispose.call(this);
  61374. };
  61375. // Serialize rendering pipeline
  61376. StandardRenderingPipeline.prototype.serialize = function () {
  61377. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61378. serializationObject.customType = "StandardRenderingPipeline";
  61379. return serializationObject;
  61380. };
  61381. /**
  61382. * Static members
  61383. */
  61384. // Parse serialized pipeline
  61385. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61386. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  61387. };
  61388. // Luminance steps
  61389. StandardRenderingPipeline.LuminanceSteps = 6;
  61390. __decorate([
  61391. BABYLON.serialize()
  61392. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  61393. __decorate([
  61394. BABYLON.serialize()
  61395. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  61396. __decorate([
  61397. BABYLON.serialize()
  61398. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  61399. __decorate([
  61400. BABYLON.serialize()
  61401. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  61402. __decorate([
  61403. BABYLON.serializeAsTexture("lensTexture")
  61404. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  61405. __decorate([
  61406. BABYLON.serialize()
  61407. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  61408. __decorate([
  61409. BABYLON.serialize()
  61410. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  61411. __decorate([
  61412. BABYLON.serialize()
  61413. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  61414. __decorate([
  61415. BABYLON.serialize()
  61416. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  61417. __decorate([
  61418. BABYLON.serialize()
  61419. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  61420. __decorate([
  61421. BABYLON.serialize()
  61422. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  61423. __decorate([
  61424. BABYLON.serializeAsTexture("lensColorTexture")
  61425. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  61426. __decorate([
  61427. BABYLON.serialize()
  61428. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  61429. __decorate([
  61430. BABYLON.serialize()
  61431. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  61432. __decorate([
  61433. BABYLON.serialize()
  61434. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  61435. __decorate([
  61436. BABYLON.serialize()
  61437. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  61438. __decorate([
  61439. BABYLON.serializeAsTexture("lensStarTexture")
  61440. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  61441. __decorate([
  61442. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  61443. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  61444. __decorate([
  61445. BABYLON.serialize()
  61446. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  61447. __decorate([
  61448. BABYLON.serialize()
  61449. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  61450. __decorate([
  61451. BABYLON.serialize()
  61452. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  61453. __decorate([
  61454. BABYLON.serialize()
  61455. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  61456. __decorate([
  61457. BABYLON.serialize()
  61458. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  61459. __decorate([
  61460. BABYLON.serialize()
  61461. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  61462. __decorate([
  61463. BABYLON.serialize()
  61464. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  61465. __decorate([
  61466. BABYLON.serialize()
  61467. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  61468. __decorate([
  61469. BABYLON.serialize()
  61470. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  61471. __decorate([
  61472. BABYLON.serialize()
  61473. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  61474. __decorate([
  61475. BABYLON.serialize()
  61476. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  61477. __decorate([
  61478. BABYLON.serialize()
  61479. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  61480. return StandardRenderingPipeline;
  61481. }(BABYLON.PostProcessRenderPipeline));
  61482. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  61483. })(BABYLON || (BABYLON = {}));
  61484. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  61485. var BABYLON;
  61486. (function (BABYLON) {
  61487. var FxaaPostProcess = /** @class */ (function (_super) {
  61488. __extends(FxaaPostProcess, _super);
  61489. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61490. if (camera === void 0) { camera = null; }
  61491. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61492. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  61493. _this.onApplyObservable.add(function (effect) {
  61494. var texelSize = _this.texelSize;
  61495. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  61496. });
  61497. return _this;
  61498. }
  61499. return FxaaPostProcess;
  61500. }(BABYLON.PostProcess));
  61501. BABYLON.FxaaPostProcess = FxaaPostProcess;
  61502. })(BABYLON || (BABYLON = {}));
  61503. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  61504. var BABYLON;
  61505. (function (BABYLON) {
  61506. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  61507. __extends(DefaultRenderingPipeline, _super);
  61508. /**
  61509. * @constructor
  61510. * @param {string} name - The rendering pipeline name
  61511. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61512. * @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)
  61513. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61514. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  61515. */
  61516. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  61517. if (automaticBuild === void 0) { automaticBuild = true; }
  61518. var _this = _super.call(this, scene.getEngine(), name) || this;
  61519. _this.PassPostProcessId = "PassPostProcessEffect";
  61520. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  61521. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  61522. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  61523. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  61524. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  61525. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  61526. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  61527. // IAnimatable
  61528. _this.animations = [];
  61529. // Values
  61530. _this._bloomEnabled = false;
  61531. _this._fxaaEnabled = false;
  61532. _this._imageProcessingEnabled = true;
  61533. _this._bloomScale = 0.6;
  61534. _this._buildAllowed = true;
  61535. /**
  61536. * Specifies the size of the bloom blur kernel, relative to the final output size
  61537. */
  61538. _this.bloomKernel = 64;
  61539. /**
  61540. * Specifies the weight of the bloom in the final rendering
  61541. */
  61542. _this._bloomWeight = 0.15;
  61543. _this._cameras = cameras || [];
  61544. _this._buildAllowed = automaticBuild;
  61545. // Initialize
  61546. _this._scene = scene;
  61547. var caps = _this._scene.getEngine().getCaps();
  61548. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  61549. // Misc
  61550. if (_this._hdr) {
  61551. if (caps.textureHalfFloatRender) {
  61552. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61553. }
  61554. else if (caps.textureFloatRender) {
  61555. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61556. }
  61557. }
  61558. else {
  61559. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61560. }
  61561. // Attach
  61562. scene.postProcessRenderPipelineManager.addPipeline(_this);
  61563. _this._buildPipeline();
  61564. return _this;
  61565. }
  61566. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  61567. get: function () {
  61568. return this._bloomWeight;
  61569. },
  61570. set: function (value) {
  61571. if (this._bloomWeight === value) {
  61572. return;
  61573. }
  61574. this._bloomWeight = value;
  61575. if (this._hdr && this.copyBack) {
  61576. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  61577. }
  61578. },
  61579. enumerable: true,
  61580. configurable: true
  61581. });
  61582. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  61583. get: function () {
  61584. return this._bloomScale;
  61585. },
  61586. set: function (value) {
  61587. if (this._bloomScale === value) {
  61588. return;
  61589. }
  61590. this._bloomScale = value;
  61591. this._buildPipeline();
  61592. },
  61593. enumerable: true,
  61594. configurable: true
  61595. });
  61596. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  61597. get: function () {
  61598. return this._bloomEnabled;
  61599. },
  61600. set: function (enabled) {
  61601. if (this._bloomEnabled === enabled) {
  61602. return;
  61603. }
  61604. this._bloomEnabled = enabled;
  61605. this._buildPipeline();
  61606. },
  61607. enumerable: true,
  61608. configurable: true
  61609. });
  61610. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  61611. get: function () {
  61612. return this._fxaaEnabled;
  61613. },
  61614. set: function (enabled) {
  61615. if (this._fxaaEnabled === enabled) {
  61616. return;
  61617. }
  61618. this._fxaaEnabled = enabled;
  61619. this._buildPipeline();
  61620. },
  61621. enumerable: true,
  61622. configurable: true
  61623. });
  61624. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  61625. get: function () {
  61626. return this._imageProcessingEnabled;
  61627. },
  61628. set: function (enabled) {
  61629. if (this._imageProcessingEnabled === enabled) {
  61630. return;
  61631. }
  61632. this._imageProcessingEnabled = enabled;
  61633. this._buildPipeline();
  61634. },
  61635. enumerable: true,
  61636. configurable: true
  61637. });
  61638. /**
  61639. * Force the compilation of the entire pipeline.
  61640. */
  61641. DefaultRenderingPipeline.prototype.prepare = function () {
  61642. var previousState = this._buildAllowed;
  61643. this._buildAllowed = true;
  61644. this._buildPipeline();
  61645. this._buildAllowed = previousState;
  61646. };
  61647. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  61648. var _this = this;
  61649. if (!this._buildAllowed) {
  61650. return;
  61651. }
  61652. var engine = this._scene.getEngine();
  61653. this._disposePostProcesses();
  61654. this._reset();
  61655. if (this.bloomEnabled) {
  61656. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61657. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  61658. if (!this._hdr) {
  61659. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61660. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  61661. this.highlights.autoClear = false;
  61662. this.highlights.alwaysForcePOT = true;
  61663. }
  61664. 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);
  61665. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  61666. this.blurX.alwaysForcePOT = true;
  61667. this.blurX.autoClear = false;
  61668. this.blurX.onActivateObservable.add(function () {
  61669. var dw = _this.blurX.width / engine.getRenderWidth(true);
  61670. _this.blurX.kernel = _this.bloomKernel * dw;
  61671. });
  61672. 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);
  61673. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  61674. this.blurY.alwaysForcePOT = true;
  61675. this.blurY.autoClear = false;
  61676. this.blurY.onActivateObservable.add(function () {
  61677. var dh = _this.blurY.height / engine.getRenderHeight(true);
  61678. _this.blurY.kernel = _this.bloomKernel * dh;
  61679. });
  61680. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61681. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  61682. this.copyBack.alwaysForcePOT = true;
  61683. if (this._hdr) {
  61684. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  61685. var w = this.bloomWeight;
  61686. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  61687. }
  61688. else {
  61689. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  61690. }
  61691. this.copyBack.autoClear = false;
  61692. }
  61693. if (this._imageProcessingEnabled) {
  61694. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61695. if (this._hdr) {
  61696. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  61697. }
  61698. else {
  61699. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  61700. }
  61701. }
  61702. if (this.fxaaEnabled) {
  61703. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61704. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  61705. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61706. }
  61707. else if (this._hdr && this.imageProcessing) {
  61708. this.finalMerge = this.imageProcessing;
  61709. }
  61710. else {
  61711. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61712. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61713. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61714. }
  61715. if (this.bloomEnabled) {
  61716. if (this._hdr) {
  61717. this.copyBack.shareOutputWith(this.blurX);
  61718. if (this.imageProcessing) {
  61719. this.imageProcessing.shareOutputWith(this.pass);
  61720. this.imageProcessing.autoClear = false;
  61721. }
  61722. else if (this.fxaa) {
  61723. this.fxaa.shareOutputWith(this.pass);
  61724. }
  61725. else {
  61726. this.finalMerge.shareOutputWith(this.pass);
  61727. }
  61728. }
  61729. else {
  61730. if (this.fxaa) {
  61731. this.fxaa.shareOutputWith(this.pass);
  61732. }
  61733. else {
  61734. this.finalMerge.shareOutputWith(this.pass);
  61735. }
  61736. }
  61737. }
  61738. if (this._cameras !== null) {
  61739. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61740. }
  61741. };
  61742. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61743. for (var i = 0; i < this._cameras.length; i++) {
  61744. var camera = this._cameras[i];
  61745. if (this.pass) {
  61746. this.pass.dispose(camera);
  61747. }
  61748. if (this.highlights) {
  61749. this.highlights.dispose(camera);
  61750. }
  61751. if (this.blurX) {
  61752. this.blurX.dispose(camera);
  61753. }
  61754. if (this.blurY) {
  61755. this.blurY.dispose(camera);
  61756. }
  61757. if (this.copyBack) {
  61758. this.copyBack.dispose(camera);
  61759. }
  61760. if (this.imageProcessing) {
  61761. this.imageProcessing.dispose(camera);
  61762. }
  61763. if (this.fxaa) {
  61764. this.fxaa.dispose(camera);
  61765. }
  61766. if (this.finalMerge) {
  61767. this.finalMerge.dispose(camera);
  61768. }
  61769. }
  61770. this.pass = null;
  61771. this.highlights = null;
  61772. this.blurX = null;
  61773. this.blurY = null;
  61774. this.copyBack = null;
  61775. this.imageProcessing = null;
  61776. this.fxaa = null;
  61777. this.finalMerge = null;
  61778. };
  61779. // Dispose
  61780. DefaultRenderingPipeline.prototype.dispose = function () {
  61781. this._disposePostProcesses();
  61782. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61783. _super.prototype.dispose.call(this);
  61784. };
  61785. // Serialize rendering pipeline
  61786. DefaultRenderingPipeline.prototype.serialize = function () {
  61787. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61788. serializationObject.customType = "DefaultRenderingPipeline";
  61789. return serializationObject;
  61790. };
  61791. // Parse serialized pipeline
  61792. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61793. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61794. };
  61795. __decorate([
  61796. BABYLON.serialize()
  61797. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61798. __decorate([
  61799. BABYLON.serialize()
  61800. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61801. __decorate([
  61802. BABYLON.serialize()
  61803. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61804. __decorate([
  61805. BABYLON.serialize()
  61806. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61807. __decorate([
  61808. BABYLON.serialize()
  61809. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61810. __decorate([
  61811. BABYLON.serialize()
  61812. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61813. __decorate([
  61814. BABYLON.serialize()
  61815. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61816. __decorate([
  61817. BABYLON.serialize()
  61818. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61819. return DefaultRenderingPipeline;
  61820. }(BABYLON.PostProcessRenderPipeline));
  61821. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61822. })(BABYLON || (BABYLON = {}));
  61823. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61824. var BABYLON;
  61825. (function (BABYLON) {
  61826. var GeometryBufferRenderer = /** @class */ (function () {
  61827. function GeometryBufferRenderer(scene, ratio) {
  61828. if (ratio === void 0) { ratio = 1; }
  61829. this._enablePosition = false;
  61830. this._scene = scene;
  61831. this._ratio = ratio;
  61832. // Render target
  61833. this._createRenderTargets();
  61834. }
  61835. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  61836. set: function (meshes) {
  61837. this._multiRenderTarget.renderList = meshes;
  61838. },
  61839. enumerable: true,
  61840. configurable: true
  61841. });
  61842. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  61843. get: function () {
  61844. return this._multiRenderTarget.isSupported;
  61845. },
  61846. enumerable: true,
  61847. configurable: true
  61848. });
  61849. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  61850. get: function () {
  61851. return this._enablePosition;
  61852. },
  61853. set: function (enable) {
  61854. this._enablePosition = enable;
  61855. this.dispose();
  61856. this._createRenderTargets();
  61857. },
  61858. enumerable: true,
  61859. configurable: true
  61860. });
  61861. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  61862. var material = subMesh.getMaterial();
  61863. if (material && material.disableDepthWrite) {
  61864. return false;
  61865. }
  61866. var defines = [];
  61867. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61868. var mesh = subMesh.getMesh();
  61869. // Alpha test
  61870. if (material && material.needAlphaTesting()) {
  61871. defines.push("#define ALPHATEST");
  61872. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61873. attribs.push(BABYLON.VertexBuffer.UVKind);
  61874. defines.push("#define UV1");
  61875. }
  61876. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61877. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61878. defines.push("#define UV2");
  61879. }
  61880. }
  61881. // Buffers
  61882. if (this._enablePosition) {
  61883. defines.push("#define POSITION");
  61884. }
  61885. // Bones
  61886. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61887. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61888. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61889. if (mesh.numBoneInfluencers > 4) {
  61890. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61891. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61892. }
  61893. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61894. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61895. }
  61896. else {
  61897. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61898. }
  61899. // Instances
  61900. if (useInstances) {
  61901. defines.push("#define INSTANCES");
  61902. attribs.push("world0");
  61903. attribs.push("world1");
  61904. attribs.push("world2");
  61905. attribs.push("world3");
  61906. }
  61907. // Get correct effect
  61908. var join = defines.join("\n");
  61909. if (this._cachedDefines !== join) {
  61910. this._cachedDefines = join;
  61911. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  61912. }
  61913. return this._effect.isReady();
  61914. };
  61915. GeometryBufferRenderer.prototype.getGBuffer = function () {
  61916. return this._multiRenderTarget;
  61917. };
  61918. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  61919. get: function () {
  61920. return this._multiRenderTarget.samples;
  61921. },
  61922. set: function (value) {
  61923. this._multiRenderTarget.samples = value;
  61924. },
  61925. enumerable: true,
  61926. configurable: true
  61927. });
  61928. // Methods
  61929. GeometryBufferRenderer.prototype.dispose = function () {
  61930. this.getGBuffer().dispose();
  61931. };
  61932. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  61933. var _this = this;
  61934. var engine = this._scene.getEngine();
  61935. var count = this._enablePosition ? 3 : 2;
  61936. 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 });
  61937. if (!this.isSupported) {
  61938. return;
  61939. }
  61940. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61941. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61942. this._multiRenderTarget.refreshRate = 1;
  61943. this._multiRenderTarget.renderParticles = false;
  61944. this._multiRenderTarget.renderList = null;
  61945. // set default depth value to 1.0 (far away)
  61946. this._multiRenderTarget.onClearObservable.add(function (engine) {
  61947. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  61948. });
  61949. // Custom render function
  61950. var renderSubMesh = function (subMesh) {
  61951. var mesh = subMesh.getRenderingMesh();
  61952. var scene = _this._scene;
  61953. var engine = scene.getEngine();
  61954. var material = subMesh.getMaterial();
  61955. if (!material) {
  61956. return;
  61957. }
  61958. // Culling
  61959. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61960. // Managing instances
  61961. var batch = mesh._getInstancesRenderList(subMesh._id);
  61962. if (batch.mustReturn) {
  61963. return;
  61964. }
  61965. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61966. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61967. engine.enableEffect(_this._effect);
  61968. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61969. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61970. _this._effect.setMatrix("view", scene.getViewMatrix());
  61971. // Alpha test
  61972. if (material && material.needAlphaTesting()) {
  61973. var alphaTexture = material.getAlphaTestTexture();
  61974. if (alphaTexture) {
  61975. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61976. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61977. }
  61978. }
  61979. // Bones
  61980. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61981. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61982. }
  61983. // Draw
  61984. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61985. }
  61986. };
  61987. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61988. var index;
  61989. if (depthOnlySubMeshes.length) {
  61990. engine.setColorWrite(false);
  61991. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61992. renderSubMesh(depthOnlySubMeshes.data[index]);
  61993. }
  61994. engine.setColorWrite(true);
  61995. }
  61996. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61997. renderSubMesh(opaqueSubMeshes.data[index]);
  61998. }
  61999. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62000. renderSubMesh(alphaTestSubMeshes.data[index]);
  62001. }
  62002. };
  62003. };
  62004. return GeometryBufferRenderer;
  62005. }());
  62006. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  62007. })(BABYLON || (BABYLON = {}));
  62008. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  62009. var BABYLON;
  62010. (function (BABYLON) {
  62011. var RefractionPostProcess = /** @class */ (function (_super) {
  62012. __extends(RefractionPostProcess, _super);
  62013. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  62014. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  62015. _this.color = color;
  62016. _this.depth = depth;
  62017. _this.colorLevel = colorLevel;
  62018. _this.onActivateObservable.add(function (cam) {
  62019. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  62020. });
  62021. _this.onApplyObservable.add(function (effect) {
  62022. effect.setColor3("baseColor", _this.color);
  62023. effect.setFloat("depth", _this.depth);
  62024. effect.setFloat("colorLevel", _this.colorLevel);
  62025. effect.setTexture("refractionSampler", _this._refRexture);
  62026. });
  62027. return _this;
  62028. }
  62029. // Methods
  62030. RefractionPostProcess.prototype.dispose = function (camera) {
  62031. if (this._refRexture) {
  62032. this._refRexture.dispose();
  62033. }
  62034. _super.prototype.dispose.call(this, camera);
  62035. };
  62036. return RefractionPostProcess;
  62037. }(BABYLON.PostProcess));
  62038. BABYLON.RefractionPostProcess = RefractionPostProcess;
  62039. })(BABYLON || (BABYLON = {}));
  62040. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  62041. var BABYLON;
  62042. (function (BABYLON) {
  62043. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  62044. __extends(BlackAndWhitePostProcess, _super);
  62045. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  62046. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  62047. _this.degree = 1;
  62048. _this.onApplyObservable.add(function (effect) {
  62049. effect.setFloat("degree", _this.degree);
  62050. });
  62051. return _this;
  62052. }
  62053. return BlackAndWhitePostProcess;
  62054. }(BABYLON.PostProcess));
  62055. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  62056. })(BABYLON || (BABYLON = {}));
  62057. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  62058. var BABYLON;
  62059. (function (BABYLON) {
  62060. var ConvolutionPostProcess = /** @class */ (function (_super) {
  62061. __extends(ConvolutionPostProcess, _super);
  62062. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  62063. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  62064. _this.kernel = kernel;
  62065. _this.onApply = function (effect) {
  62066. effect.setFloat2("screenSize", _this.width, _this.height);
  62067. effect.setArray("kernel", _this.kernel);
  62068. };
  62069. return _this;
  62070. }
  62071. // Statics
  62072. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  62073. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  62074. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  62075. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  62076. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  62077. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  62078. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  62079. return ConvolutionPostProcess;
  62080. }(BABYLON.PostProcess));
  62081. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  62082. })(BABYLON || (BABYLON = {}));
  62083. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  62084. var BABYLON;
  62085. (function (BABYLON) {
  62086. var FilterPostProcess = /** @class */ (function (_super) {
  62087. __extends(FilterPostProcess, _super);
  62088. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  62089. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  62090. _this.kernelMatrix = kernelMatrix;
  62091. _this.onApply = function (effect) {
  62092. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  62093. };
  62094. return _this;
  62095. }
  62096. return FilterPostProcess;
  62097. }(BABYLON.PostProcess));
  62098. BABYLON.FilterPostProcess = FilterPostProcess;
  62099. })(BABYLON || (BABYLON = {}));
  62100. //# sourceMappingURL=babylon.filterPostProcess.js.map
  62101. var BABYLON;
  62102. (function (BABYLON) {
  62103. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  62104. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  62105. __extends(VolumetricLightScatteringPostProcess, _super);
  62106. /**
  62107. * @constructor
  62108. * @param {string} name - The post-process name
  62109. * @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)
  62110. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  62111. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  62112. * @param {number} samples - The post-process quality, default 100
  62113. * @param {number} samplingMode - The post-process filtering mode
  62114. * @param {BABYLON.Engine} engine - The babylon engine
  62115. * @param {boolean} reusable - If the post-process is reusable
  62116. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  62117. */
  62118. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  62119. if (samples === void 0) { samples = 100; }
  62120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62121. 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;
  62122. _this._screenCoordinates = BABYLON.Vector2.Zero();
  62123. /**
  62124. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  62125. * @type {Vector3}
  62126. */
  62127. _this.customMeshPosition = BABYLON.Vector3.Zero();
  62128. /**
  62129. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  62130. * @type {boolean}
  62131. */
  62132. _this.useCustomMeshPosition = false;
  62133. /**
  62134. * If the post-process should inverse the light scattering direction
  62135. * @type {boolean}
  62136. */
  62137. _this.invert = true;
  62138. /**
  62139. * Array containing the excluded meshes not rendered in the internal pass
  62140. */
  62141. _this.excludedMeshes = new Array();
  62142. /**
  62143. * Controls the overall intensity of the post-process
  62144. * @type {number}
  62145. */
  62146. _this.exposure = 0.3;
  62147. /**
  62148. * Dissipates each sample's contribution in range [0, 1]
  62149. * @type {number}
  62150. */
  62151. _this.decay = 0.96815;
  62152. /**
  62153. * Controls the overall intensity of each sample
  62154. * @type {number}
  62155. */
  62156. _this.weight = 0.58767;
  62157. /**
  62158. * Controls the density of each sample
  62159. * @type {number}
  62160. */
  62161. _this.density = 0.926;
  62162. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  62163. engine = scene.getEngine();
  62164. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  62165. // Configure mesh
  62166. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  62167. // Configure
  62168. _this._createPass(scene, ratio.passRatio || ratio);
  62169. _this.onActivate = function (camera) {
  62170. if (!_this.isSupported) {
  62171. _this.dispose(camera);
  62172. }
  62173. _this.onActivate = null;
  62174. };
  62175. _this.onApplyObservable.add(function (effect) {
  62176. _this._updateMeshScreenCoordinates(scene);
  62177. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  62178. effect.setFloat("exposure", _this.exposure);
  62179. effect.setFloat("decay", _this.decay);
  62180. effect.setFloat("weight", _this.weight);
  62181. effect.setFloat("density", _this.density);
  62182. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  62183. });
  62184. return _this;
  62185. }
  62186. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  62187. get: function () {
  62188. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62189. return false;
  62190. },
  62191. set: function (useDiffuseColor) {
  62192. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  62193. },
  62194. enumerable: true,
  62195. configurable: true
  62196. });
  62197. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  62198. return "VolumetricLightScatteringPostProcess";
  62199. };
  62200. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  62201. var mesh = subMesh.getMesh();
  62202. // Render this.mesh as default
  62203. if (mesh === this.mesh && mesh.material) {
  62204. return mesh.material.isReady(mesh);
  62205. }
  62206. var defines = [];
  62207. var attribs = [BABYLON.VertexBuffer.PositionKind];
  62208. var material = subMesh.getMaterial();
  62209. // Alpha test
  62210. if (material) {
  62211. if (material.needAlphaTesting()) {
  62212. defines.push("#define ALPHATEST");
  62213. }
  62214. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  62215. attribs.push(BABYLON.VertexBuffer.UVKind);
  62216. defines.push("#define UV1");
  62217. }
  62218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  62219. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  62220. defines.push("#define UV2");
  62221. }
  62222. }
  62223. // Bones
  62224. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  62225. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62226. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62227. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62228. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  62229. }
  62230. else {
  62231. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62232. }
  62233. // Instances
  62234. if (useInstances) {
  62235. defines.push("#define INSTANCES");
  62236. attribs.push("world0");
  62237. attribs.push("world1");
  62238. attribs.push("world2");
  62239. attribs.push("world3");
  62240. }
  62241. // Get correct effect
  62242. var join = defines.join("\n");
  62243. if (this._cachedDefines !== join) {
  62244. this._cachedDefines = join;
  62245. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  62246. }
  62247. return this._volumetricLightScatteringPass.isReady();
  62248. };
  62249. /**
  62250. * Sets the new light position for light scattering effect
  62251. * @param {BABYLON.Vector3} The new custom light position
  62252. */
  62253. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  62254. this.customMeshPosition = position;
  62255. };
  62256. /**
  62257. * Returns the light position for light scattering effect
  62258. * @return {BABYLON.Vector3} The custom light position
  62259. */
  62260. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  62261. return this.customMeshPosition;
  62262. };
  62263. /**
  62264. * Disposes the internal assets and detaches the post-process from the camera
  62265. */
  62266. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  62267. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  62268. if (rttIndex !== -1) {
  62269. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  62270. }
  62271. this._volumetricLightScatteringRTT.dispose();
  62272. _super.prototype.dispose.call(this, camera);
  62273. };
  62274. /**
  62275. * Returns the render target texture used by the post-process
  62276. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  62277. */
  62278. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  62279. return this._volumetricLightScatteringRTT;
  62280. };
  62281. // Private methods
  62282. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  62283. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  62284. return true;
  62285. }
  62286. return false;
  62287. };
  62288. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  62289. var _this = this;
  62290. var engine = scene.getEngine();
  62291. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62292. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62293. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62294. this._volumetricLightScatteringRTT.renderList = null;
  62295. this._volumetricLightScatteringRTT.renderParticles = false;
  62296. var camera = this.getCamera();
  62297. if (camera) {
  62298. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62299. }
  62300. else {
  62301. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  62302. }
  62303. // Custom render function for submeshes
  62304. var renderSubMesh = function (subMesh) {
  62305. var mesh = subMesh.getRenderingMesh();
  62306. if (_this._meshExcluded(mesh)) {
  62307. return;
  62308. }
  62309. var material = subMesh.getMaterial();
  62310. if (!material) {
  62311. return;
  62312. }
  62313. var scene = mesh.getScene();
  62314. var engine = scene.getEngine();
  62315. // Culling
  62316. engine.setState(material.backFaceCulling);
  62317. // Managing instances
  62318. var batch = mesh._getInstancesRenderList(subMesh._id);
  62319. if (batch.mustReturn) {
  62320. return;
  62321. }
  62322. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  62323. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  62324. var effect = _this._volumetricLightScatteringPass;
  62325. if (mesh === _this.mesh) {
  62326. if (subMesh.effect) {
  62327. effect = subMesh.effect;
  62328. }
  62329. else {
  62330. effect = material.getEffect();
  62331. }
  62332. }
  62333. engine.enableEffect(effect);
  62334. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  62335. if (mesh === _this.mesh) {
  62336. material.bind(mesh.getWorldMatrix(), mesh);
  62337. }
  62338. else {
  62339. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  62340. // Alpha test
  62341. if (material && material.needAlphaTesting()) {
  62342. var alphaTexture = material.getAlphaTestTexture();
  62343. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  62344. if (alphaTexture) {
  62345. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  62346. }
  62347. }
  62348. // Bones
  62349. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62350. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  62351. }
  62352. }
  62353. // Draw
  62354. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  62355. }
  62356. };
  62357. // Render target texture callbacks
  62358. var savedSceneClearColor;
  62359. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  62360. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  62361. savedSceneClearColor = scene.clearColor;
  62362. scene.clearColor = sceneClearColor;
  62363. });
  62364. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  62365. scene.clearColor = savedSceneClearColor;
  62366. });
  62367. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  62368. var engine = scene.getEngine();
  62369. var index;
  62370. if (depthOnlySubMeshes.length) {
  62371. engine.setColorWrite(false);
  62372. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  62373. renderSubMesh(depthOnlySubMeshes.data[index]);
  62374. }
  62375. engine.setColorWrite(true);
  62376. }
  62377. for (index = 0; index < opaqueSubMeshes.length; index++) {
  62378. renderSubMesh(opaqueSubMeshes.data[index]);
  62379. }
  62380. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  62381. renderSubMesh(alphaTestSubMeshes.data[index]);
  62382. }
  62383. if (transparentSubMeshes.length) {
  62384. // Sort sub meshes
  62385. for (index = 0; index < transparentSubMeshes.length; index++) {
  62386. var submesh = transparentSubMeshes.data[index];
  62387. var boundingInfo = submesh.getBoundingInfo();
  62388. if (boundingInfo && scene.activeCamera) {
  62389. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  62390. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  62391. }
  62392. }
  62393. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  62394. sortedArray.sort(function (a, b) {
  62395. // Alpha index first
  62396. if (a._alphaIndex > b._alphaIndex) {
  62397. return 1;
  62398. }
  62399. if (a._alphaIndex < b._alphaIndex) {
  62400. return -1;
  62401. }
  62402. // Then distance to camera
  62403. if (a._distanceToCamera < b._distanceToCamera) {
  62404. return 1;
  62405. }
  62406. if (a._distanceToCamera > b._distanceToCamera) {
  62407. return -1;
  62408. }
  62409. return 0;
  62410. });
  62411. // Render sub meshes
  62412. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  62413. for (index = 0; index < sortedArray.length; index++) {
  62414. renderSubMesh(sortedArray[index]);
  62415. }
  62416. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  62417. }
  62418. };
  62419. };
  62420. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  62421. var transform = scene.getTransformMatrix();
  62422. var meshPosition;
  62423. if (this.useCustomMeshPosition) {
  62424. meshPosition = this.customMeshPosition;
  62425. }
  62426. else if (this.attachedNode) {
  62427. meshPosition = this.attachedNode.position;
  62428. }
  62429. else {
  62430. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  62431. }
  62432. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  62433. this._screenCoordinates.x = pos.x / this._viewPort.width;
  62434. this._screenCoordinates.y = pos.y / this._viewPort.height;
  62435. if (this.invert)
  62436. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  62437. };
  62438. // Static methods
  62439. /**
  62440. * Creates a default mesh for the Volumeric Light Scattering post-process
  62441. * @param {string} The mesh name
  62442. * @param {BABYLON.Scene} The scene where to create the mesh
  62443. * @return {BABYLON.Mesh} the default mesh
  62444. */
  62445. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  62446. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  62447. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  62448. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  62449. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  62450. mesh.material = material;
  62451. return mesh;
  62452. };
  62453. __decorate([
  62454. BABYLON.serializeAsVector3()
  62455. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  62456. __decorate([
  62457. BABYLON.serialize()
  62458. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  62459. __decorate([
  62460. BABYLON.serialize()
  62461. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  62462. __decorate([
  62463. BABYLON.serializeAsMeshReference()
  62464. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  62465. __decorate([
  62466. BABYLON.serialize()
  62467. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  62468. __decorate([
  62469. BABYLON.serialize()
  62470. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  62471. __decorate([
  62472. BABYLON.serialize()
  62473. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  62474. __decorate([
  62475. BABYLON.serialize()
  62476. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  62477. __decorate([
  62478. BABYLON.serialize()
  62479. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  62480. return VolumetricLightScatteringPostProcess;
  62481. }(BABYLON.PostProcess));
  62482. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  62483. })(BABYLON || (BABYLON = {}));
  62484. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  62485. //
  62486. // This post-process allows the modification of rendered colors by using
  62487. // a 'look-up table' (LUT). This effect is also called Color Grading.
  62488. //
  62489. // The object needs to be provided an url to a texture containing the color
  62490. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  62491. // Use an image editing software to tweak the LUT to match your needs.
  62492. //
  62493. // For an example of a color LUT, see here:
  62494. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  62495. // For explanations on color grading, see here:
  62496. // http://udn.epicgames.com/Three/ColorGrading.html
  62497. //
  62498. var BABYLON;
  62499. (function (BABYLON) {
  62500. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  62501. __extends(ColorCorrectionPostProcess, _super);
  62502. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  62503. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  62504. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  62505. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  62506. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62507. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62508. _this.onApply = function (effect) {
  62509. effect.setTexture("colorTable", _this._colorTableTexture);
  62510. };
  62511. return _this;
  62512. }
  62513. return ColorCorrectionPostProcess;
  62514. }(BABYLON.PostProcess));
  62515. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  62516. })(BABYLON || (BABYLON = {}));
  62517. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  62518. var BABYLON;
  62519. (function (BABYLON) {
  62520. var TonemappingOperator;
  62521. (function (TonemappingOperator) {
  62522. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  62523. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  62524. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  62525. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  62526. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  62527. ;
  62528. var TonemapPostProcess = /** @class */ (function (_super) {
  62529. __extends(TonemapPostProcess, _super);
  62530. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  62531. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62532. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62533. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  62534. _this._operator = _operator;
  62535. _this.exposureAdjustment = exposureAdjustment;
  62536. var defines = "#define ";
  62537. if (_this._operator === TonemappingOperator.Hable)
  62538. defines += "HABLE_TONEMAPPING";
  62539. else if (_this._operator === TonemappingOperator.Reinhard)
  62540. defines += "REINHARD_TONEMAPPING";
  62541. else if (_this._operator === TonemappingOperator.HejiDawson)
  62542. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  62543. else if (_this._operator === TonemappingOperator.Photographic)
  62544. defines += "PHOTOGRAPHIC_TONEMAPPING";
  62545. //sadly a second call to create the effect.
  62546. _this.updateEffect(defines);
  62547. _this.onApply = function (effect) {
  62548. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  62549. };
  62550. return _this;
  62551. }
  62552. return TonemapPostProcess;
  62553. }(BABYLON.PostProcess));
  62554. BABYLON.TonemapPostProcess = TonemapPostProcess;
  62555. })(BABYLON || (BABYLON = {}));
  62556. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  62557. var BABYLON;
  62558. (function (BABYLON) {
  62559. var DisplayPassPostProcess = /** @class */ (function (_super) {
  62560. __extends(DisplayPassPostProcess, _super);
  62561. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  62562. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  62563. }
  62564. return DisplayPassPostProcess;
  62565. }(BABYLON.PostProcess));
  62566. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  62567. })(BABYLON || (BABYLON = {}));
  62568. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  62569. var BABYLON;
  62570. (function (BABYLON) {
  62571. var HighlightsPostProcess = /** @class */ (function (_super) {
  62572. __extends(HighlightsPostProcess, _super);
  62573. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  62574. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62575. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  62576. }
  62577. return HighlightsPostProcess;
  62578. }(BABYLON.PostProcess));
  62579. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  62580. })(BABYLON || (BABYLON = {}));
  62581. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  62582. var BABYLON;
  62583. (function (BABYLON) {
  62584. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  62585. __extends(ImageProcessingPostProcess, _super);
  62586. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  62587. if (camera === void 0) { camera = null; }
  62588. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62589. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  62590. _this._fromLinearSpace = true;
  62591. /**
  62592. * Defines cache preventing GC.
  62593. */
  62594. _this._defines = {
  62595. IMAGEPROCESSING: false,
  62596. VIGNETTE: false,
  62597. VIGNETTEBLENDMODEMULTIPLY: false,
  62598. VIGNETTEBLENDMODEOPAQUE: false,
  62599. TONEMAPPING: false,
  62600. CONTRAST: false,
  62601. COLORCURVES: false,
  62602. COLORGRADING: false,
  62603. COLORGRADING3D: false,
  62604. FROMLINEARSPACE: false,
  62605. SAMPLER3DGREENDEPTH: false,
  62606. SAMPLER3DBGRMAP: false,
  62607. IMAGEPROCESSINGPOSTPROCESS: false,
  62608. EXPOSURE: false,
  62609. };
  62610. // Setup the configuration as forced by the constructor. This would then not force the
  62611. // scene materials output in linear space and let untouched the default forward pass.
  62612. if (imageProcessingConfiguration) {
  62613. imageProcessingConfiguration.applyByPostProcess = true;
  62614. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  62615. // This will cause the shader to be compiled
  62616. _this.fromLinearSpace = false;
  62617. }
  62618. else {
  62619. _this._attachImageProcessingConfiguration(null, true);
  62620. _this.imageProcessingConfiguration.applyByPostProcess = true;
  62621. }
  62622. _this.onApply = function (effect) {
  62623. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  62624. };
  62625. return _this;
  62626. }
  62627. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  62628. /**
  62629. * Gets the image processing configuration used either in this material.
  62630. */
  62631. get: function () {
  62632. return this._imageProcessingConfiguration;
  62633. },
  62634. /**
  62635. * Sets the Default image processing configuration used either in the this material.
  62636. *
  62637. * If sets to null, the scene one is in use.
  62638. */
  62639. set: function (value) {
  62640. this._attachImageProcessingConfiguration(value);
  62641. },
  62642. enumerable: true,
  62643. configurable: true
  62644. });
  62645. /**
  62646. * Attaches a new image processing configuration to the PBR Material.
  62647. * @param configuration
  62648. */
  62649. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  62650. var _this = this;
  62651. if (doNotBuild === void 0) { doNotBuild = false; }
  62652. if (configuration === this._imageProcessingConfiguration) {
  62653. return;
  62654. }
  62655. // Detaches observer.
  62656. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62657. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62658. }
  62659. // Pick the scene configuration if needed.
  62660. if (!configuration) {
  62661. var scene = null;
  62662. var engine = this.getEngine();
  62663. var camera = this.getCamera();
  62664. if (camera) {
  62665. scene = camera.getScene();
  62666. }
  62667. else if (engine && engine.scenes) {
  62668. var scenes = engine.scenes;
  62669. scene = scenes[scenes.length - 1];
  62670. }
  62671. else {
  62672. scene = BABYLON.Engine.LastCreatedScene;
  62673. }
  62674. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  62675. }
  62676. else {
  62677. this._imageProcessingConfiguration = configuration;
  62678. }
  62679. // Attaches observer.
  62680. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  62681. _this._updateParameters();
  62682. });
  62683. // Ensure the effect will be rebuilt.
  62684. if (!doNotBuild) {
  62685. this._updateParameters();
  62686. }
  62687. };
  62688. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  62689. /**
  62690. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62691. */
  62692. get: function () {
  62693. return this.imageProcessingConfiguration.colorCurves;
  62694. },
  62695. /**
  62696. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  62697. */
  62698. set: function (value) {
  62699. this.imageProcessingConfiguration.colorCurves = value;
  62700. },
  62701. enumerable: true,
  62702. configurable: true
  62703. });
  62704. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62705. /**
  62706. * Gets wether the color curves effect is enabled.
  62707. */
  62708. get: function () {
  62709. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62710. },
  62711. /**
  62712. * Sets wether the color curves effect is enabled.
  62713. */
  62714. set: function (value) {
  62715. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62716. },
  62717. enumerable: true,
  62718. configurable: true
  62719. });
  62720. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62721. /**
  62722. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62723. */
  62724. get: function () {
  62725. return this.imageProcessingConfiguration.colorGradingTexture;
  62726. },
  62727. /**
  62728. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62729. */
  62730. set: function (value) {
  62731. this.imageProcessingConfiguration.colorGradingTexture = value;
  62732. },
  62733. enumerable: true,
  62734. configurable: true
  62735. });
  62736. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62737. /**
  62738. * Gets wether the color grading effect is enabled.
  62739. */
  62740. get: function () {
  62741. return this.imageProcessingConfiguration.colorGradingEnabled;
  62742. },
  62743. /**
  62744. * Gets wether the color grading effect is enabled.
  62745. */
  62746. set: function (value) {
  62747. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62748. },
  62749. enumerable: true,
  62750. configurable: true
  62751. });
  62752. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62753. /**
  62754. * Gets exposure used in the effect.
  62755. */
  62756. get: function () {
  62757. return this.imageProcessingConfiguration.exposure;
  62758. },
  62759. /**
  62760. * Sets exposure used in the effect.
  62761. */
  62762. set: function (value) {
  62763. this.imageProcessingConfiguration.exposure = value;
  62764. },
  62765. enumerable: true,
  62766. configurable: true
  62767. });
  62768. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62769. /**
  62770. * Gets wether tonemapping is enabled or not.
  62771. */
  62772. get: function () {
  62773. return this._imageProcessingConfiguration.toneMappingEnabled;
  62774. },
  62775. /**
  62776. * Sets wether tonemapping is enabled or not
  62777. */
  62778. set: function (value) {
  62779. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62780. },
  62781. enumerable: true,
  62782. configurable: true
  62783. });
  62784. ;
  62785. ;
  62786. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62787. /**
  62788. * Gets contrast used in the effect.
  62789. */
  62790. get: function () {
  62791. return this.imageProcessingConfiguration.contrast;
  62792. },
  62793. /**
  62794. * Sets contrast used in the effect.
  62795. */
  62796. set: function (value) {
  62797. this.imageProcessingConfiguration.contrast = value;
  62798. },
  62799. enumerable: true,
  62800. configurable: true
  62801. });
  62802. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62803. /**
  62804. * Gets Vignette stretch size.
  62805. */
  62806. get: function () {
  62807. return this.imageProcessingConfiguration.vignetteStretch;
  62808. },
  62809. /**
  62810. * Sets Vignette stretch size.
  62811. */
  62812. set: function (value) {
  62813. this.imageProcessingConfiguration.vignetteStretch = value;
  62814. },
  62815. enumerable: true,
  62816. configurable: true
  62817. });
  62818. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62819. /**
  62820. * Gets Vignette centre X Offset.
  62821. */
  62822. get: function () {
  62823. return this.imageProcessingConfiguration.vignetteCentreX;
  62824. },
  62825. /**
  62826. * Sets Vignette centre X Offset.
  62827. */
  62828. set: function (value) {
  62829. this.imageProcessingConfiguration.vignetteCentreX = value;
  62830. },
  62831. enumerable: true,
  62832. configurable: true
  62833. });
  62834. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  62835. /**
  62836. * Gets Vignette centre Y Offset.
  62837. */
  62838. get: function () {
  62839. return this.imageProcessingConfiguration.vignetteCentreY;
  62840. },
  62841. /**
  62842. * Sets Vignette centre Y Offset.
  62843. */
  62844. set: function (value) {
  62845. this.imageProcessingConfiguration.vignetteCentreY = value;
  62846. },
  62847. enumerable: true,
  62848. configurable: true
  62849. });
  62850. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  62851. /**
  62852. * Gets Vignette weight or intensity of the vignette effect.
  62853. */
  62854. get: function () {
  62855. return this.imageProcessingConfiguration.vignetteWeight;
  62856. },
  62857. /**
  62858. * Sets Vignette weight or intensity of the vignette effect.
  62859. */
  62860. set: function (value) {
  62861. this.imageProcessingConfiguration.vignetteWeight = value;
  62862. },
  62863. enumerable: true,
  62864. configurable: true
  62865. });
  62866. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  62867. /**
  62868. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62869. * if vignetteEnabled is set to true.
  62870. */
  62871. get: function () {
  62872. return this.imageProcessingConfiguration.vignetteColor;
  62873. },
  62874. /**
  62875. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62876. * if vignetteEnabled is set to true.
  62877. */
  62878. set: function (value) {
  62879. this.imageProcessingConfiguration.vignetteColor = value;
  62880. },
  62881. enumerable: true,
  62882. configurable: true
  62883. });
  62884. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  62885. /**
  62886. * Gets Camera field of view used by the Vignette effect.
  62887. */
  62888. get: function () {
  62889. return this.imageProcessingConfiguration.vignetteCameraFov;
  62890. },
  62891. /**
  62892. * Sets Camera field of view used by the Vignette effect.
  62893. */
  62894. set: function (value) {
  62895. this.imageProcessingConfiguration.vignetteCameraFov = value;
  62896. },
  62897. enumerable: true,
  62898. configurable: true
  62899. });
  62900. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  62901. /**
  62902. * Gets the vignette blend mode allowing different kind of effect.
  62903. */
  62904. get: function () {
  62905. return this.imageProcessingConfiguration.vignetteBlendMode;
  62906. },
  62907. /**
  62908. * Sets the vignette blend mode allowing different kind of effect.
  62909. */
  62910. set: function (value) {
  62911. this.imageProcessingConfiguration.vignetteBlendMode = value;
  62912. },
  62913. enumerable: true,
  62914. configurable: true
  62915. });
  62916. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  62917. /**
  62918. * Gets wether the vignette effect is enabled.
  62919. */
  62920. get: function () {
  62921. return this.imageProcessingConfiguration.vignetteEnabled;
  62922. },
  62923. /**
  62924. * Sets wether the vignette effect is enabled.
  62925. */
  62926. set: function (value) {
  62927. this.imageProcessingConfiguration.vignetteEnabled = value;
  62928. },
  62929. enumerable: true,
  62930. configurable: true
  62931. });
  62932. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  62933. /**
  62934. * Gets wether the input of the processing is in Gamma or Linear Space.
  62935. */
  62936. get: function () {
  62937. return this._fromLinearSpace;
  62938. },
  62939. /**
  62940. * Sets wether the input of the processing is in Gamma or Linear Space.
  62941. */
  62942. set: function (value) {
  62943. if (this._fromLinearSpace === value) {
  62944. return;
  62945. }
  62946. this._fromLinearSpace = value;
  62947. this._updateParameters();
  62948. },
  62949. enumerable: true,
  62950. configurable: true
  62951. });
  62952. ImageProcessingPostProcess.prototype.getClassName = function () {
  62953. return "ImageProcessingPostProcess";
  62954. };
  62955. ImageProcessingPostProcess.prototype._updateParameters = function () {
  62956. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  62957. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  62958. var defines = "";
  62959. for (var define in this._defines) {
  62960. if (this._defines[define]) {
  62961. defines += "#define " + define + ";\r\n";
  62962. }
  62963. }
  62964. var samplers = ["textureSampler"];
  62965. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  62966. var uniforms = ["scale"];
  62967. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  62968. this.updateEffect(defines, uniforms, samplers);
  62969. };
  62970. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  62971. _super.prototype.dispose.call(this, camera);
  62972. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62973. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62974. }
  62975. this.imageProcessingConfiguration.applyByPostProcess = false;
  62976. };
  62977. __decorate([
  62978. BABYLON.serialize()
  62979. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  62980. return ImageProcessingPostProcess;
  62981. }(BABYLON.PostProcess));
  62982. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  62983. })(BABYLON || (BABYLON = {}));
  62984. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  62985. var BABYLON;
  62986. (function (BABYLON) {
  62987. var BlurPostProcess = /** @class */ (function (_super) {
  62988. __extends(BlurPostProcess, _super);
  62989. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  62990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62991. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62992. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  62993. _this.direction = direction;
  62994. _this._packedFloat = false;
  62995. _this.onApplyObservable.add(function (effect) {
  62996. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  62997. });
  62998. _this.kernel = kernel;
  62999. return _this;
  63000. }
  63001. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  63002. /**
  63003. * Gets the length in pixels of the blur sample region
  63004. */
  63005. get: function () {
  63006. return this._idealKernel;
  63007. },
  63008. /**
  63009. * Sets the length in pixels of the blur sample region
  63010. */
  63011. set: function (v) {
  63012. if (this._idealKernel === v) {
  63013. return;
  63014. }
  63015. v = Math.max(v, 1);
  63016. this._idealKernel = v;
  63017. this._kernel = this._nearestBestKernel(v);
  63018. this._updateParameters();
  63019. },
  63020. enumerable: true,
  63021. configurable: true
  63022. });
  63023. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  63024. /**
  63025. * Gets wether or not the blur is unpacking/repacking floats
  63026. */
  63027. get: function () {
  63028. return this._packedFloat;
  63029. },
  63030. /**
  63031. * Sets wether or not the blur needs to unpack/repack floats
  63032. */
  63033. set: function (v) {
  63034. if (this._packedFloat === v) {
  63035. return;
  63036. }
  63037. this._packedFloat = v;
  63038. this._updateParameters();
  63039. },
  63040. enumerable: true,
  63041. configurable: true
  63042. });
  63043. BlurPostProcess.prototype._updateParameters = function () {
  63044. // Generate sampling offsets and weights
  63045. var N = this._kernel;
  63046. var centerIndex = (N - 1) / 2;
  63047. // Generate Gaussian sampling weights over kernel
  63048. var offsets = [];
  63049. var weights = [];
  63050. var totalWeight = 0;
  63051. for (var i = 0; i < N; i++) {
  63052. var u = i / (N - 1);
  63053. var w = this._gaussianWeight(u * 2.0 - 1);
  63054. offsets[i] = (i - centerIndex);
  63055. weights[i] = w;
  63056. totalWeight += w;
  63057. }
  63058. // Normalize weights
  63059. for (var i = 0; i < weights.length; i++) {
  63060. weights[i] /= totalWeight;
  63061. }
  63062. // Optimize: combine samples to take advantage of hardware linear sampling
  63063. // Walk from left to center, combining pairs (symmetrically)
  63064. var linearSamplingWeights = [];
  63065. var linearSamplingOffsets = [];
  63066. var linearSamplingMap = [];
  63067. for (var i = 0; i <= centerIndex; i += 2) {
  63068. var j = Math.min(i + 1, Math.floor(centerIndex));
  63069. var singleCenterSample = i === j;
  63070. if (singleCenterSample) {
  63071. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63072. }
  63073. else {
  63074. var sharedCell = j === centerIndex;
  63075. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  63076. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  63077. if (offsetLinear === 0) {
  63078. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  63079. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  63080. }
  63081. else {
  63082. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  63083. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  63084. }
  63085. }
  63086. }
  63087. for (var i = 0; i < linearSamplingMap.length; i++) {
  63088. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  63089. linearSamplingWeights[i] = linearSamplingMap[i].w;
  63090. }
  63091. // Replace with optimized
  63092. offsets = linearSamplingOffsets;
  63093. weights = linearSamplingWeights;
  63094. // Generate shaders
  63095. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  63096. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  63097. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  63098. var defines = "";
  63099. for (var i = 0; i < varyingCount; i++) {
  63100. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  63101. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  63102. }
  63103. var depCount = 0;
  63104. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  63105. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  63106. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  63107. depCount++;
  63108. }
  63109. if (this.packedFloat) {
  63110. defines += "#define PACKEDFLOAT 1";
  63111. }
  63112. this.updateEffect(defines, null, null, {
  63113. varyingCount: varyingCount,
  63114. depCount: depCount
  63115. });
  63116. };
  63117. /**
  63118. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  63119. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  63120. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  63121. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  63122. * The gaps between physical kernels are compensated for in the weighting of the samples
  63123. * @param idealKernel Ideal blur kernel.
  63124. * @return Nearest best kernel.
  63125. */
  63126. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  63127. var v = Math.round(idealKernel);
  63128. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  63129. var k = _a[_i];
  63130. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  63131. return Math.max(k, 3);
  63132. }
  63133. }
  63134. return Math.max(v, 3);
  63135. };
  63136. /**
  63137. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  63138. * @param x The point on the Gaussian distribution to sample.
  63139. * @return the value of the Gaussian function at x.
  63140. */
  63141. BlurPostProcess.prototype._gaussianWeight = function (x) {
  63142. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  63143. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  63144. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  63145. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  63146. // truncated at around 1.3% of peak strength.
  63147. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  63148. var sigma = (1 / 3);
  63149. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  63150. var exponent = -((x * x) / (2.0 * sigma * sigma));
  63151. var weight = (1.0 / denominator) * Math.exp(exponent);
  63152. return weight;
  63153. };
  63154. /**
  63155. * Generates a string that can be used as a floating point number in GLSL.
  63156. * @param x Value to print.
  63157. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  63158. * @return GLSL float string.
  63159. */
  63160. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  63161. if (decimalFigures === void 0) { decimalFigures = 8; }
  63162. return x.toFixed(decimalFigures).replace(/0+$/, '');
  63163. };
  63164. return BlurPostProcess;
  63165. }(BABYLON.PostProcess));
  63166. BABYLON.BlurPostProcess = BlurPostProcess;
  63167. })(BABYLON || (BABYLON = {}));
  63168. //# sourceMappingURL=babylon.blurPostProcess.js.map
  63169. var BABYLON;
  63170. (function (BABYLON) {
  63171. var Bone = /** @class */ (function (_super) {
  63172. __extends(Bone, _super);
  63173. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  63174. if (parentBone === void 0) { parentBone = null; }
  63175. if (localMatrix === void 0) { localMatrix = null; }
  63176. if (restPose === void 0) { restPose = null; }
  63177. if (baseMatrix === void 0) { baseMatrix = null; }
  63178. if (index === void 0) { index = null; }
  63179. var _this = _super.call(this, name, skeleton.getScene()) || this;
  63180. _this.name = name;
  63181. _this.children = new Array();
  63182. _this.animations = new Array();
  63183. // Set this value to map this bone to a different index in the transform matrices.
  63184. // Set this value to -1 to exclude the bone from the transform matrices.
  63185. _this._index = null;
  63186. _this._worldTransform = new BABYLON.Matrix();
  63187. _this._absoluteTransform = new BABYLON.Matrix();
  63188. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  63189. _this._scaleMatrix = BABYLON.Matrix.Identity();
  63190. _this._scaleVector = BABYLON.Vector3.One();
  63191. _this._negateScaleChildren = BABYLON.Vector3.One();
  63192. _this._scalingDeterminant = 1;
  63193. _this._skeleton = skeleton;
  63194. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  63195. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  63196. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  63197. _this._index = index;
  63198. skeleton.bones.push(_this);
  63199. _this.setParent(parentBone, false);
  63200. _this._updateDifferenceMatrix();
  63201. return _this;
  63202. }
  63203. Object.defineProperty(Bone.prototype, "_matrix", {
  63204. get: function () {
  63205. return this._localMatrix;
  63206. },
  63207. set: function (val) {
  63208. if (this._localMatrix) {
  63209. this._localMatrix.copyFrom(val);
  63210. }
  63211. else {
  63212. this._localMatrix = val;
  63213. }
  63214. },
  63215. enumerable: true,
  63216. configurable: true
  63217. });
  63218. // Members
  63219. Bone.prototype.getSkeleton = function () {
  63220. return this._skeleton;
  63221. };
  63222. Bone.prototype.getParent = function () {
  63223. return this._parent;
  63224. };
  63225. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  63226. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63227. if (this._parent === parent) {
  63228. return;
  63229. }
  63230. if (this._parent) {
  63231. var index = this._parent.children.indexOf(this);
  63232. if (index !== -1) {
  63233. this._parent.children.splice(index, 1);
  63234. }
  63235. }
  63236. this._parent = parent;
  63237. if (this._parent) {
  63238. this._parent.children.push(this);
  63239. }
  63240. if (updateDifferenceMatrix) {
  63241. this._updateDifferenceMatrix();
  63242. }
  63243. };
  63244. Bone.prototype.getLocalMatrix = function () {
  63245. return this._localMatrix;
  63246. };
  63247. Bone.prototype.getBaseMatrix = function () {
  63248. return this._baseMatrix;
  63249. };
  63250. Bone.prototype.getRestPose = function () {
  63251. return this._restPose;
  63252. };
  63253. Bone.prototype.returnToRest = function () {
  63254. this.updateMatrix(this._restPose.clone());
  63255. };
  63256. Bone.prototype.getWorldMatrix = function () {
  63257. return this._worldTransform;
  63258. };
  63259. Bone.prototype.getInvertedAbsoluteTransform = function () {
  63260. return this._invertedAbsoluteTransform;
  63261. };
  63262. Bone.prototype.getAbsoluteTransform = function () {
  63263. return this._absoluteTransform;
  63264. };
  63265. Object.defineProperty(Bone.prototype, "position", {
  63266. // Properties (matches AbstractMesh properties)
  63267. get: function () {
  63268. return this.getPosition();
  63269. },
  63270. set: function (newPosition) {
  63271. this.setPosition(newPosition);
  63272. },
  63273. enumerable: true,
  63274. configurable: true
  63275. });
  63276. Object.defineProperty(Bone.prototype, "rotation", {
  63277. get: function () {
  63278. return this.getRotation();
  63279. },
  63280. set: function (newRotation) {
  63281. this.setRotation(newRotation);
  63282. },
  63283. enumerable: true,
  63284. configurable: true
  63285. });
  63286. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  63287. get: function () {
  63288. return this.getRotationQuaternion();
  63289. },
  63290. set: function (newRotation) {
  63291. this.setRotationQuaternion(newRotation);
  63292. },
  63293. enumerable: true,
  63294. configurable: true
  63295. });
  63296. Object.defineProperty(Bone.prototype, "scaling", {
  63297. get: function () {
  63298. return this.getScale();
  63299. },
  63300. set: function (newScaling) {
  63301. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  63302. },
  63303. enumerable: true,
  63304. configurable: true
  63305. });
  63306. // Methods
  63307. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  63308. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  63309. this._baseMatrix = matrix.clone();
  63310. this._localMatrix = matrix.clone();
  63311. this._skeleton._markAsDirty();
  63312. if (updateDifferenceMatrix) {
  63313. this._updateDifferenceMatrix();
  63314. }
  63315. };
  63316. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  63317. if (!rootMatrix) {
  63318. rootMatrix = this._baseMatrix;
  63319. }
  63320. if (this._parent) {
  63321. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63322. }
  63323. else {
  63324. this._absoluteTransform.copyFrom(rootMatrix);
  63325. }
  63326. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  63327. for (var index = 0; index < this.children.length; index++) {
  63328. this.children[index]._updateDifferenceMatrix();
  63329. }
  63330. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  63331. };
  63332. Bone.prototype.markAsDirty = function () {
  63333. this._currentRenderId++;
  63334. this._skeleton._markAsDirty();
  63335. };
  63336. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  63337. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  63338. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  63339. // all animation may be coming from a library skeleton, so may need to create animation
  63340. if (this.animations.length === 0) {
  63341. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  63342. this.animations[0].setKeys([]);
  63343. }
  63344. // get animation info / verify there is such a range from the source bone
  63345. var sourceRange = source.animations[0].getRange(rangeName);
  63346. if (!sourceRange) {
  63347. return false;
  63348. }
  63349. var from = sourceRange.from;
  63350. var to = sourceRange.to;
  63351. var sourceKeys = source.animations[0].getKeys();
  63352. // rescaling prep
  63353. var sourceBoneLength = source.length;
  63354. var sourceParent = source.getParent();
  63355. var parent = this.getParent();
  63356. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  63357. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  63358. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  63359. var destKeys = this.animations[0].getKeys();
  63360. // loop vars declaration
  63361. var orig;
  63362. var origTranslation;
  63363. var mat;
  63364. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  63365. orig = sourceKeys[key];
  63366. if (orig.frame >= from && orig.frame <= to) {
  63367. if (rescaleAsRequired) {
  63368. mat = orig.value.clone();
  63369. // scale based on parent ratio, when bone has parent
  63370. if (parentScalingReqd) {
  63371. origTranslation = mat.getTranslation();
  63372. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  63373. // scale based on skeleton dimension ratio when root bone, and value is passed
  63374. }
  63375. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  63376. origTranslation = mat.getTranslation();
  63377. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  63378. // use original when root bone, and no data for skelDimensionsRatio
  63379. }
  63380. else {
  63381. mat = orig.value;
  63382. }
  63383. }
  63384. else {
  63385. mat = orig.value;
  63386. }
  63387. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  63388. }
  63389. }
  63390. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  63391. return true;
  63392. };
  63393. /**
  63394. * Translate the bone in local or world space.
  63395. * @param vec The amount to translate the bone.
  63396. * @param space The space that the translation is in.
  63397. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63398. */
  63399. Bone.prototype.translate = function (vec, space, mesh) {
  63400. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63401. var lm = this.getLocalMatrix();
  63402. if (space == BABYLON.Space.LOCAL) {
  63403. lm.m[12] += vec.x;
  63404. lm.m[13] += vec.y;
  63405. lm.m[14] += vec.z;
  63406. }
  63407. else {
  63408. var wm = null;
  63409. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63410. if (mesh) {
  63411. wm = mesh.getWorldMatrix();
  63412. }
  63413. this._skeleton.computeAbsoluteTransforms();
  63414. var tmat = Bone._tmpMats[0];
  63415. var tvec = Bone._tmpVecs[0];
  63416. if (this._parent) {
  63417. if (mesh && wm) {
  63418. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63419. tmat.multiplyToRef(wm, tmat);
  63420. }
  63421. else {
  63422. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63423. }
  63424. }
  63425. tmat.m[12] = 0;
  63426. tmat.m[13] = 0;
  63427. tmat.m[14] = 0;
  63428. tmat.invert();
  63429. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  63430. lm.m[12] += tvec.x;
  63431. lm.m[13] += tvec.y;
  63432. lm.m[14] += tvec.z;
  63433. }
  63434. this.markAsDirty();
  63435. };
  63436. /**
  63437. * Set the postion of the bone in local or world space.
  63438. * @param position The position to set the bone.
  63439. * @param space The space that the position is in.
  63440. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63441. */
  63442. Bone.prototype.setPosition = function (position, space, mesh) {
  63443. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63444. var lm = this.getLocalMatrix();
  63445. if (space == BABYLON.Space.LOCAL) {
  63446. lm.m[12] = position.x;
  63447. lm.m[13] = position.y;
  63448. lm.m[14] = position.z;
  63449. }
  63450. else {
  63451. var wm = null;
  63452. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63453. if (mesh) {
  63454. wm = mesh.getWorldMatrix();
  63455. }
  63456. this._skeleton.computeAbsoluteTransforms();
  63457. var tmat = Bone._tmpMats[0];
  63458. var vec = Bone._tmpVecs[0];
  63459. if (this._parent) {
  63460. if (mesh && wm) {
  63461. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63462. tmat.multiplyToRef(wm, tmat);
  63463. }
  63464. else {
  63465. tmat.copyFrom(this._parent.getAbsoluteTransform());
  63466. }
  63467. }
  63468. tmat.invert();
  63469. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  63470. lm.m[12] = vec.x;
  63471. lm.m[13] = vec.y;
  63472. lm.m[14] = vec.z;
  63473. }
  63474. this.markAsDirty();
  63475. };
  63476. /**
  63477. * Set the absolute postion of the bone (world space).
  63478. * @param position The position to set the bone.
  63479. * @param mesh The mesh that this bone is attached to.
  63480. */
  63481. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  63482. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  63483. };
  63484. /**
  63485. * Set the scale of the bone on the x, y and z axes.
  63486. * @param x The scale of the bone on the x axis.
  63487. * @param x The scale of the bone on the y axis.
  63488. * @param z The scale of the bone on the z axis.
  63489. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63490. */
  63491. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  63492. if (scaleChildren === void 0) { scaleChildren = false; }
  63493. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  63494. if (!scaleChildren) {
  63495. this._negateScaleChildren.x = 1 / x;
  63496. this._negateScaleChildren.y = 1 / y;
  63497. this._negateScaleChildren.z = 1 / z;
  63498. }
  63499. this._syncScaleVector();
  63500. }
  63501. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  63502. };
  63503. /**
  63504. * Scale the bone on the x, y and z axes.
  63505. * @param x The amount to scale the bone on the x axis.
  63506. * @param x The amount to scale the bone on the y axis.
  63507. * @param z The amount to scale the bone on the z axis.
  63508. * @param scaleChildren Set this to true if children of the bone should be scaled.
  63509. */
  63510. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  63511. if (scaleChildren === void 0) { scaleChildren = false; }
  63512. var locMat = this.getLocalMatrix();
  63513. var origLocMat = Bone._tmpMats[0];
  63514. origLocMat.copyFrom(locMat);
  63515. var origLocMatInv = Bone._tmpMats[1];
  63516. origLocMatInv.copyFrom(origLocMat);
  63517. origLocMatInv.invert();
  63518. var scaleMat = Bone._tmpMats[2];
  63519. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  63520. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  63521. this._scaleVector.x *= x;
  63522. this._scaleVector.y *= y;
  63523. this._scaleVector.z *= z;
  63524. locMat.multiplyToRef(origLocMatInv, locMat);
  63525. locMat.multiplyToRef(scaleMat, locMat);
  63526. locMat.multiplyToRef(origLocMat, locMat);
  63527. var parent = this.getParent();
  63528. if (parent) {
  63529. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  63530. }
  63531. else {
  63532. this.getAbsoluteTransform().copyFrom(locMat);
  63533. }
  63534. var len = this.children.length;
  63535. scaleMat.invert();
  63536. for (var i = 0; i < len; i++) {
  63537. var child = this.children[i];
  63538. var cm = child.getLocalMatrix();
  63539. cm.multiplyToRef(scaleMat, cm);
  63540. var lm = child.getLocalMatrix();
  63541. lm.m[12] *= x;
  63542. lm.m[13] *= y;
  63543. lm.m[14] *= z;
  63544. }
  63545. this.computeAbsoluteTransforms();
  63546. if (scaleChildren) {
  63547. for (var i = 0; i < len; i++) {
  63548. this.children[i].scale(x, y, z, scaleChildren);
  63549. }
  63550. }
  63551. this.markAsDirty();
  63552. };
  63553. /**
  63554. * Set the yaw, pitch, and roll of the bone in local or world space.
  63555. * @param yaw The rotation of the bone on the y axis.
  63556. * @param pitch The rotation of the bone on the x axis.
  63557. * @param roll The rotation of the bone on the z axis.
  63558. * @param space The space that the axes of rotation are in.
  63559. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63560. */
  63561. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  63562. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63563. var rotMat = Bone._tmpMats[0];
  63564. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  63565. var rotMatInv = Bone._tmpMats[1];
  63566. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63567. rotMatInv.multiplyToRef(rotMat, rotMat);
  63568. this._rotateWithMatrix(rotMat, space, mesh);
  63569. };
  63570. /**
  63571. * Rotate the bone on an axis in local or world space.
  63572. * @param axis The axis to rotate the bone on.
  63573. * @param amount The amount to rotate the bone.
  63574. * @param space The space that the axis is in.
  63575. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63576. */
  63577. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  63578. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63579. var rmat = Bone._tmpMats[0];
  63580. rmat.m[12] = 0;
  63581. rmat.m[13] = 0;
  63582. rmat.m[14] = 0;
  63583. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  63584. this._rotateWithMatrix(rmat, space, mesh);
  63585. };
  63586. /**
  63587. * Set the rotation of the bone to a particular axis angle in local or world space.
  63588. * @param axis The axis to rotate the bone on.
  63589. * @param angle The angle that the bone should be rotated to.
  63590. * @param space The space that the axis is in.
  63591. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63592. */
  63593. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  63594. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63595. var rotMat = Bone._tmpMats[0];
  63596. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  63597. var rotMatInv = Bone._tmpMats[1];
  63598. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63599. rotMatInv.multiplyToRef(rotMat, rotMat);
  63600. this._rotateWithMatrix(rotMat, space, mesh);
  63601. };
  63602. /**
  63603. * Set the euler rotation of the bone in local of world space.
  63604. * @param rotation The euler rotation that the bone should be set to.
  63605. * @param space The space that the rotation is in.
  63606. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63607. */
  63608. Bone.prototype.setRotation = function (rotation, space, mesh) {
  63609. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63610. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  63611. };
  63612. /**
  63613. * Set the quaternion rotation of the bone in local of world space.
  63614. * @param quat The quaternion rotation that the bone should be set to.
  63615. * @param space The space that the rotation is in.
  63616. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63617. */
  63618. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  63619. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63620. var rotMatInv = Bone._tmpMats[0];
  63621. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63622. var rotMat = Bone._tmpMats[1];
  63623. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  63624. rotMatInv.multiplyToRef(rotMat, rotMat);
  63625. this._rotateWithMatrix(rotMat, space, mesh);
  63626. };
  63627. /**
  63628. * Set the rotation matrix of the bone in local of world space.
  63629. * @param rotMat The rotation matrix that the bone should be set to.
  63630. * @param space The space that the rotation is in.
  63631. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63632. */
  63633. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  63634. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63635. var rotMatInv = Bone._tmpMats[0];
  63636. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  63637. var rotMat2 = Bone._tmpMats[1];
  63638. rotMat2.copyFrom(rotMat);
  63639. rotMatInv.multiplyToRef(rotMat, rotMat2);
  63640. this._rotateWithMatrix(rotMat2, space, mesh);
  63641. };
  63642. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  63643. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63644. var lmat = this.getLocalMatrix();
  63645. var lx = lmat.m[12];
  63646. var ly = lmat.m[13];
  63647. var lz = lmat.m[14];
  63648. var parent = this.getParent();
  63649. var parentScale = Bone._tmpMats[3];
  63650. var parentScaleInv = Bone._tmpMats[4];
  63651. if (parent) {
  63652. if (space == BABYLON.Space.WORLD) {
  63653. if (mesh) {
  63654. parentScale.copyFrom(mesh.getWorldMatrix());
  63655. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  63656. }
  63657. else {
  63658. parentScale.copyFrom(parent.getAbsoluteTransform());
  63659. }
  63660. }
  63661. else {
  63662. parentScale = parent._scaleMatrix;
  63663. }
  63664. parentScaleInv.copyFrom(parentScale);
  63665. parentScaleInv.invert();
  63666. lmat.multiplyToRef(parentScale, lmat);
  63667. lmat.multiplyToRef(rmat, lmat);
  63668. lmat.multiplyToRef(parentScaleInv, lmat);
  63669. }
  63670. else {
  63671. if (space == BABYLON.Space.WORLD && mesh) {
  63672. parentScale.copyFrom(mesh.getWorldMatrix());
  63673. parentScaleInv.copyFrom(parentScale);
  63674. parentScaleInv.invert();
  63675. lmat.multiplyToRef(parentScale, lmat);
  63676. lmat.multiplyToRef(rmat, lmat);
  63677. lmat.multiplyToRef(parentScaleInv, lmat);
  63678. }
  63679. else {
  63680. lmat.multiplyToRef(rmat, lmat);
  63681. }
  63682. }
  63683. lmat.m[12] = lx;
  63684. lmat.m[13] = ly;
  63685. lmat.m[14] = lz;
  63686. this.computeAbsoluteTransforms();
  63687. this.markAsDirty();
  63688. };
  63689. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  63690. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63691. if (space == BABYLON.Space.WORLD) {
  63692. var scaleMatrix = Bone._tmpMats[2];
  63693. scaleMatrix.copyFrom(this._scaleMatrix);
  63694. rotMatInv.copyFrom(this.getAbsoluteTransform());
  63695. if (mesh) {
  63696. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  63697. var meshScale = Bone._tmpMats[3];
  63698. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  63699. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  63700. }
  63701. rotMatInv.invert();
  63702. scaleMatrix.m[0] *= this._scalingDeterminant;
  63703. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63704. }
  63705. else {
  63706. rotMatInv.copyFrom(this.getLocalMatrix());
  63707. rotMatInv.invert();
  63708. var scaleMatrix = Bone._tmpMats[2];
  63709. scaleMatrix.copyFrom(this._scaleMatrix);
  63710. if (this._parent) {
  63711. var pscaleMatrix = Bone._tmpMats[3];
  63712. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63713. pscaleMatrix.invert();
  63714. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63715. }
  63716. else {
  63717. scaleMatrix.m[0] *= this._scalingDeterminant;
  63718. }
  63719. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63720. }
  63721. };
  63722. /**
  63723. * Get the scale of the bone
  63724. * @returns the scale of the bone
  63725. */
  63726. Bone.prototype.getScale = function () {
  63727. return this._scaleVector.clone();
  63728. };
  63729. /**
  63730. * Copy the scale of the bone to a vector3.
  63731. * @param result The vector3 to copy the scale to
  63732. */
  63733. Bone.prototype.getScaleToRef = function (result) {
  63734. result.copyFrom(this._scaleVector);
  63735. };
  63736. /**
  63737. * Get the position of the bone in local or world space.
  63738. * @param space The space that the returned position is in.
  63739. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63740. * @returns The position of the bone
  63741. */
  63742. Bone.prototype.getPosition = function (space, mesh) {
  63743. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63744. if (mesh === void 0) { mesh = null; }
  63745. var pos = BABYLON.Vector3.Zero();
  63746. this.getPositionToRef(space, mesh, pos);
  63747. return pos;
  63748. };
  63749. /**
  63750. * Copy the position of the bone to a vector3 in local or world space.
  63751. * @param space The space that the returned position is in.
  63752. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63753. * @param result The vector3 to copy the position to.
  63754. */
  63755. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63756. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63757. if (space == BABYLON.Space.LOCAL) {
  63758. var lm = this.getLocalMatrix();
  63759. result.x = lm.m[12];
  63760. result.y = lm.m[13];
  63761. result.z = lm.m[14];
  63762. }
  63763. else {
  63764. var wm = null;
  63765. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63766. if (mesh) {
  63767. wm = mesh.getWorldMatrix();
  63768. }
  63769. this._skeleton.computeAbsoluteTransforms();
  63770. var tmat = Bone._tmpMats[0];
  63771. if (mesh && wm) {
  63772. tmat.copyFrom(this.getAbsoluteTransform());
  63773. tmat.multiplyToRef(wm, tmat);
  63774. }
  63775. else {
  63776. tmat = this.getAbsoluteTransform();
  63777. }
  63778. result.x = tmat.m[12];
  63779. result.y = tmat.m[13];
  63780. result.z = tmat.m[14];
  63781. }
  63782. };
  63783. /**
  63784. * Get the absolute position of the bone (world space).
  63785. * @param mesh The mesh that this bone is attached to.
  63786. * @returns The absolute position of the bone
  63787. */
  63788. Bone.prototype.getAbsolutePosition = function (mesh) {
  63789. if (mesh === void 0) { mesh = null; }
  63790. var pos = BABYLON.Vector3.Zero();
  63791. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63792. return pos;
  63793. };
  63794. /**
  63795. * Copy the absolute position of the bone (world space) to the result param.
  63796. * @param mesh The mesh that this bone is attached to.
  63797. * @param result The vector3 to copy the absolute position to.
  63798. */
  63799. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63800. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63801. };
  63802. /**
  63803. * Compute the absolute transforms of this bone and its children.
  63804. */
  63805. Bone.prototype.computeAbsoluteTransforms = function () {
  63806. if (this._parent) {
  63807. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63808. }
  63809. else {
  63810. this._absoluteTransform.copyFrom(this._localMatrix);
  63811. var poseMatrix = this._skeleton.getPoseMatrix();
  63812. if (poseMatrix) {
  63813. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63814. }
  63815. }
  63816. var children = this.children;
  63817. var len = children.length;
  63818. for (var i = 0; i < len; i++) {
  63819. children[i].computeAbsoluteTransforms();
  63820. }
  63821. };
  63822. Bone.prototype._syncScaleVector = function () {
  63823. var lm = this.getLocalMatrix();
  63824. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63825. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63826. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63827. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63828. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63829. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63830. this._scaleVector.x = xs * Math.sqrt(xsq);
  63831. this._scaleVector.y = ys * Math.sqrt(ysq);
  63832. this._scaleVector.z = zs * Math.sqrt(zsq);
  63833. if (this._parent) {
  63834. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  63835. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  63836. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  63837. }
  63838. 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);
  63839. };
  63840. /**
  63841. * Get the world direction from an axis that is in the local space of the bone.
  63842. * @param localAxis The local direction that is used to compute the world direction.
  63843. * @param mesh The mesh that this bone is attached to.
  63844. * @returns The world direction
  63845. */
  63846. Bone.prototype.getDirection = function (localAxis, mesh) {
  63847. if (mesh === void 0) { mesh = null; }
  63848. var result = BABYLON.Vector3.Zero();
  63849. this.getDirectionToRef(localAxis, mesh, result);
  63850. return result;
  63851. };
  63852. /**
  63853. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  63854. * @param localAxis The local direction that is used to compute the world direction.
  63855. * @param mesh The mesh that this bone is attached to.
  63856. * @param result The vector3 that the world direction will be copied to.
  63857. */
  63858. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  63859. if (mesh === void 0) { mesh = null; }
  63860. var wm = null;
  63861. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63862. if (mesh) {
  63863. wm = mesh.getWorldMatrix();
  63864. }
  63865. this._skeleton.computeAbsoluteTransforms();
  63866. var mat = Bone._tmpMats[0];
  63867. mat.copyFrom(this.getAbsoluteTransform());
  63868. if (mesh && wm) {
  63869. mat.multiplyToRef(wm, mat);
  63870. }
  63871. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  63872. result.normalize();
  63873. };
  63874. /**
  63875. * Get the euler rotation of the bone in local or world space.
  63876. * @param space The space that the rotation should be in.
  63877. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63878. * @returns The euler rotation
  63879. */
  63880. Bone.prototype.getRotation = function (space, mesh) {
  63881. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63882. if (mesh === void 0) { mesh = null; }
  63883. var result = BABYLON.Vector3.Zero();
  63884. this.getRotationToRef(space, mesh, result);
  63885. return result;
  63886. };
  63887. /**
  63888. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  63889. * @param space The space that the rotation should be in.
  63890. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63891. * @param result The vector3 that the rotation should be copied to.
  63892. */
  63893. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  63894. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63895. if (mesh === void 0) { mesh = null; }
  63896. var quat = Bone._tmpQuat;
  63897. this.getRotationQuaternionToRef(space, mesh, quat);
  63898. quat.toEulerAnglesToRef(result);
  63899. };
  63900. /**
  63901. * Get the quaternion rotation of the bone in either local or world space.
  63902. * @param space The space that the rotation should be in.
  63903. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63904. * @returns The quaternion rotation
  63905. */
  63906. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  63907. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63908. if (mesh === void 0) { mesh = null; }
  63909. var result = BABYLON.Quaternion.Identity();
  63910. this.getRotationQuaternionToRef(space, mesh, result);
  63911. return result;
  63912. };
  63913. /**
  63914. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  63915. * @param space The space that the rotation should be in.
  63916. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63917. * @param result The quaternion that the rotation should be copied to.
  63918. */
  63919. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  63920. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63921. if (mesh === void 0) { mesh = null; }
  63922. if (space == BABYLON.Space.LOCAL) {
  63923. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63924. }
  63925. else {
  63926. var mat = Bone._tmpMats[0];
  63927. var amat = this.getAbsoluteTransform();
  63928. if (mesh) {
  63929. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63930. }
  63931. else {
  63932. mat.copyFrom(amat);
  63933. }
  63934. mat.m[0] *= this._scalingDeterminant;
  63935. mat.m[1] *= this._scalingDeterminant;
  63936. mat.m[2] *= this._scalingDeterminant;
  63937. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63938. }
  63939. };
  63940. /**
  63941. * Get the rotation matrix of the bone in local or world space.
  63942. * @param space The space that the rotation should be in.
  63943. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63944. * @returns The rotation matrix
  63945. */
  63946. Bone.prototype.getRotationMatrix = function (space, mesh) {
  63947. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63948. var result = BABYLON.Matrix.Identity();
  63949. this.getRotationMatrixToRef(space, mesh, result);
  63950. return result;
  63951. };
  63952. /**
  63953. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  63954. * @param space The space that the rotation should be in.
  63955. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63956. * @param result The quaternion that the rotation should be copied to.
  63957. */
  63958. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  63959. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63960. if (space == BABYLON.Space.LOCAL) {
  63961. this.getLocalMatrix().getRotationMatrixToRef(result);
  63962. }
  63963. else {
  63964. var mat = Bone._tmpMats[0];
  63965. var amat = this.getAbsoluteTransform();
  63966. if (mesh) {
  63967. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63968. }
  63969. else {
  63970. mat.copyFrom(amat);
  63971. }
  63972. mat.m[0] *= this._scalingDeterminant;
  63973. mat.m[1] *= this._scalingDeterminant;
  63974. mat.m[2] *= this._scalingDeterminant;
  63975. mat.getRotationMatrixToRef(result);
  63976. }
  63977. };
  63978. /**
  63979. * Get the world position of a point that is in the local space of the bone.
  63980. * @param position The local position
  63981. * @param mesh The mesh that this bone is attached to.
  63982. * @returns The world position
  63983. */
  63984. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  63985. if (mesh === void 0) { mesh = null; }
  63986. var result = BABYLON.Vector3.Zero();
  63987. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  63988. return result;
  63989. };
  63990. /**
  63991. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  63992. * @param position The local position
  63993. * @param mesh The mesh that this bone is attached to.
  63994. * @param result The vector3 that the world position should be copied to.
  63995. */
  63996. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  63997. if (mesh === void 0) { mesh = null; }
  63998. var wm = null;
  63999. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64000. if (mesh) {
  64001. wm = mesh.getWorldMatrix();
  64002. }
  64003. this._skeleton.computeAbsoluteTransforms();
  64004. var tmat = Bone._tmpMats[0];
  64005. if (mesh && wm) {
  64006. tmat.copyFrom(this.getAbsoluteTransform());
  64007. tmat.multiplyToRef(wm, tmat);
  64008. }
  64009. else {
  64010. tmat = this.getAbsoluteTransform();
  64011. }
  64012. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64013. };
  64014. /**
  64015. * Get the local position of a point that is in world space.
  64016. * @param position The world position
  64017. * @param mesh The mesh that this bone is attached to.
  64018. * @returns The local position
  64019. */
  64020. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  64021. if (mesh === void 0) { mesh = null; }
  64022. var result = BABYLON.Vector3.Zero();
  64023. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  64024. return result;
  64025. };
  64026. /**
  64027. * Get the local position of a point that is in world space and copy it to the result param.
  64028. * @param position The world position
  64029. * @param mesh The mesh that this bone is attached to.
  64030. * @param result The vector3 that the local position should be copied to.
  64031. */
  64032. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  64033. if (mesh === void 0) { mesh = null; }
  64034. var wm = null;
  64035. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  64036. if (mesh) {
  64037. wm = mesh.getWorldMatrix();
  64038. }
  64039. this._skeleton.computeAbsoluteTransforms();
  64040. var tmat = Bone._tmpMats[0];
  64041. tmat.copyFrom(this.getAbsoluteTransform());
  64042. if (mesh && wm) {
  64043. tmat.multiplyToRef(wm, tmat);
  64044. }
  64045. tmat.invert();
  64046. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  64047. };
  64048. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64049. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  64050. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64051. return Bone;
  64052. }(BABYLON.Node));
  64053. BABYLON.Bone = Bone;
  64054. })(BABYLON || (BABYLON = {}));
  64055. //# sourceMappingURL=babylon.bone.js.map
  64056. var BABYLON;
  64057. (function (BABYLON) {
  64058. var BoneIKController = /** @class */ (function () {
  64059. function BoneIKController(mesh, bone, options) {
  64060. this.targetPosition = BABYLON.Vector3.Zero();
  64061. this.poleTargetPosition = BABYLON.Vector3.Zero();
  64062. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  64063. this.poleAngle = 0;
  64064. this.slerpAmount = 1;
  64065. this._bone1Quat = BABYLON.Quaternion.Identity();
  64066. this._bone1Mat = BABYLON.Matrix.Identity();
  64067. this._bone2Ang = Math.PI;
  64068. this._maxAngle = Math.PI;
  64069. this._rightHandedSystem = false;
  64070. this._bendAxis = BABYLON.Vector3.Right();
  64071. this._slerping = false;
  64072. this._adjustRoll = 0;
  64073. this._bone2 = bone;
  64074. this._bone1 = bone.getParent();
  64075. if (!this._bone1) {
  64076. return;
  64077. }
  64078. this.mesh = mesh;
  64079. var bonePos = bone.getPosition();
  64080. if (bone.getAbsoluteTransform().determinant() > 0) {
  64081. this._rightHandedSystem = true;
  64082. this._bendAxis.x = 0;
  64083. this._bendAxis.y = 0;
  64084. this._bendAxis.z = -1;
  64085. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  64086. this._adjustRoll = Math.PI * .5;
  64087. this._bendAxis.z = 1;
  64088. }
  64089. }
  64090. if (this._bone1.length) {
  64091. var boneScale1 = this._bone1.getScale();
  64092. var boneScale2 = this._bone2.getScale();
  64093. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  64094. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  64095. }
  64096. else if (this._bone1.children[0]) {
  64097. mesh.computeWorldMatrix(true);
  64098. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  64099. var pos2 = this._bone2.getAbsolutePosition(mesh);
  64100. var pos3 = this._bone1.getAbsolutePosition(mesh);
  64101. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  64102. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  64103. }
  64104. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  64105. this.maxAngle = Math.PI;
  64106. if (options) {
  64107. if (options.targetMesh) {
  64108. this.targetMesh = options.targetMesh;
  64109. this.targetMesh.computeWorldMatrix(true);
  64110. }
  64111. if (options.poleTargetMesh) {
  64112. this.poleTargetMesh = options.poleTargetMesh;
  64113. this.poleTargetMesh.computeWorldMatrix(true);
  64114. }
  64115. else if (options.poleTargetBone) {
  64116. this.poleTargetBone = options.poleTargetBone;
  64117. }
  64118. else if (this._bone1.getParent()) {
  64119. this.poleTargetBone = this._bone1.getParent();
  64120. }
  64121. if (options.poleTargetLocalOffset) {
  64122. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  64123. }
  64124. if (options.poleAngle) {
  64125. this.poleAngle = options.poleAngle;
  64126. }
  64127. if (options.bendAxis) {
  64128. this._bendAxis.copyFrom(options.bendAxis);
  64129. }
  64130. if (options.maxAngle) {
  64131. this.maxAngle = options.maxAngle;
  64132. }
  64133. if (options.slerpAmount) {
  64134. this.slerpAmount = options.slerpAmount;
  64135. }
  64136. }
  64137. }
  64138. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  64139. get: function () {
  64140. return this._maxAngle;
  64141. },
  64142. set: function (value) {
  64143. this._setMaxAngle(value);
  64144. },
  64145. enumerable: true,
  64146. configurable: true
  64147. });
  64148. BoneIKController.prototype._setMaxAngle = function (ang) {
  64149. if (ang < 0) {
  64150. ang = 0;
  64151. }
  64152. if (ang > Math.PI || ang == undefined) {
  64153. ang = Math.PI;
  64154. }
  64155. this._maxAngle = ang;
  64156. var a = this._bone1Length;
  64157. var b = this._bone2Length;
  64158. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  64159. };
  64160. BoneIKController.prototype.update = function () {
  64161. var bone1 = this._bone1;
  64162. if (!bone1) {
  64163. return;
  64164. }
  64165. var target = this.targetPosition;
  64166. var poleTarget = this.poleTargetPosition;
  64167. var mat1 = BoneIKController._tmpMats[0];
  64168. var mat2 = BoneIKController._tmpMats[1];
  64169. if (this.targetMesh) {
  64170. target.copyFrom(this.targetMesh.getAbsolutePosition());
  64171. }
  64172. if (this.poleTargetBone) {
  64173. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  64174. }
  64175. else if (this.poleTargetMesh) {
  64176. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  64177. }
  64178. var bonePos = BoneIKController._tmpVecs[0];
  64179. var zaxis = BoneIKController._tmpVecs[1];
  64180. var xaxis = BoneIKController._tmpVecs[2];
  64181. var yaxis = BoneIKController._tmpVecs[3];
  64182. var upAxis = BoneIKController._tmpVecs[4];
  64183. var _tmpQuat = BoneIKController._tmpQuat;
  64184. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  64185. poleTarget.subtractToRef(bonePos, upAxis);
  64186. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  64187. upAxis.y = 1;
  64188. }
  64189. else {
  64190. upAxis.normalize();
  64191. }
  64192. target.subtractToRef(bonePos, yaxis);
  64193. yaxis.normalize();
  64194. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  64195. zaxis.normalize();
  64196. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  64197. xaxis.normalize();
  64198. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  64199. var a = this._bone1Length;
  64200. var b = this._bone2Length;
  64201. var c = BABYLON.Vector3.Distance(bonePos, target);
  64202. if (this._maxReach > 0) {
  64203. c = Math.min(this._maxReach, c);
  64204. }
  64205. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  64206. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  64207. if (acosa > 1) {
  64208. acosa = 1;
  64209. }
  64210. if (acosb > 1) {
  64211. acosb = 1;
  64212. }
  64213. if (acosa < -1) {
  64214. acosa = -1;
  64215. }
  64216. if (acosb < -1) {
  64217. acosb = -1;
  64218. }
  64219. var angA = Math.acos(acosa);
  64220. var angB = Math.acos(acosb);
  64221. var angC = -angA - angB;
  64222. if (this._rightHandedSystem) {
  64223. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  64224. mat2.multiplyToRef(mat1, mat1);
  64225. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  64226. mat2.multiplyToRef(mat1, mat1);
  64227. }
  64228. else {
  64229. var _tmpVec = BoneIKController._tmpVecs[5];
  64230. _tmpVec.copyFrom(this._bendAxis);
  64231. _tmpVec.x *= -1;
  64232. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  64233. mat2.multiplyToRef(mat1, mat1);
  64234. }
  64235. if (this.poleAngle) {
  64236. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  64237. mat1.multiplyToRef(mat2, mat1);
  64238. }
  64239. if (this._bone1) {
  64240. if (this.slerpAmount < 1) {
  64241. if (!this._slerping) {
  64242. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  64243. }
  64244. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  64245. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  64246. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  64247. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  64248. this._slerping = true;
  64249. }
  64250. else {
  64251. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  64252. this._bone1Mat.copyFrom(mat1);
  64253. this._slerping = false;
  64254. }
  64255. }
  64256. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  64257. this._bone2Ang = angC;
  64258. };
  64259. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64260. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  64261. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64262. return BoneIKController;
  64263. }());
  64264. BABYLON.BoneIKController = BoneIKController;
  64265. })(BABYLON || (BABYLON = {}));
  64266. //# sourceMappingURL=babylon.boneIKController.js.map
  64267. var BABYLON;
  64268. (function (BABYLON) {
  64269. var BoneLookController = /** @class */ (function () {
  64270. /**
  64271. * Create a BoneLookController
  64272. * @param mesh the mesh that the bone belongs to
  64273. * @param bone the bone that will be looking to the target
  64274. * @param target the target Vector3 to look at
  64275. * @param settings optional settings:
  64276. * - maxYaw: the maximum angle the bone will yaw to
  64277. * - minYaw: the minimum angle the bone will yaw to
  64278. * - maxPitch: the maximum angle the bone will pitch to
  64279. * - minPitch: the minimum angle the bone will yaw to
  64280. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  64281. * - upAxis: the up axis of the coordinate system
  64282. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64283. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  64284. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  64285. * - adjustYaw: used to make an adjustment to the yaw of the bone
  64286. * - adjustPitch: used to make an adjustment to the pitch of the bone
  64287. * - adjustRoll: used to make an adjustment to the roll of the bone
  64288. **/
  64289. function BoneLookController(mesh, bone, target, options) {
  64290. /**
  64291. * The up axis of the coordinate system that is used when the bone is rotated.
  64292. */
  64293. this.upAxis = BABYLON.Vector3.Up();
  64294. /**
  64295. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  64296. */
  64297. this.upAxisSpace = BABYLON.Space.LOCAL;
  64298. /**
  64299. * Used to make an adjustment to the yaw of the bone.
  64300. */
  64301. this.adjustYaw = 0;
  64302. /**
  64303. * Used to make an adjustment to the pitch of the bone.
  64304. */
  64305. this.adjustPitch = 0;
  64306. /**
  64307. * Used to make an adjustment to the roll of the bone.
  64308. */
  64309. this.adjustRoll = 0;
  64310. /**
  64311. * 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).
  64312. */
  64313. this.slerpAmount = 1;
  64314. this._boneQuat = BABYLON.Quaternion.Identity();
  64315. this._slerping = false;
  64316. this._firstFrameSkipped = false;
  64317. this._fowardAxis = BABYLON.Vector3.Forward();
  64318. this.mesh = mesh;
  64319. this.bone = bone;
  64320. this.target = target;
  64321. if (options) {
  64322. if (options.adjustYaw) {
  64323. this.adjustYaw = options.adjustYaw;
  64324. }
  64325. if (options.adjustPitch) {
  64326. this.adjustPitch = options.adjustPitch;
  64327. }
  64328. if (options.adjustRoll) {
  64329. this.adjustRoll = options.adjustRoll;
  64330. }
  64331. if (options.maxYaw != null) {
  64332. this.maxYaw = options.maxYaw;
  64333. }
  64334. else {
  64335. this.maxYaw = Math.PI;
  64336. }
  64337. if (options.minYaw != null) {
  64338. this.minYaw = options.minYaw;
  64339. }
  64340. else {
  64341. this.minYaw = -Math.PI;
  64342. }
  64343. if (options.maxPitch != null) {
  64344. this.maxPitch = options.maxPitch;
  64345. }
  64346. else {
  64347. this.maxPitch = Math.PI;
  64348. }
  64349. if (options.minPitch != null) {
  64350. this.minPitch = options.minPitch;
  64351. }
  64352. else {
  64353. this.minPitch = -Math.PI;
  64354. }
  64355. if (options.slerpAmount != null) {
  64356. this.slerpAmount = options.slerpAmount;
  64357. }
  64358. if (options.upAxis != null) {
  64359. this.upAxis = options.upAxis;
  64360. }
  64361. if (options.upAxisSpace != null) {
  64362. this.upAxisSpace = options.upAxisSpace;
  64363. }
  64364. if (options.yawAxis != null || options.pitchAxis != null) {
  64365. var newYawAxis = BABYLON.Axis.Y;
  64366. var newPitchAxis = BABYLON.Axis.X;
  64367. if (options.yawAxis != null) {
  64368. newYawAxis = options.yawAxis.clone();
  64369. newYawAxis.normalize();
  64370. }
  64371. if (options.pitchAxis != null) {
  64372. newPitchAxis = options.pitchAxis.clone();
  64373. newPitchAxis.normalize();
  64374. }
  64375. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  64376. this._transformYawPitch = BABYLON.Matrix.Identity();
  64377. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  64378. this._transformYawPitchInv = this._transformYawPitch.clone();
  64379. this._transformYawPitch.invert();
  64380. }
  64381. }
  64382. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  64383. this.upAxisSpace = BABYLON.Space.LOCAL;
  64384. }
  64385. }
  64386. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  64387. /**
  64388. * Get/set the minimum yaw angle that the bone can look to.
  64389. */
  64390. get: function () {
  64391. return this._minYaw;
  64392. },
  64393. set: function (value) {
  64394. this._minYaw = value;
  64395. this._minYawSin = Math.sin(value);
  64396. this._minYawCos = Math.cos(value);
  64397. if (this._maxYaw != null) {
  64398. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64399. this._yawRange = this._maxYaw - this._minYaw;
  64400. }
  64401. },
  64402. enumerable: true,
  64403. configurable: true
  64404. });
  64405. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  64406. /**
  64407. * Get/set the maximum yaw angle that the bone can look to.
  64408. */
  64409. get: function () {
  64410. return this._maxYaw;
  64411. },
  64412. set: function (value) {
  64413. this._maxYaw = value;
  64414. this._maxYawSin = Math.sin(value);
  64415. this._maxYawCos = Math.cos(value);
  64416. if (this._minYaw != null) {
  64417. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  64418. this._yawRange = this._maxYaw - this._minYaw;
  64419. }
  64420. },
  64421. enumerable: true,
  64422. configurable: true
  64423. });
  64424. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  64425. /**
  64426. * Get/set the minimum pitch angle that the bone can look to.
  64427. */
  64428. get: function () {
  64429. return this._minPitch;
  64430. },
  64431. set: function (value) {
  64432. this._minPitch = value;
  64433. this._minPitchTan = Math.tan(value);
  64434. },
  64435. enumerable: true,
  64436. configurable: true
  64437. });
  64438. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  64439. /**
  64440. * Get/set the maximum pitch angle that the bone can look to.
  64441. */
  64442. get: function () {
  64443. return this._maxPitch;
  64444. },
  64445. set: function (value) {
  64446. this._maxPitch = value;
  64447. this._maxPitchTan = Math.tan(value);
  64448. },
  64449. enumerable: true,
  64450. configurable: true
  64451. });
  64452. /**
  64453. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  64454. */
  64455. BoneLookController.prototype.update = function () {
  64456. //skip the first frame when slerping so that the mesh rotation is correct
  64457. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  64458. this._firstFrameSkipped = true;
  64459. return;
  64460. }
  64461. var bone = this.bone;
  64462. var bonePos = BoneLookController._tmpVecs[0];
  64463. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  64464. var target = this.target;
  64465. var _tmpMat1 = BoneLookController._tmpMats[0];
  64466. var _tmpMat2 = BoneLookController._tmpMats[1];
  64467. var mesh = this.mesh;
  64468. var parentBone = bone.getParent();
  64469. var upAxis = BoneLookController._tmpVecs[1];
  64470. upAxis.copyFrom(this.upAxis);
  64471. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  64472. if (this._transformYawPitch) {
  64473. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  64474. }
  64475. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  64476. }
  64477. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  64478. mesh.getDirectionToRef(upAxis, upAxis);
  64479. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  64480. upAxis.normalize();
  64481. }
  64482. }
  64483. var checkYaw = false;
  64484. var checkPitch = false;
  64485. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  64486. checkYaw = true;
  64487. }
  64488. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  64489. checkPitch = true;
  64490. }
  64491. if (checkYaw || checkPitch) {
  64492. var spaceMat = BoneLookController._tmpMats[2];
  64493. var spaceMatInv = BoneLookController._tmpMats[3];
  64494. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  64495. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  64496. }
  64497. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  64498. spaceMat.copyFrom(mesh.getWorldMatrix());
  64499. }
  64500. else {
  64501. var forwardAxis = BoneLookController._tmpVecs[2];
  64502. forwardAxis.copyFrom(this._fowardAxis);
  64503. if (this._transformYawPitch) {
  64504. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  64505. }
  64506. if (parentBone) {
  64507. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  64508. }
  64509. else {
  64510. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  64511. }
  64512. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  64513. rightAxis.normalize();
  64514. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  64515. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  64516. }
  64517. spaceMat.invertToRef(spaceMatInv);
  64518. var xzlen = null;
  64519. if (checkPitch) {
  64520. var localTarget = BoneLookController._tmpVecs[3];
  64521. target.subtractToRef(bonePos, localTarget);
  64522. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64523. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64524. var pitch = Math.atan2(localTarget.y, xzlen);
  64525. var newPitch = pitch;
  64526. if (pitch > this._maxPitch) {
  64527. localTarget.y = this._maxPitchTan * xzlen;
  64528. newPitch = this._maxPitch;
  64529. }
  64530. else if (pitch < this._minPitch) {
  64531. localTarget.y = this._minPitchTan * xzlen;
  64532. newPitch = this._minPitch;
  64533. }
  64534. if (pitch != newPitch) {
  64535. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64536. localTarget.addInPlace(bonePos);
  64537. target = localTarget;
  64538. }
  64539. }
  64540. if (checkYaw) {
  64541. var localTarget = BoneLookController._tmpVecs[4];
  64542. target.subtractToRef(bonePos, localTarget);
  64543. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  64544. var yaw = Math.atan2(localTarget.x, localTarget.z);
  64545. var newYaw = yaw;
  64546. if (yaw > this._maxYaw || yaw < this._minYaw) {
  64547. if (xzlen == null) {
  64548. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64549. }
  64550. if (this._yawRange > Math.PI) {
  64551. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  64552. localTarget.z = this._maxYawCos * xzlen;
  64553. localTarget.x = this._maxYawSin * xzlen;
  64554. newYaw = this._maxYaw;
  64555. }
  64556. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  64557. localTarget.z = this._minYawCos * xzlen;
  64558. localTarget.x = this._minYawSin * xzlen;
  64559. newYaw = this._minYaw;
  64560. }
  64561. }
  64562. else {
  64563. if (yaw > this._maxYaw) {
  64564. localTarget.z = this._maxYawCos * xzlen;
  64565. localTarget.x = this._maxYawSin * xzlen;
  64566. newYaw = this._maxYaw;
  64567. }
  64568. else if (yaw < this._minYaw) {
  64569. localTarget.z = this._minYawCos * xzlen;
  64570. localTarget.x = this._minYawSin * xzlen;
  64571. newYaw = this._minYaw;
  64572. }
  64573. }
  64574. }
  64575. if (this._slerping && this._yawRange > Math.PI) {
  64576. //are we going to be crossing into the min/max region?
  64577. var boneFwd = BoneLookController._tmpVecs[8];
  64578. boneFwd.copyFrom(BABYLON.Axis.Z);
  64579. if (this._transformYawPitch) {
  64580. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  64581. }
  64582. var boneRotMat = BoneLookController._tmpMats[4];
  64583. this._boneQuat.toRotationMatrix(boneRotMat);
  64584. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  64585. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  64586. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  64587. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  64588. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  64589. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  64590. if (angBtwTar > angBtwMidYaw) {
  64591. if (xzlen == null) {
  64592. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  64593. }
  64594. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  64595. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  64596. if (angBtwMin < angBtwMax) {
  64597. newYaw = boneYaw + Math.PI * .75;
  64598. localTarget.z = Math.cos(newYaw) * xzlen;
  64599. localTarget.x = Math.sin(newYaw) * xzlen;
  64600. }
  64601. else {
  64602. newYaw = boneYaw - Math.PI * .75;
  64603. localTarget.z = Math.cos(newYaw) * xzlen;
  64604. localTarget.x = Math.sin(newYaw) * xzlen;
  64605. }
  64606. }
  64607. }
  64608. if (yaw != newYaw) {
  64609. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  64610. localTarget.addInPlace(bonePos);
  64611. target = localTarget;
  64612. }
  64613. }
  64614. }
  64615. var zaxis = BoneLookController._tmpVecs[5];
  64616. var xaxis = BoneLookController._tmpVecs[6];
  64617. var yaxis = BoneLookController._tmpVecs[7];
  64618. var _tmpQuat = BoneLookController._tmpQuat;
  64619. target.subtractToRef(bonePos, zaxis);
  64620. zaxis.normalize();
  64621. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  64622. xaxis.normalize();
  64623. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  64624. yaxis.normalize();
  64625. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  64626. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  64627. return;
  64628. }
  64629. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  64630. return;
  64631. }
  64632. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  64633. return;
  64634. }
  64635. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  64636. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  64637. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  64638. }
  64639. if (this.slerpAmount < 1) {
  64640. if (!this._slerping) {
  64641. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  64642. }
  64643. if (this._transformYawPitch) {
  64644. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64645. }
  64646. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  64647. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  64648. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  64649. this._slerping = true;
  64650. }
  64651. else {
  64652. if (this._transformYawPitch) {
  64653. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  64654. }
  64655. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  64656. this._slerping = false;
  64657. }
  64658. };
  64659. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  64660. var angDiff = ang2 - ang1;
  64661. angDiff %= Math.PI * 2;
  64662. if (angDiff > Math.PI) {
  64663. angDiff -= Math.PI * 2;
  64664. }
  64665. else if (angDiff < -Math.PI) {
  64666. angDiff += Math.PI * 2;
  64667. }
  64668. return angDiff;
  64669. };
  64670. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  64671. ang1 %= (2 * Math.PI);
  64672. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64673. ang2 %= (2 * Math.PI);
  64674. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64675. var ab = 0;
  64676. if (ang1 < ang2) {
  64677. ab = ang2 - ang1;
  64678. }
  64679. else {
  64680. ab = ang1 - ang2;
  64681. }
  64682. if (ab > Math.PI) {
  64683. ab = Math.PI * 2 - ab;
  64684. }
  64685. return ab;
  64686. };
  64687. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  64688. ang %= (2 * Math.PI);
  64689. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  64690. ang1 %= (2 * Math.PI);
  64691. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  64692. ang2 %= (2 * Math.PI);
  64693. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  64694. if (ang1 < ang2) {
  64695. if (ang > ang1 && ang < ang2) {
  64696. return true;
  64697. }
  64698. }
  64699. else {
  64700. if (ang > ang2 && ang < ang1) {
  64701. return true;
  64702. }
  64703. }
  64704. return false;
  64705. };
  64706. 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()];
  64707. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64708. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64709. return BoneLookController;
  64710. }());
  64711. BABYLON.BoneLookController = BoneLookController;
  64712. })(BABYLON || (BABYLON = {}));
  64713. //# sourceMappingURL=babylon.boneLookController.js.map
  64714. var BABYLON;
  64715. (function (BABYLON) {
  64716. var Skeleton = /** @class */ (function () {
  64717. function Skeleton(name, id, scene) {
  64718. this.name = name;
  64719. this.id = id;
  64720. this.bones = new Array();
  64721. this.needInitialSkinMatrix = false;
  64722. this._isDirty = true;
  64723. this._meshesWithPoseMatrix = new Array();
  64724. this._identity = BABYLON.Matrix.Identity();
  64725. this._ranges = {};
  64726. this._lastAbsoluteTransformsUpdateId = -1;
  64727. // Events
  64728. /**
  64729. * An event triggered before computing the skeleton's matrices
  64730. * @type {BABYLON.Observable}
  64731. */
  64732. this.onBeforeComputeObservable = new BABYLON.Observable();
  64733. this.bones = [];
  64734. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64735. scene.skeletons.push(this);
  64736. //make sure it will recalculate the matrix next time prepare is called.
  64737. this._isDirty = true;
  64738. }
  64739. // Members
  64740. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64741. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64742. return mesh._bonesTransformMatrices;
  64743. }
  64744. if (!this._transformMatrices) {
  64745. this.prepare();
  64746. }
  64747. return this._transformMatrices;
  64748. };
  64749. Skeleton.prototype.getScene = function () {
  64750. return this._scene;
  64751. };
  64752. // Methods
  64753. /**
  64754. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64755. */
  64756. Skeleton.prototype.toString = function (fullDetails) {
  64757. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64758. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64759. if (fullDetails) {
  64760. ret += ", Ranges: {";
  64761. var first = true;
  64762. for (var name_1 in this._ranges) {
  64763. if (first) {
  64764. ret += ", ";
  64765. first = false;
  64766. }
  64767. ret += name_1;
  64768. }
  64769. ret += "}";
  64770. }
  64771. return ret;
  64772. };
  64773. /**
  64774. * Get bone's index searching by name
  64775. * @param {string} name is bone's name to search for
  64776. * @return {number} Indice of the bone. Returns -1 if not found
  64777. */
  64778. Skeleton.prototype.getBoneIndexByName = function (name) {
  64779. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64780. if (this.bones[boneIndex].name === name) {
  64781. return boneIndex;
  64782. }
  64783. }
  64784. return -1;
  64785. };
  64786. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64787. // check name not already in use
  64788. if (!this._ranges[name]) {
  64789. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64790. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64791. if (this.bones[i].animations[0]) {
  64792. this.bones[i].animations[0].createRange(name, from, to);
  64793. }
  64794. }
  64795. }
  64796. };
  64797. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64798. if (deleteFrames === void 0) { deleteFrames = true; }
  64799. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64800. if (this.bones[i].animations[0]) {
  64801. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64802. }
  64803. }
  64804. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64805. };
  64806. Skeleton.prototype.getAnimationRange = function (name) {
  64807. return this._ranges[name];
  64808. };
  64809. /**
  64810. * Returns as an Array, all AnimationRanges defined on this skeleton
  64811. */
  64812. Skeleton.prototype.getAnimationRanges = function () {
  64813. var animationRanges = [];
  64814. var name;
  64815. var i = 0;
  64816. for (name in this._ranges) {
  64817. animationRanges[i] = this._ranges[name];
  64818. i++;
  64819. }
  64820. return animationRanges;
  64821. };
  64822. /**
  64823. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64824. */
  64825. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64826. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64827. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64828. return false;
  64829. }
  64830. var ret = true;
  64831. var frameOffset = this._getHighestAnimationFrame() + 1;
  64832. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64833. var boneDict = {};
  64834. var sourceBones = source.bones;
  64835. var nBones;
  64836. var i;
  64837. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  64838. boneDict[sourceBones[i].name] = sourceBones[i];
  64839. }
  64840. if (this.bones.length !== sourceBones.length) {
  64841. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  64842. ret = false;
  64843. }
  64844. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  64845. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  64846. var boneName = this.bones[i].name;
  64847. var sourceBone = boneDict[boneName];
  64848. if (sourceBone) {
  64849. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  64850. }
  64851. else {
  64852. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  64853. ret = false;
  64854. }
  64855. }
  64856. // do not call createAnimationRange(), since it also is done to bones, which was already done
  64857. var range = source.getAnimationRange(name);
  64858. if (range) {
  64859. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  64860. }
  64861. return ret;
  64862. };
  64863. Skeleton.prototype.returnToRest = function () {
  64864. for (var index = 0; index < this.bones.length; index++) {
  64865. this.bones[index].returnToRest();
  64866. }
  64867. };
  64868. Skeleton.prototype._getHighestAnimationFrame = function () {
  64869. var ret = 0;
  64870. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64871. if (this.bones[i].animations[0]) {
  64872. var highest = this.bones[i].animations[0].getHighestFrame();
  64873. if (ret < highest) {
  64874. ret = highest;
  64875. }
  64876. }
  64877. }
  64878. return ret;
  64879. };
  64880. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  64881. var range = this.getAnimationRange(name);
  64882. if (!range) {
  64883. return null;
  64884. }
  64885. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  64886. };
  64887. Skeleton.prototype._markAsDirty = function () {
  64888. this._isDirty = true;
  64889. };
  64890. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  64891. this._meshesWithPoseMatrix.push(mesh);
  64892. };
  64893. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  64894. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  64895. if (index > -1) {
  64896. this._meshesWithPoseMatrix.splice(index, 1);
  64897. }
  64898. };
  64899. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  64900. this.onBeforeComputeObservable.notifyObservers(this);
  64901. for (var index = 0; index < this.bones.length; index++) {
  64902. var bone = this.bones[index];
  64903. var parentBone = bone.getParent();
  64904. if (parentBone) {
  64905. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  64906. }
  64907. else {
  64908. if (initialSkinMatrix) {
  64909. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  64910. }
  64911. else {
  64912. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  64913. }
  64914. }
  64915. if (bone._index !== -1) {
  64916. var mappedIndex = bone._index === null ? index : bone._index;
  64917. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  64918. }
  64919. }
  64920. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  64921. };
  64922. Skeleton.prototype.prepare = function () {
  64923. if (!this._isDirty) {
  64924. return;
  64925. }
  64926. if (this.needInitialSkinMatrix) {
  64927. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  64928. var mesh = this._meshesWithPoseMatrix[index];
  64929. var poseMatrix = mesh.getPoseMatrix();
  64930. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  64931. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64932. }
  64933. if (this._synchronizedWithMesh !== mesh) {
  64934. this._synchronizedWithMesh = mesh;
  64935. // Prepare bones
  64936. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  64937. var bone = this.bones[boneIndex];
  64938. if (!bone.getParent()) {
  64939. var matrix = bone.getBaseMatrix();
  64940. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  64941. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  64942. }
  64943. }
  64944. }
  64945. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  64946. }
  64947. }
  64948. else {
  64949. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  64950. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64951. }
  64952. this._computeTransformMatrices(this._transformMatrices, null);
  64953. }
  64954. this._isDirty = false;
  64955. this._scene._activeBones.addCount(this.bones.length, false);
  64956. };
  64957. Skeleton.prototype.getAnimatables = function () {
  64958. if (!this._animatables || this._animatables.length !== this.bones.length) {
  64959. this._animatables = [];
  64960. for (var index = 0; index < this.bones.length; index++) {
  64961. this._animatables.push(this.bones[index]);
  64962. }
  64963. }
  64964. return this._animatables;
  64965. };
  64966. Skeleton.prototype.clone = function (name, id) {
  64967. var result = new Skeleton(name, id || name, this._scene);
  64968. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64969. for (var index = 0; index < this.bones.length; index++) {
  64970. var source = this.bones[index];
  64971. var parentBone = null;
  64972. var parent_1 = source.getParent();
  64973. if (parent_1) {
  64974. var parentIndex = this.bones.indexOf(parent_1);
  64975. parentBone = result.bones[parentIndex];
  64976. }
  64977. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  64978. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  64979. }
  64980. if (this._ranges) {
  64981. result._ranges = {};
  64982. for (var rangeName in this._ranges) {
  64983. var range = this._ranges[rangeName];
  64984. if (range) {
  64985. result._ranges[rangeName] = range.clone();
  64986. }
  64987. }
  64988. }
  64989. this._isDirty = true;
  64990. return result;
  64991. };
  64992. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  64993. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  64994. this.bones.forEach(function (bone) {
  64995. bone.animations.forEach(function (animation) {
  64996. animation.enableBlending = true;
  64997. animation.blendingSpeed = blendingSpeed;
  64998. });
  64999. });
  65000. };
  65001. Skeleton.prototype.dispose = function () {
  65002. this._meshesWithPoseMatrix = [];
  65003. // Animations
  65004. this.getScene().stopAnimation(this);
  65005. // Remove from scene
  65006. this.getScene().removeSkeleton(this);
  65007. };
  65008. Skeleton.prototype.serialize = function () {
  65009. var serializationObject = {};
  65010. serializationObject.name = this.name;
  65011. serializationObject.id = this.id;
  65012. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  65013. serializationObject.bones = [];
  65014. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  65015. for (var index = 0; index < this.bones.length; index++) {
  65016. var bone = this.bones[index];
  65017. var parent_2 = bone.getParent();
  65018. var serializedBone = {
  65019. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  65020. name: bone.name,
  65021. matrix: bone.getBaseMatrix().toArray(),
  65022. rest: bone.getRestPose().toArray()
  65023. };
  65024. serializationObject.bones.push(serializedBone);
  65025. if (bone.length) {
  65026. serializedBone.length = bone.length;
  65027. }
  65028. if (bone.animations && bone.animations.length > 0) {
  65029. serializedBone.animation = bone.animations[0].serialize();
  65030. }
  65031. serializationObject.ranges = [];
  65032. for (var name in this._ranges) {
  65033. var source = this._ranges[name];
  65034. if (!source) {
  65035. continue;
  65036. }
  65037. var range = {};
  65038. range.name = name;
  65039. range.from = source.from;
  65040. range.to = source.to;
  65041. serializationObject.ranges.push(range);
  65042. }
  65043. }
  65044. return serializationObject;
  65045. };
  65046. Skeleton.Parse = function (parsedSkeleton, scene) {
  65047. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  65048. if (parsedSkeleton.dimensionsAtRest) {
  65049. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  65050. }
  65051. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  65052. var index;
  65053. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  65054. var parsedBone = parsedSkeleton.bones[index];
  65055. var parentBone = null;
  65056. if (parsedBone.parentBoneIndex > -1) {
  65057. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  65058. }
  65059. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  65060. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  65061. if (parsedBone.length) {
  65062. bone.length = parsedBone.length;
  65063. }
  65064. if (parsedBone.animation) {
  65065. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  65066. }
  65067. }
  65068. // placed after bones, so createAnimationRange can cascade down
  65069. if (parsedSkeleton.ranges) {
  65070. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  65071. var data = parsedSkeleton.ranges[index];
  65072. skeleton.createAnimationRange(data.name, data.from, data.to);
  65073. }
  65074. }
  65075. return skeleton;
  65076. };
  65077. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  65078. if (forceUpdate === void 0) { forceUpdate = false; }
  65079. var renderId = this._scene.getRenderId();
  65080. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  65081. this.bones[0].computeAbsoluteTransforms();
  65082. this._lastAbsoluteTransformsUpdateId = renderId;
  65083. }
  65084. };
  65085. Skeleton.prototype.getPoseMatrix = function () {
  65086. var poseMatrix = null;
  65087. if (this._meshesWithPoseMatrix.length > 0) {
  65088. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  65089. }
  65090. return poseMatrix;
  65091. };
  65092. Skeleton.prototype.sortBones = function () {
  65093. var bones = new Array();
  65094. var visited = new Array(this.bones.length);
  65095. for (var index = 0; index < this.bones.length; index++) {
  65096. this._sortBones(index, bones, visited);
  65097. }
  65098. this.bones = bones;
  65099. };
  65100. Skeleton.prototype._sortBones = function (index, bones, visited) {
  65101. if (visited[index]) {
  65102. return;
  65103. }
  65104. visited[index] = true;
  65105. var bone = this.bones[index];
  65106. if (bone._index === undefined) {
  65107. bone._index = index;
  65108. }
  65109. var parentBone = bone.getParent();
  65110. if (parentBone) {
  65111. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  65112. }
  65113. bones.push(bone);
  65114. };
  65115. return Skeleton;
  65116. }());
  65117. BABYLON.Skeleton = Skeleton;
  65118. })(BABYLON || (BABYLON = {}));
  65119. //# sourceMappingURL=babylon.skeleton.js.map
  65120. var BABYLON;
  65121. (function (BABYLON) {
  65122. var SphericalPolynomial = /** @class */ (function () {
  65123. function SphericalPolynomial() {
  65124. this.x = BABYLON.Vector3.Zero();
  65125. this.y = BABYLON.Vector3.Zero();
  65126. this.z = BABYLON.Vector3.Zero();
  65127. this.xx = BABYLON.Vector3.Zero();
  65128. this.yy = BABYLON.Vector3.Zero();
  65129. this.zz = BABYLON.Vector3.Zero();
  65130. this.xy = BABYLON.Vector3.Zero();
  65131. this.yz = BABYLON.Vector3.Zero();
  65132. this.zx = BABYLON.Vector3.Zero();
  65133. }
  65134. SphericalPolynomial.prototype.addAmbient = function (color) {
  65135. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65136. this.xx = this.xx.add(colorVector);
  65137. this.yy = this.yy.add(colorVector);
  65138. this.zz = this.zz.add(colorVector);
  65139. };
  65140. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  65141. var result = new SphericalPolynomial();
  65142. result.x = harmonics.L11.scale(1.02333);
  65143. result.y = harmonics.L1_1.scale(1.02333);
  65144. result.z = harmonics.L10.scale(1.02333);
  65145. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  65146. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  65147. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  65148. result.yz = harmonics.L2_1.scale(0.858086);
  65149. result.zx = harmonics.L21.scale(0.858086);
  65150. result.xy = harmonics.L2_2.scale(0.858086);
  65151. result.scale(1.0 / Math.PI);
  65152. return result;
  65153. };
  65154. SphericalPolynomial.prototype.scale = function (scale) {
  65155. this.x = this.x.scale(scale);
  65156. this.y = this.y.scale(scale);
  65157. this.z = this.z.scale(scale);
  65158. this.xx = this.xx.scale(scale);
  65159. this.yy = this.yy.scale(scale);
  65160. this.zz = this.zz.scale(scale);
  65161. this.yz = this.yz.scale(scale);
  65162. this.zx = this.zx.scale(scale);
  65163. this.xy = this.xy.scale(scale);
  65164. };
  65165. return SphericalPolynomial;
  65166. }());
  65167. BABYLON.SphericalPolynomial = SphericalPolynomial;
  65168. var SphericalHarmonics = /** @class */ (function () {
  65169. function SphericalHarmonics() {
  65170. this.L00 = BABYLON.Vector3.Zero();
  65171. this.L1_1 = BABYLON.Vector3.Zero();
  65172. this.L10 = BABYLON.Vector3.Zero();
  65173. this.L11 = BABYLON.Vector3.Zero();
  65174. this.L2_2 = BABYLON.Vector3.Zero();
  65175. this.L2_1 = BABYLON.Vector3.Zero();
  65176. this.L20 = BABYLON.Vector3.Zero();
  65177. this.L21 = BABYLON.Vector3.Zero();
  65178. this.L22 = BABYLON.Vector3.Zero();
  65179. }
  65180. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  65181. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  65182. var c = colorVector.scale(deltaSolidAngle);
  65183. this.L00 = this.L00.add(c.scale(0.282095));
  65184. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  65185. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  65186. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  65187. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  65188. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  65189. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  65190. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  65191. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  65192. };
  65193. SphericalHarmonics.prototype.scale = function (scale) {
  65194. this.L00 = this.L00.scale(scale);
  65195. this.L1_1 = this.L1_1.scale(scale);
  65196. this.L10 = this.L10.scale(scale);
  65197. this.L11 = this.L11.scale(scale);
  65198. this.L2_2 = this.L2_2.scale(scale);
  65199. this.L2_1 = this.L2_1.scale(scale);
  65200. this.L20 = this.L20.scale(scale);
  65201. this.L21 = this.L21.scale(scale);
  65202. this.L22 = this.L22.scale(scale);
  65203. };
  65204. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  65205. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  65206. //
  65207. // E_lm = A_l * L_lm
  65208. //
  65209. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  65210. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  65211. // the scaling factors are given in equation 9.
  65212. // Constant (Band 0)
  65213. this.L00 = this.L00.scale(3.141593);
  65214. // Linear (Band 1)
  65215. this.L1_1 = this.L1_1.scale(2.094395);
  65216. this.L10 = this.L10.scale(2.094395);
  65217. this.L11 = this.L11.scale(2.094395);
  65218. // Quadratic (Band 2)
  65219. this.L2_2 = this.L2_2.scale(0.785398);
  65220. this.L2_1 = this.L2_1.scale(0.785398);
  65221. this.L20 = this.L20.scale(0.785398);
  65222. this.L21 = this.L21.scale(0.785398);
  65223. this.L22 = this.L22.scale(0.785398);
  65224. };
  65225. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  65226. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  65227. // L = (1/pi) * E * rho
  65228. //
  65229. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  65230. this.scale(1.0 / Math.PI);
  65231. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  65232. // (The pixel shader must apply albedo after texture fetches, etc).
  65233. };
  65234. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  65235. var result = new SphericalHarmonics();
  65236. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  65237. result.L1_1 = polynomial.y.scale(0.977204);
  65238. result.L10 = polynomial.z.scale(0.977204);
  65239. result.L11 = polynomial.x.scale(0.977204);
  65240. result.L2_2 = polynomial.xy.scale(1.16538);
  65241. result.L2_1 = polynomial.yz.scale(1.16538);
  65242. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  65243. result.L21 = polynomial.zx.scale(1.16538);
  65244. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  65245. result.scale(Math.PI);
  65246. return result;
  65247. };
  65248. return SphericalHarmonics;
  65249. }());
  65250. BABYLON.SphericalHarmonics = SphericalHarmonics;
  65251. })(BABYLON || (BABYLON = {}));
  65252. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  65253. var BABYLON;
  65254. (function (BABYLON) {
  65255. var FileFaceOrientation = /** @class */ (function () {
  65256. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  65257. this.name = name;
  65258. this.worldAxisForNormal = worldAxisForNormal;
  65259. this.worldAxisForFileX = worldAxisForFileX;
  65260. this.worldAxisForFileY = worldAxisForFileY;
  65261. }
  65262. return FileFaceOrientation;
  65263. }());
  65264. ;
  65265. /**
  65266. * Helper class dealing with the extraction of spherical polynomial dataArray
  65267. * from a cube map.
  65268. */
  65269. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  65270. function CubeMapToSphericalPolynomialTools() {
  65271. }
  65272. /**
  65273. * Converts a texture to the according Spherical Polynomial data.
  65274. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65275. *
  65276. * @param texture The texture to extract the information from.
  65277. * @return The Spherical Polynomial data.
  65278. */
  65279. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  65280. if (!texture.isCube) {
  65281. // Only supports cube Textures currently.
  65282. return null;
  65283. }
  65284. var size = texture.getSize().width;
  65285. var right = texture.readPixels(0);
  65286. var left = texture.readPixels(1);
  65287. var up;
  65288. var down;
  65289. if (texture.isRenderTarget) {
  65290. up = texture.readPixels(3);
  65291. down = texture.readPixels(2);
  65292. }
  65293. else {
  65294. up = texture.readPixels(2);
  65295. down = texture.readPixels(3);
  65296. }
  65297. var front = texture.readPixels(4);
  65298. var back = texture.readPixels(5);
  65299. var gammaSpace = texture.gammaSpace;
  65300. // Always read as RGBA.
  65301. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  65302. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65303. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65304. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65305. }
  65306. var cubeInfo = {
  65307. size: size,
  65308. right: right,
  65309. left: left,
  65310. up: up,
  65311. down: down,
  65312. front: front,
  65313. back: back,
  65314. format: format,
  65315. type: type,
  65316. gammaSpace: gammaSpace,
  65317. };
  65318. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  65319. };
  65320. /**
  65321. * Converts a cubemap to the according Spherical Polynomial data.
  65322. * This extracts the first 3 orders only as they are the only one used in the lighting.
  65323. *
  65324. * @param cubeInfo The Cube map to extract the information from.
  65325. * @return The Spherical Polynomial data.
  65326. */
  65327. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  65328. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  65329. var totalSolidAngle = 0.0;
  65330. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  65331. var du = 2.0 / cubeInfo.size;
  65332. var dv = du;
  65333. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  65334. var minUV = du * 0.5 - 1.0;
  65335. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65336. var fileFace = this.FileFaces[faceIndex];
  65337. var dataArray = cubeInfo[fileFace.name];
  65338. var v = minUV;
  65339. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  65340. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  65341. // Because SP is still linear, so summation is fine in that basis.
  65342. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  65343. for (var y = 0; y < cubeInfo.size; y++) {
  65344. var u = minUV;
  65345. for (var x = 0; x < cubeInfo.size; x++) {
  65346. // World direction (not normalised)
  65347. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  65348. worldDirection.normalize();
  65349. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  65350. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  65351. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  65352. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  65353. // Handle Integer types.
  65354. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65355. r /= 255;
  65356. g /= 255;
  65357. b /= 255;
  65358. }
  65359. // Handle Gamma space textures.
  65360. if (cubeInfo.gammaSpace) {
  65361. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  65362. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  65363. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  65364. }
  65365. var color = new BABYLON.Color3(r, g, b);
  65366. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  65367. totalSolidAngle += deltaSolidAngle;
  65368. u += du;
  65369. }
  65370. v += dv;
  65371. }
  65372. }
  65373. // Solid angle for entire sphere is 4*pi
  65374. var sphereSolidAngle = 4.0 * Math.PI;
  65375. // Adjust the solid angle to allow for how many faces we processed.
  65376. var facesProcessed = 6.0;
  65377. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  65378. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  65379. // This is needed because the numerical integration over the cube uses a
  65380. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  65381. // and also to compensate for accumulative error due to float precision in the summation.
  65382. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  65383. sphericalHarmonics.scale(correctionFactor);
  65384. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  65385. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  65386. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  65387. };
  65388. CubeMapToSphericalPolynomialTools.FileFaces = [
  65389. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  65390. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  65391. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  65392. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  65393. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  65394. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  65395. ];
  65396. return CubeMapToSphericalPolynomialTools;
  65397. }());
  65398. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  65399. })(BABYLON || (BABYLON = {}));
  65400. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  65401. var BABYLON;
  65402. (function (BABYLON) {
  65403. /**
  65404. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  65405. */
  65406. var PanoramaToCubeMapTools = /** @class */ (function () {
  65407. function PanoramaToCubeMapTools() {
  65408. }
  65409. /**
  65410. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  65411. *
  65412. * @param float32Array The source data.
  65413. * @param inputWidth The width of the input panorama.
  65414. * @param inputhHeight The height of the input panorama.
  65415. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  65416. * @return The cubemap data
  65417. */
  65418. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  65419. if (!float32Array) {
  65420. throw "ConvertPanoramaToCubemap: input cannot be null";
  65421. }
  65422. if (float32Array.length != inputWidth * inputHeight * 3) {
  65423. throw "ConvertPanoramaToCubemap: input size is wrong";
  65424. }
  65425. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  65426. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  65427. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  65428. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  65429. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  65430. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  65431. return {
  65432. front: textureFront,
  65433. back: textureBack,
  65434. left: textureLeft,
  65435. right: textureRight,
  65436. up: textureUp,
  65437. down: textureDown,
  65438. size: size,
  65439. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  65440. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  65441. gammaSpace: false,
  65442. };
  65443. };
  65444. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  65445. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  65446. var textureArray = new Float32Array(buffer);
  65447. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  65448. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  65449. var dy = 1 / texSize;
  65450. var fy = 0;
  65451. for (var y = 0; y < texSize; y++) {
  65452. var xv1 = faceData[0];
  65453. var xv2 = faceData[2];
  65454. for (var x = 0; x < texSize; x++) {
  65455. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  65456. v.normalize();
  65457. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  65458. // 3 channels per pixels
  65459. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  65460. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  65461. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  65462. xv1 = xv1.add(rotDX1);
  65463. xv2 = xv2.add(rotDX2);
  65464. }
  65465. fy += dy;
  65466. }
  65467. return textureArray;
  65468. };
  65469. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  65470. var theta = Math.atan2(vDir.z, vDir.x);
  65471. var phi = Math.acos(vDir.y);
  65472. while (theta < -Math.PI)
  65473. theta += 2 * Math.PI;
  65474. while (theta > Math.PI)
  65475. theta -= 2 * Math.PI;
  65476. var dx = theta / Math.PI;
  65477. var dy = phi / Math.PI;
  65478. // recenter.
  65479. dx = dx * 0.5 + 0.5;
  65480. var px = Math.round(dx * inputWidth);
  65481. if (px < 0)
  65482. px = 0;
  65483. else if (px >= inputWidth)
  65484. px = inputWidth - 1;
  65485. var py = Math.round(dy * inputHeight);
  65486. if (py < 0)
  65487. py = 0;
  65488. else if (py >= inputHeight)
  65489. py = inputHeight - 1;
  65490. var inputY = (inputHeight - py - 1);
  65491. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  65492. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  65493. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  65494. return {
  65495. r: r,
  65496. g: g,
  65497. b: b
  65498. };
  65499. };
  65500. PanoramaToCubeMapTools.FACE_FRONT = [
  65501. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65502. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65503. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65504. new BABYLON.Vector3(1.0, 1.0, -1.0)
  65505. ];
  65506. PanoramaToCubeMapTools.FACE_BACK = [
  65507. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65508. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65509. new BABYLON.Vector3(1.0, 1.0, 1.0),
  65510. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  65511. ];
  65512. PanoramaToCubeMapTools.FACE_RIGHT = [
  65513. new BABYLON.Vector3(1.0, -1.0, -1.0),
  65514. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65515. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65516. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65517. ];
  65518. PanoramaToCubeMapTools.FACE_LEFT = [
  65519. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65520. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65521. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65522. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  65523. ];
  65524. PanoramaToCubeMapTools.FACE_DOWN = [
  65525. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  65526. new BABYLON.Vector3(1.0, 1.0, -1.0),
  65527. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  65528. new BABYLON.Vector3(1.0, 1.0, 1.0)
  65529. ];
  65530. PanoramaToCubeMapTools.FACE_UP = [
  65531. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  65532. new BABYLON.Vector3(1.0, -1.0, 1.0),
  65533. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  65534. new BABYLON.Vector3(1.0, -1.0, -1.0)
  65535. ];
  65536. return PanoramaToCubeMapTools;
  65537. }());
  65538. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  65539. })(BABYLON || (BABYLON = {}));
  65540. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  65541. var BABYLON;
  65542. (function (BABYLON) {
  65543. ;
  65544. /**
  65545. * This groups tools to convert HDR texture to native colors array.
  65546. */
  65547. var HDRTools = /** @class */ (function () {
  65548. function HDRTools() {
  65549. }
  65550. HDRTools.Ldexp = function (mantissa, exponent) {
  65551. if (exponent > 1023) {
  65552. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  65553. }
  65554. if (exponent < -1074) {
  65555. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  65556. }
  65557. return mantissa * Math.pow(2, exponent);
  65558. };
  65559. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  65560. if (exponent > 0) {
  65561. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  65562. float32array[index + 0] = red * exponent;
  65563. float32array[index + 1] = green * exponent;
  65564. float32array[index + 2] = blue * exponent;
  65565. }
  65566. else {
  65567. float32array[index + 0] = 0;
  65568. float32array[index + 1] = 0;
  65569. float32array[index + 2] = 0;
  65570. }
  65571. };
  65572. HDRTools.readStringLine = function (uint8array, startIndex) {
  65573. var line = "";
  65574. var character = "";
  65575. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  65576. character = String.fromCharCode(uint8array[i]);
  65577. if (character == "\n") {
  65578. break;
  65579. }
  65580. line += character;
  65581. }
  65582. return line;
  65583. };
  65584. /**
  65585. * Reads header information from an RGBE texture stored in a native array.
  65586. * More information on this format are available here:
  65587. * https://en.wikipedia.org/wiki/RGBE_image_format
  65588. *
  65589. * @param uint8array The binary file stored in native array.
  65590. * @return The header information.
  65591. */
  65592. HDRTools.RGBE_ReadHeader = function (uint8array) {
  65593. var height = 0;
  65594. var width = 0;
  65595. var line = this.readStringLine(uint8array, 0);
  65596. if (line[0] != '#' || line[1] != '?') {
  65597. throw "Bad HDR Format.";
  65598. }
  65599. var endOfHeader = false;
  65600. var findFormat = false;
  65601. var lineIndex = 0;
  65602. do {
  65603. lineIndex += (line.length + 1);
  65604. line = this.readStringLine(uint8array, lineIndex);
  65605. if (line == "FORMAT=32-bit_rle_rgbe") {
  65606. findFormat = true;
  65607. }
  65608. else if (line.length == 0) {
  65609. endOfHeader = true;
  65610. }
  65611. } while (!endOfHeader);
  65612. if (!findFormat) {
  65613. throw "HDR Bad header format, unsupported FORMAT";
  65614. }
  65615. lineIndex += (line.length + 1);
  65616. line = this.readStringLine(uint8array, lineIndex);
  65617. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  65618. var match = sizeRegexp.exec(line);
  65619. // TODO. Support +Y and -X if needed.
  65620. if (!match || match.length < 3) {
  65621. throw "HDR Bad header format, no size";
  65622. }
  65623. width = parseInt(match[2]);
  65624. height = parseInt(match[1]);
  65625. if (width < 8 || width > 0x7fff) {
  65626. throw "HDR Bad header format, unsupported size";
  65627. }
  65628. lineIndex += (line.length + 1);
  65629. return {
  65630. height: height,
  65631. width: width,
  65632. dataPosition: lineIndex
  65633. };
  65634. };
  65635. /**
  65636. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  65637. * This RGBE texture needs to store the information as a panorama.
  65638. *
  65639. * More information on this format are available here:
  65640. * https://en.wikipedia.org/wiki/RGBE_image_format
  65641. *
  65642. * @param buffer The binary file stored in an array buffer.
  65643. * @param size The expected size of the extracted cubemap.
  65644. * @return The Cube Map information.
  65645. */
  65646. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  65647. var uint8array = new Uint8Array(buffer);
  65648. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  65649. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65650. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  65651. return cubeMapData;
  65652. };
  65653. /**
  65654. * Returns the pixels data extracted from an RGBE texture.
  65655. * This pixels will be stored left to right up to down in the R G B order in one array.
  65656. *
  65657. * More information on this format are available here:
  65658. * https://en.wikipedia.org/wiki/RGBE_image_format
  65659. *
  65660. * @param uint8array The binary file stored in an array buffer.
  65661. * @param hdrInfo The header information of the file.
  65662. * @return The pixels data in RGB right to left up to down order.
  65663. */
  65664. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  65665. // Keep for multi format supports.
  65666. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  65667. };
  65668. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  65669. var num_scanlines = hdrInfo.height;
  65670. var scanline_width = hdrInfo.width;
  65671. var a, b, c, d, count;
  65672. var dataIndex = hdrInfo.dataPosition;
  65673. var index = 0, endIndex = 0, i = 0;
  65674. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  65675. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  65676. // 3 channels of 4 bytes per pixel in float.
  65677. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  65678. var resultArray = new Float32Array(resultBuffer);
  65679. // read in each successive scanline
  65680. while (num_scanlines > 0) {
  65681. a = uint8array[dataIndex++];
  65682. b = uint8array[dataIndex++];
  65683. c = uint8array[dataIndex++];
  65684. d = uint8array[dataIndex++];
  65685. if (a != 2 || b != 2 || (c & 0x80)) {
  65686. // this file is not run length encoded
  65687. throw "HDR Bad header format, not RLE";
  65688. }
  65689. if (((c << 8) | d) != scanline_width) {
  65690. throw "HDR Bad header format, wrong scan line width";
  65691. }
  65692. index = 0;
  65693. // read each of the four channels for the scanline into the buffer
  65694. for (i = 0; i < 4; i++) {
  65695. endIndex = (i + 1) * scanline_width;
  65696. while (index < endIndex) {
  65697. a = uint8array[dataIndex++];
  65698. b = uint8array[dataIndex++];
  65699. if (a > 128) {
  65700. // a run of the same value
  65701. count = a - 128;
  65702. if ((count == 0) || (count > endIndex - index)) {
  65703. throw "HDR Bad Format, bad scanline data (run)";
  65704. }
  65705. while (count-- > 0) {
  65706. scanLineArray[index++] = b;
  65707. }
  65708. }
  65709. else {
  65710. // a non-run
  65711. count = a;
  65712. if ((count == 0) || (count > endIndex - index)) {
  65713. throw "HDR Bad Format, bad scanline data (non-run)";
  65714. }
  65715. scanLineArray[index++] = b;
  65716. if (--count > 0) {
  65717. for (var j = 0; j < count; j++) {
  65718. scanLineArray[index++] = uint8array[dataIndex++];
  65719. }
  65720. }
  65721. }
  65722. }
  65723. }
  65724. // now convert data from buffer into floats
  65725. for (i = 0; i < scanline_width; i++) {
  65726. a = scanLineArray[i];
  65727. b = scanLineArray[i + scanline_width];
  65728. c = scanLineArray[i + 2 * scanline_width];
  65729. d = scanLineArray[i + 3 * scanline_width];
  65730. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65731. }
  65732. num_scanlines--;
  65733. }
  65734. return resultArray;
  65735. };
  65736. return HDRTools;
  65737. }());
  65738. BABYLON.HDRTools = HDRTools;
  65739. })(BABYLON || (BABYLON = {}));
  65740. //# sourceMappingURL=babylon.hdr.js.map
  65741. var BABYLON;
  65742. (function (BABYLON) {
  65743. /**
  65744. * This represents a texture coming from an HDR input.
  65745. *
  65746. * The only supported format is currently panorama picture stored in RGBE format.
  65747. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65748. */
  65749. var HDRCubeTexture = /** @class */ (function (_super) {
  65750. __extends(HDRCubeTexture, _super);
  65751. /**
  65752. * Instantiates an HDRTexture from the following parameters.
  65753. *
  65754. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65755. * @param scene The scene the texture will be used in
  65756. * @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.
  65757. * @param noMipmap Forces to not generate the mipmap if true
  65758. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  65759. * @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)
  65760. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65761. */
  65762. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65763. if (noMipmap === void 0) { noMipmap = false; }
  65764. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65765. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65766. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65767. if (onLoad === void 0) { onLoad = null; }
  65768. if (onError === void 0) { onError = null; }
  65769. var _this = _super.call(this, scene) || this;
  65770. _this._useInGammaSpace = false;
  65771. _this._generateHarmonics = true;
  65772. _this._isBABYLONPreprocessed = false;
  65773. _this._onLoad = null;
  65774. _this._onError = null;
  65775. /**
  65776. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65777. */
  65778. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65779. /**
  65780. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65781. * This is usefull at run time to apply the good shader.
  65782. */
  65783. _this.isPMREM = false;
  65784. _this._isBlocking = true;
  65785. if (!url) {
  65786. return _this;
  65787. }
  65788. _this.name = url;
  65789. _this.url = url;
  65790. _this.hasAlpha = false;
  65791. _this.isCube = true;
  65792. _this._textureMatrix = BABYLON.Matrix.Identity();
  65793. _this._onLoad = onLoad;
  65794. _this._onError = onError;
  65795. _this.gammaSpace = false;
  65796. var caps = scene.getEngine().getCaps();
  65797. if (size) {
  65798. _this._isBABYLONPreprocessed = false;
  65799. _this._noMipmap = noMipmap;
  65800. _this._size = size;
  65801. _this._useInGammaSpace = useInGammaSpace;
  65802. _this._usePMREMGenerator = usePMREMGenerator &&
  65803. caps.textureLOD &&
  65804. caps.textureFloat &&
  65805. !_this._useInGammaSpace;
  65806. }
  65807. else {
  65808. _this._isBABYLONPreprocessed = true;
  65809. _this._noMipmap = false;
  65810. _this._useInGammaSpace = false;
  65811. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65812. !_this._useInGammaSpace;
  65813. }
  65814. _this.isPMREM = _this._usePMREMGenerator;
  65815. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65816. if (!_this._texture) {
  65817. if (!scene.useDelayedTextureLoading) {
  65818. _this.loadTexture();
  65819. }
  65820. else {
  65821. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65822. }
  65823. }
  65824. return _this;
  65825. }
  65826. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65827. /**
  65828. * Gets wether or not the texture is blocking during loading.
  65829. */
  65830. get: function () {
  65831. return this._isBlocking;
  65832. },
  65833. /**
  65834. * Sets wether or not the texture is blocking during loading.
  65835. */
  65836. set: function (value) {
  65837. this._isBlocking = value;
  65838. },
  65839. enumerable: true,
  65840. configurable: true
  65841. });
  65842. /**
  65843. * Occurs when the file is a preprocessed .babylon.hdr file.
  65844. */
  65845. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  65846. var _this = this;
  65847. var mipLevels = 0;
  65848. var floatArrayView = null;
  65849. var scene = this.getScene();
  65850. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  65851. var mips = new Array();
  65852. if (!floatArrayView) {
  65853. return mips;
  65854. }
  65855. var startIndex = 30;
  65856. for (var level = 0; level < mipLevels; level++) {
  65857. mips.push([]);
  65858. // Fill each pixel of the mip level.
  65859. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  65860. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65861. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  65862. mips[level].push(faceData);
  65863. startIndex += faceSize;
  65864. }
  65865. }
  65866. return mips;
  65867. } : null;
  65868. var callback = function (buffer) {
  65869. var scene = _this.getScene();
  65870. if (!scene) {
  65871. return null;
  65872. }
  65873. // Create Native Array Views
  65874. var intArrayView = new Int32Array(buffer);
  65875. floatArrayView = new Float32Array(buffer);
  65876. // Fill header.
  65877. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  65878. _this._size = intArrayView[1]; // CubeMap max mip face size.
  65879. // Update Texture Information.
  65880. if (!_this._texture) {
  65881. return null;
  65882. }
  65883. _this._texture.updateSize(_this._size, _this._size);
  65884. // Fill polynomial information.
  65885. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  65886. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  65887. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  65888. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  65889. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  65890. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  65891. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  65892. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  65893. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  65894. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  65895. _this.sphericalPolynomial = sphericalPolynomial;
  65896. // Fill pixel data.
  65897. mipLevels = intArrayView[29]; // Number of mip levels.
  65898. var startIndex = 30;
  65899. var data = [];
  65900. var faceSize = Math.pow(_this._size, 2) * 3;
  65901. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65902. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  65903. startIndex += faceSize;
  65904. }
  65905. var results = [];
  65906. var byteArray = null;
  65907. // Push each faces.
  65908. for (var k = 0; k < 6; k++) {
  65909. var dataFace = null;
  65910. // To be deprecated.
  65911. if (version === 1) {
  65912. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  65913. dataFace = data[j];
  65914. }
  65915. // If special cases.
  65916. if (!mipmapGenerator && dataFace) {
  65917. if (!scene.getEngine().getCaps().textureFloat) {
  65918. // 3 channels of 1 bytes per pixel in bytes.
  65919. var byteBuffer = new ArrayBuffer(faceSize);
  65920. byteArray = new Uint8Array(byteBuffer);
  65921. }
  65922. for (var i = 0; i < _this._size * _this._size; i++) {
  65923. // Put in gamma space if requested.
  65924. if (_this._useInGammaSpace) {
  65925. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65926. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65927. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65928. }
  65929. // Convert to int texture for fallback.
  65930. if (byteArray) {
  65931. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65932. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65933. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65934. // May use luminance instead if the result is not accurate.
  65935. var max = Math.max(Math.max(r, g), b);
  65936. if (max > 255) {
  65937. var scale = 255 / max;
  65938. r *= scale;
  65939. g *= scale;
  65940. b *= scale;
  65941. }
  65942. byteArray[(i * 3) + 0] = r;
  65943. byteArray[(i * 3) + 1] = g;
  65944. byteArray[(i * 3) + 2] = b;
  65945. }
  65946. }
  65947. }
  65948. // Fill the array accordingly.
  65949. if (byteArray) {
  65950. results.push(byteArray);
  65951. }
  65952. else {
  65953. results.push(dataFace);
  65954. }
  65955. }
  65956. return results;
  65957. };
  65958. if (scene) {
  65959. 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);
  65960. }
  65961. };
  65962. /**
  65963. * Occurs when the file is raw .hdr file.
  65964. */
  65965. HDRCubeTexture.prototype.loadHDRTexture = function () {
  65966. var _this = this;
  65967. var callback = function (buffer) {
  65968. var scene = _this.getScene();
  65969. if (!scene) {
  65970. return null;
  65971. }
  65972. // Extract the raw linear data.
  65973. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  65974. // Generate harmonics if needed.
  65975. if (_this._generateHarmonics) {
  65976. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  65977. _this.sphericalPolynomial = sphericalPolynomial;
  65978. }
  65979. var results = [];
  65980. var byteArray = null;
  65981. // Push each faces.
  65982. for (var j = 0; j < 6; j++) {
  65983. // Create uintarray fallback.
  65984. if (!scene.getEngine().getCaps().textureFloat) {
  65985. // 3 channels of 1 bytes per pixel in bytes.
  65986. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  65987. byteArray = new Uint8Array(byteBuffer);
  65988. }
  65989. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  65990. // If special cases.
  65991. if (_this._useInGammaSpace || byteArray) {
  65992. for (var i = 0; i < _this._size * _this._size; i++) {
  65993. // Put in gamma space if requested.
  65994. if (_this._useInGammaSpace) {
  65995. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65996. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65997. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65998. }
  65999. // Convert to int texture for fallback.
  66000. if (byteArray) {
  66001. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  66002. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  66003. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  66004. // May use luminance instead if the result is not accurate.
  66005. var max = Math.max(Math.max(r, g), b);
  66006. if (max > 255) {
  66007. var scale = 255 / max;
  66008. r *= scale;
  66009. g *= scale;
  66010. b *= scale;
  66011. }
  66012. byteArray[(i * 3) + 0] = r;
  66013. byteArray[(i * 3) + 1] = g;
  66014. byteArray[(i * 3) + 2] = b;
  66015. }
  66016. }
  66017. }
  66018. if (byteArray) {
  66019. results.push(byteArray);
  66020. }
  66021. else {
  66022. results.push(dataFace);
  66023. }
  66024. }
  66025. return results;
  66026. };
  66027. var mipmapGenerator = null;
  66028. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  66029. // if (!this._noMipmap &&
  66030. // this._usePMREMGenerator) {
  66031. // mipmapGenerator = (data: ArrayBufferView[]) => {
  66032. // // Custom setup of the generator matching with the PBR shader values.
  66033. // var generator = new BABYLON.PMREMGenerator(data,
  66034. // this._size,
  66035. // this._size,
  66036. // 0,
  66037. // 3,
  66038. // this.getScene().getEngine().getCaps().textureFloat,
  66039. // 2048,
  66040. // 0.25,
  66041. // false,
  66042. // true);
  66043. // return generator.filterCubeMap();
  66044. // };
  66045. // }
  66046. var scene = this.getScene();
  66047. if (scene) {
  66048. 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);
  66049. }
  66050. };
  66051. /**
  66052. * Starts the loading process of the texture.
  66053. */
  66054. HDRCubeTexture.prototype.loadTexture = function () {
  66055. if (this._isBABYLONPreprocessed) {
  66056. this.loadBabylonTexture();
  66057. }
  66058. else {
  66059. this.loadHDRTexture();
  66060. }
  66061. };
  66062. HDRCubeTexture.prototype.clone = function () {
  66063. var scene = this.getScene();
  66064. if (!scene) {
  66065. return this;
  66066. }
  66067. var size = (this._isBABYLONPreprocessed ? null : this._size);
  66068. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  66069. // Base texture
  66070. newTexture.level = this.level;
  66071. newTexture.wrapU = this.wrapU;
  66072. newTexture.wrapV = this.wrapV;
  66073. newTexture.coordinatesIndex = this.coordinatesIndex;
  66074. newTexture.coordinatesMode = this.coordinatesMode;
  66075. return newTexture;
  66076. };
  66077. // Methods
  66078. HDRCubeTexture.prototype.delayLoad = function () {
  66079. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  66080. return;
  66081. }
  66082. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  66083. this._texture = this._getFromCache(this.url, this._noMipmap);
  66084. if (!this._texture) {
  66085. this.loadTexture();
  66086. }
  66087. };
  66088. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  66089. return this._textureMatrix;
  66090. };
  66091. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  66092. this._textureMatrix = value;
  66093. };
  66094. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  66095. var texture = null;
  66096. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  66097. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  66098. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  66099. texture.name = parsedTexture.name;
  66100. texture.hasAlpha = parsedTexture.hasAlpha;
  66101. texture.level = parsedTexture.level;
  66102. texture.coordinatesMode = parsedTexture.coordinatesMode;
  66103. texture.isBlocking = parsedTexture.isBlocking;
  66104. }
  66105. return texture;
  66106. };
  66107. HDRCubeTexture.prototype.serialize = function () {
  66108. if (!this.name) {
  66109. return null;
  66110. }
  66111. var serializationObject = {};
  66112. serializationObject.name = this.name;
  66113. serializationObject.hasAlpha = this.hasAlpha;
  66114. serializationObject.isCube = true;
  66115. serializationObject.level = this.level;
  66116. serializationObject.size = this._size;
  66117. serializationObject.coordinatesMode = this.coordinatesMode;
  66118. serializationObject.useInGammaSpace = this._useInGammaSpace;
  66119. serializationObject.generateHarmonics = this._generateHarmonics;
  66120. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  66121. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  66122. serializationObject.customType = "BABYLON.HDRCubeTexture";
  66123. serializationObject.noMipmap = this._noMipmap;
  66124. serializationObject.isBlocking = this._isBlocking;
  66125. return serializationObject;
  66126. };
  66127. /**
  66128. * Saves as a file the data contained in the texture in a binary format.
  66129. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66130. * as the spherical used in the lighting.
  66131. * @param url The HDR file url.
  66132. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66133. * @param onError Method called if any error happens during download.
  66134. * @return The packed binary data.
  66135. */
  66136. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  66137. if (onError === void 0) { onError = null; }
  66138. var callback = function (buffer) {
  66139. var data = new Blob([buffer], { type: 'application/octet-stream' });
  66140. // Returns a URL you can use as a href.
  66141. var objUrl = window.URL.createObjectURL(data);
  66142. // Simulates a link to it and click to dowload.
  66143. var a = document.createElement("a");
  66144. document.body.appendChild(a);
  66145. a.style.display = "none";
  66146. a.href = objUrl;
  66147. a.download = "envmap.babylon.hdr";
  66148. a.click();
  66149. };
  66150. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  66151. };
  66152. /**
  66153. * Serializes the data contained in the texture in a binary format.
  66154. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  66155. * as the spherical used in the lighting.
  66156. * @param url The HDR file url.
  66157. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  66158. * @param onError Method called if any error happens during download.
  66159. * @return The packed binary data.
  66160. */
  66161. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  66162. if (onError === void 0) { onError = null; }
  66163. // Needs the url tho create the texture.
  66164. if (!url) {
  66165. return;
  66166. }
  66167. // Check Power of two size.
  66168. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  66169. return;
  66170. }
  66171. // Coming Back in 3.x.
  66172. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  66173. };
  66174. HDRCubeTexture._facesMapping = [
  66175. "right",
  66176. "left",
  66177. "up",
  66178. "down",
  66179. "front",
  66180. "back"
  66181. ];
  66182. return HDRCubeTexture;
  66183. }(BABYLON.BaseTexture));
  66184. BABYLON.HDRCubeTexture = HDRCubeTexture;
  66185. })(BABYLON || (BABYLON = {}));
  66186. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  66187. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  66188. // Huge respect for a such great lib.
  66189. // Earcut license:
  66190. // Copyright (c) 2016, Mapbox
  66191. //
  66192. // Permission to use, copy, modify, and/or distribute this software for any purpose
  66193. // with or without fee is hereby granted, provided that the above copyright notice
  66194. // and this permission notice appear in all copies.
  66195. //
  66196. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  66197. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  66198. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  66199. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  66200. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  66201. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  66202. // THIS SOFTWARE.
  66203. var Earcut;
  66204. (function (Earcut) {
  66205. /**
  66206. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  66207. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  66208. * @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).
  66209. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  66210. */
  66211. function earcut(data, holeIndices, dim) {
  66212. dim = dim || 2;
  66213. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  66214. if (!outerNode)
  66215. return triangles;
  66216. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  66217. if (hasHoles)
  66218. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  66219. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  66220. if (data.length > 80 * dim) {
  66221. minX = maxX = data[0];
  66222. minY = maxY = data[1];
  66223. for (var i = dim; i < outerLen; i += dim) {
  66224. x = data[i];
  66225. y = data[i + 1];
  66226. if (x < minX)
  66227. minX = x;
  66228. if (y < minY)
  66229. minY = y;
  66230. if (x > maxX)
  66231. maxX = x;
  66232. if (y > maxY)
  66233. maxY = y;
  66234. }
  66235. // minX, minY and size are later used to transform coords into integers for z-order calculation
  66236. size = Math.max(maxX - minX, maxY - minY);
  66237. }
  66238. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  66239. return triangles;
  66240. }
  66241. Earcut.earcut = earcut;
  66242. var Node = /** @class */ (function () {
  66243. function Node(i, x, y) {
  66244. this.i = i;
  66245. this.x = x;
  66246. this.y = y;
  66247. this.prev = null;
  66248. this.next = null;
  66249. this.z = null;
  66250. this.prevZ = null;
  66251. this.nextZ = null;
  66252. this.steiner = false;
  66253. }
  66254. return Node;
  66255. }());
  66256. // create a circular doubly linked list from polygon points in the specified winding order
  66257. function linkedList(data, start, end, dim, clockwise) {
  66258. var i, last = null;
  66259. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  66260. for (i = start; i < end; i += dim)
  66261. last = insertNode(i, data[i], data[i + 1], last);
  66262. }
  66263. else {
  66264. for (i = end - dim; i >= start; i -= dim)
  66265. last = insertNode(i, data[i], data[i + 1], last);
  66266. }
  66267. if (last && equals(last, last.next)) {
  66268. removeNode(last);
  66269. last = last.next;
  66270. }
  66271. return last;
  66272. }
  66273. // eliminate colinear or duplicate points
  66274. function filterPoints(start, end) {
  66275. if (!start)
  66276. return start;
  66277. if (!end)
  66278. end = start;
  66279. var p = start, again;
  66280. do {
  66281. again = false;
  66282. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  66283. removeNode(p);
  66284. p = end = p.prev;
  66285. if (p === p.next)
  66286. return undefined;
  66287. again = true;
  66288. }
  66289. else {
  66290. p = p.next;
  66291. }
  66292. } while (again || p !== end);
  66293. return end;
  66294. }
  66295. // main ear slicing loop which triangulates a polygon (given as a linked list)
  66296. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  66297. if (!ear)
  66298. return;
  66299. // interlink polygon nodes in z-order
  66300. if (!pass && size)
  66301. indexCurve(ear, minX, minY, size);
  66302. var stop = ear, prev, next;
  66303. // iterate through ears, slicing them one by one
  66304. while (ear.prev !== ear.next) {
  66305. prev = ear.prev;
  66306. next = ear.next;
  66307. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  66308. // cut off the triangle
  66309. triangles.push(prev.i / dim);
  66310. triangles.push(ear.i / dim);
  66311. triangles.push(next.i / dim);
  66312. removeNode(ear);
  66313. // skipping the next vertice leads to less sliver triangles
  66314. ear = next.next;
  66315. stop = next.next;
  66316. continue;
  66317. }
  66318. ear = next;
  66319. // if we looped through the whole remaining polygon and can't find any more ears
  66320. if (ear === stop) {
  66321. // try filtering points and slicing again
  66322. if (!pass) {
  66323. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  66324. // if this didn't work, try curing all small self-intersections locally
  66325. }
  66326. else if (pass === 1) {
  66327. ear = cureLocalIntersections(ear, triangles, dim);
  66328. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  66329. // as a last resort, try splitting the remaining polygon into two
  66330. }
  66331. else if (pass === 2) {
  66332. splitEarcut(ear, triangles, dim, minX, minY, size);
  66333. }
  66334. break;
  66335. }
  66336. }
  66337. }
  66338. // check whether a polygon node forms a valid ear with adjacent nodes
  66339. function isEar(ear) {
  66340. var a = ear.prev, b = ear, c = ear.next;
  66341. if (area(a, b, c) >= 0)
  66342. return false; // reflex, can't be an ear
  66343. // now make sure we don't have other points inside the potential ear
  66344. var p = ear.next.next;
  66345. while (p !== ear.prev) {
  66346. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66347. area(p.prev, p, p.next) >= 0)
  66348. return false;
  66349. p = p.next;
  66350. }
  66351. return true;
  66352. }
  66353. function isEarHashed(ear, minX, minY, size) {
  66354. var a = ear.prev, b = ear, c = ear.next;
  66355. if (area(a, b, c) >= 0)
  66356. return false; // reflex, can't be an ear
  66357. // triangle bbox; min & max are calculated like this for speed
  66358. 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);
  66359. // z-order range for the current triangle bbox;
  66360. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  66361. // first look for points inside the triangle in increasing z-order
  66362. var p = ear.nextZ;
  66363. while (p && p.z <= maxZ) {
  66364. if (p !== ear.prev &&
  66365. p !== ear.next &&
  66366. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66367. area(p.prev, p, p.next) >= 0)
  66368. return false;
  66369. p = p.nextZ;
  66370. }
  66371. // then look for points in decreasing z-order
  66372. p = ear.prevZ;
  66373. while (p && p.z >= minZ) {
  66374. if (p !== ear.prev &&
  66375. p !== ear.next &&
  66376. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  66377. area(p.prev, p, p.next) >= 0)
  66378. return false;
  66379. p = p.prevZ;
  66380. }
  66381. return true;
  66382. }
  66383. // go through all polygon nodes and cure small local self-intersections
  66384. function cureLocalIntersections(start, triangles, dim) {
  66385. var p = start;
  66386. do {
  66387. var a = p.prev, b = p.next.next;
  66388. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  66389. triangles.push(a.i / dim);
  66390. triangles.push(p.i / dim);
  66391. triangles.push(b.i / dim);
  66392. // remove two nodes involved
  66393. removeNode(p);
  66394. removeNode(p.next);
  66395. p = start = b;
  66396. }
  66397. p = p.next;
  66398. } while (p !== start);
  66399. return p;
  66400. }
  66401. // try splitting polygon into two and triangulate them independently
  66402. function splitEarcut(start, triangles, dim, minX, minY, size) {
  66403. // look for a valid diagonal that divides the polygon into two
  66404. var a = start;
  66405. do {
  66406. var b = a.next.next;
  66407. while (b !== a.prev) {
  66408. if (a.i !== b.i && isValidDiagonal(a, b)) {
  66409. // split the polygon in two by the diagonal
  66410. var c = splitPolygon(a, b);
  66411. // filter colinear points around the cuts
  66412. a = filterPoints(a, a.next);
  66413. c = filterPoints(c, c.next);
  66414. // run earcut on each half
  66415. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  66416. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  66417. return;
  66418. }
  66419. b = b.next;
  66420. }
  66421. a = a.next;
  66422. } while (a !== start);
  66423. }
  66424. // link every hole into the outer loop, producing a single-ring polygon without holes
  66425. function eliminateHoles(data, holeIndices, outerNode, dim) {
  66426. var queue = [], i, len, start, end, list;
  66427. for (i = 0, len = holeIndices.length; i < len; i++) {
  66428. start = holeIndices[i] * dim;
  66429. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66430. list = linkedList(data, start, end, dim, false);
  66431. if (list === list.next)
  66432. list.steiner = true;
  66433. queue.push(getLeftmost(list));
  66434. }
  66435. queue.sort(compareX);
  66436. // process holes from left to right
  66437. for (i = 0; i < queue.length; i++) {
  66438. eliminateHole(queue[i], outerNode);
  66439. outerNode = filterPoints(outerNode, outerNode.next);
  66440. }
  66441. return outerNode;
  66442. }
  66443. function compareX(a, b) {
  66444. return a.x - b.x;
  66445. }
  66446. // find a bridge between vertices that connects hole with an outer ring and and link it
  66447. function eliminateHole(hole, outerNode) {
  66448. outerNode = findHoleBridge(hole, outerNode);
  66449. if (outerNode) {
  66450. var b = splitPolygon(outerNode, hole);
  66451. filterPoints(b, b.next);
  66452. }
  66453. }
  66454. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  66455. function findHoleBridge(hole, outerNode) {
  66456. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  66457. // find a segment intersected by a ray from the hole's leftmost point to the left;
  66458. // segment's endpoint with lesser x will be potential connection point
  66459. do {
  66460. if (hy <= p.y && hy >= p.next.y) {
  66461. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  66462. if (x <= hx && x > qx) {
  66463. qx = x;
  66464. if (x === hx) {
  66465. if (hy === p.y)
  66466. return p;
  66467. if (hy === p.next.y)
  66468. return p.next;
  66469. }
  66470. m = p.x < p.next.x ? p : p.next;
  66471. }
  66472. }
  66473. p = p.next;
  66474. } while (p !== outerNode);
  66475. if (!m)
  66476. return null;
  66477. if (hx === qx)
  66478. return m.prev; // hole touches outer segment; pick lower endpoint
  66479. // look for points inside the triangle of hole point, segment intersection and endpoint;
  66480. // if there are no points found, we have a valid connection;
  66481. // otherwise choose the point of the minimum angle with the ray as connection point
  66482. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  66483. p = m.next;
  66484. while (p !== stop) {
  66485. if (hx >= p.x &&
  66486. p.x >= mx &&
  66487. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  66488. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  66489. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  66490. m = p;
  66491. tanMin = tan;
  66492. }
  66493. }
  66494. p = p.next;
  66495. }
  66496. return m;
  66497. }
  66498. // interlink polygon nodes in z-order
  66499. function indexCurve(start, minX, minY, size) {
  66500. var p = start;
  66501. do {
  66502. if (p.z === null)
  66503. p.z = zOrder(p.x, p.y, minX, minY, size);
  66504. p.prevZ = p.prev;
  66505. p.nextZ = p.next;
  66506. p = p.next;
  66507. } while (p !== start);
  66508. p.prevZ.nextZ = null;
  66509. p.prevZ = null;
  66510. sortLinked(p);
  66511. }
  66512. // Simon Tatham's linked list merge sort algorithm
  66513. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  66514. function sortLinked(list) {
  66515. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  66516. do {
  66517. p = list;
  66518. list = null;
  66519. tail = null;
  66520. numMerges = 0;
  66521. while (p) {
  66522. numMerges++;
  66523. q = p;
  66524. pSize = 0;
  66525. for (i = 0; i < inSize; i++) {
  66526. pSize++;
  66527. q = q.nextZ;
  66528. if (!q)
  66529. break;
  66530. }
  66531. qSize = inSize;
  66532. while (pSize > 0 || (qSize > 0 && q)) {
  66533. if (pSize === 0) {
  66534. e = q;
  66535. q = q.nextZ;
  66536. qSize--;
  66537. }
  66538. else if (qSize === 0 || !q) {
  66539. e = p;
  66540. p = p.nextZ;
  66541. pSize--;
  66542. }
  66543. else if (p.z <= q.z) {
  66544. e = p;
  66545. p = p.nextZ;
  66546. pSize--;
  66547. }
  66548. else {
  66549. e = q;
  66550. q = q.nextZ;
  66551. qSize--;
  66552. }
  66553. if (tail)
  66554. tail.nextZ = e;
  66555. else
  66556. list = e;
  66557. e.prevZ = tail;
  66558. tail = e;
  66559. }
  66560. p = q;
  66561. }
  66562. tail.nextZ = null;
  66563. inSize *= 2;
  66564. } while (numMerges > 1);
  66565. return list;
  66566. }
  66567. // z-order of a point given coords and size of the data bounding box
  66568. function zOrder(x, y, minX, minY, size) {
  66569. // coords are transformed into non-negative 15-bit integer range
  66570. x = 32767 * (x - minX) / size;
  66571. y = 32767 * (y - minY) / size;
  66572. x = (x | (x << 8)) & 0x00FF00FF;
  66573. x = (x | (x << 4)) & 0x0F0F0F0F;
  66574. x = (x | (x << 2)) & 0x33333333;
  66575. x = (x | (x << 1)) & 0x55555555;
  66576. y = (y | (y << 8)) & 0x00FF00FF;
  66577. y = (y | (y << 4)) & 0x0F0F0F0F;
  66578. y = (y | (y << 2)) & 0x33333333;
  66579. y = (y | (y << 1)) & 0x55555555;
  66580. return x | (y << 1);
  66581. }
  66582. // find the leftmost node of a polygon ring
  66583. function getLeftmost(start) {
  66584. var p = start, leftmost = start;
  66585. do {
  66586. if (p.x < leftmost.x)
  66587. leftmost = p;
  66588. p = p.next;
  66589. } while (p !== start);
  66590. return leftmost;
  66591. }
  66592. // check if a point lies within a convex triangle
  66593. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  66594. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  66595. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  66596. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  66597. }
  66598. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  66599. function isValidDiagonal(a, b) {
  66600. return a.next.i !== b.i &&
  66601. a.prev.i !== b.i &&
  66602. !intersectsPolygon(a, b) &&
  66603. locallyInside(a, b) &&
  66604. locallyInside(b, a) &&
  66605. middleInside(a, b);
  66606. }
  66607. // signed area of a triangle
  66608. function area(p, q, r) {
  66609. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  66610. }
  66611. // check if two points are equal
  66612. function equals(p1, p2) {
  66613. return p1.x === p2.x && p1.y === p2.y;
  66614. }
  66615. // check if two segments intersect
  66616. function intersects(p1, q1, p2, q2) {
  66617. if ((equals(p1, q1) && equals(p2, q2)) ||
  66618. (equals(p1, q2) && equals(p2, q1)))
  66619. return true;
  66620. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  66621. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  66622. }
  66623. // check if a polygon diagonal intersects any polygon segments
  66624. function intersectsPolygon(a, b) {
  66625. var p = a;
  66626. do {
  66627. if (p.i !== a.i &&
  66628. p.next.i !== a.i &&
  66629. p.i !== b.i &&
  66630. p.next.i !== b.i &&
  66631. intersects(p, p.next, a, b))
  66632. return true;
  66633. p = p.next;
  66634. } while (p !== a);
  66635. return false;
  66636. }
  66637. // check if a polygon diagonal is locally inside the polygon
  66638. function locallyInside(a, b) {
  66639. return area(a.prev, a, a.next) < 0
  66640. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  66641. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  66642. }
  66643. // check if the middle point of a polygon diagonal is inside the polygon
  66644. function middleInside(a, b) {
  66645. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  66646. do {
  66647. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  66648. inside = !inside;
  66649. p = p.next;
  66650. } while (p !== a);
  66651. return inside;
  66652. }
  66653. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  66654. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  66655. function splitPolygon(a, b) {
  66656. 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;
  66657. a.next = b;
  66658. b.prev = a;
  66659. a2.next = an;
  66660. an.prev = a2;
  66661. b2.next = a2;
  66662. a2.prev = b2;
  66663. bp.next = b2;
  66664. b2.prev = bp;
  66665. return b2;
  66666. }
  66667. // create a node and optionally link it with previous one (in a circular doubly linked list)
  66668. function insertNode(i, x, y, last) {
  66669. var p = new Node(i, x, y);
  66670. if (!last) {
  66671. p.prev = p;
  66672. p.next = p;
  66673. }
  66674. else {
  66675. p.next = last.next;
  66676. p.prev = last;
  66677. last.next.prev = p;
  66678. last.next = p;
  66679. }
  66680. return p;
  66681. }
  66682. function removeNode(p) {
  66683. p.next.prev = p.prev;
  66684. p.prev.next = p.next;
  66685. if (p.prevZ)
  66686. p.prevZ.nextZ = p.nextZ;
  66687. if (p.nextZ)
  66688. p.nextZ.prevZ = p.prevZ;
  66689. }
  66690. /**
  66691. * return a percentage difference between the polygon area and its triangulation area;
  66692. * used to verify correctness of triangulation
  66693. */
  66694. function deviation(data, holeIndices, dim, triangles) {
  66695. var hasHoles = holeIndices && holeIndices.length;
  66696. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66697. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66698. if (hasHoles) {
  66699. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66700. var start = holeIndices[i] * dim;
  66701. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66702. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66703. }
  66704. }
  66705. var trianglesArea = 0;
  66706. for (i = 0; i < triangles.length; i += 3) {
  66707. var a = triangles[i] * dim;
  66708. var b = triangles[i + 1] * dim;
  66709. var c = triangles[i + 2] * dim;
  66710. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66711. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66712. }
  66713. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66714. }
  66715. Earcut.deviation = deviation;
  66716. ;
  66717. function signedArea(data, start, end, dim) {
  66718. var sum = 0;
  66719. for (var i = start, j = end - dim; i < end; i += dim) {
  66720. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66721. j = i;
  66722. }
  66723. return sum;
  66724. }
  66725. /**
  66726. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66727. */
  66728. function flatten(data) {
  66729. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66730. for (var i = 0; i < data.length; i++) {
  66731. for (var j = 0; j < data[i].length; j++) {
  66732. for (var d = 0; d < dim; d++)
  66733. result.vertices.push(data[i][j][d]);
  66734. }
  66735. if (i > 0) {
  66736. holeIndex += data[i - 1].length;
  66737. result.holes.push(holeIndex);
  66738. }
  66739. }
  66740. return result;
  66741. }
  66742. Earcut.flatten = flatten;
  66743. ;
  66744. })(Earcut || (Earcut = {}));
  66745. //# sourceMappingURL=babylon.earcut.js.map
  66746. var BABYLON;
  66747. (function (BABYLON) {
  66748. var IndexedVector2 = /** @class */ (function (_super) {
  66749. __extends(IndexedVector2, _super);
  66750. function IndexedVector2(original, index) {
  66751. var _this = _super.call(this, original.x, original.y) || this;
  66752. _this.index = index;
  66753. return _this;
  66754. }
  66755. return IndexedVector2;
  66756. }(BABYLON.Vector2));
  66757. var PolygonPoints = /** @class */ (function () {
  66758. function PolygonPoints() {
  66759. this.elements = new Array();
  66760. }
  66761. PolygonPoints.prototype.add = function (originalPoints) {
  66762. var _this = this;
  66763. var result = new Array();
  66764. originalPoints.forEach(function (point) {
  66765. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66766. var newPoint = new IndexedVector2(point, _this.elements.length);
  66767. result.push(newPoint);
  66768. _this.elements.push(newPoint);
  66769. }
  66770. });
  66771. return result;
  66772. };
  66773. PolygonPoints.prototype.computeBounds = function () {
  66774. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66775. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66776. this.elements.forEach(function (point) {
  66777. // x
  66778. if (point.x < lmin.x) {
  66779. lmin.x = point.x;
  66780. }
  66781. else if (point.x > lmax.x) {
  66782. lmax.x = point.x;
  66783. }
  66784. // y
  66785. if (point.y < lmin.y) {
  66786. lmin.y = point.y;
  66787. }
  66788. else if (point.y > lmax.y) {
  66789. lmax.y = point.y;
  66790. }
  66791. });
  66792. return {
  66793. min: lmin,
  66794. max: lmax,
  66795. width: lmax.x - lmin.x,
  66796. height: lmax.y - lmin.y
  66797. };
  66798. };
  66799. return PolygonPoints;
  66800. }());
  66801. var Polygon = /** @class */ (function () {
  66802. function Polygon() {
  66803. }
  66804. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66805. return [
  66806. new BABYLON.Vector2(xmin, ymin),
  66807. new BABYLON.Vector2(xmax, ymin),
  66808. new BABYLON.Vector2(xmax, ymax),
  66809. new BABYLON.Vector2(xmin, ymax)
  66810. ];
  66811. };
  66812. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66813. if (cx === void 0) { cx = 0; }
  66814. if (cy === void 0) { cy = 0; }
  66815. if (numberOfSides === void 0) { numberOfSides = 32; }
  66816. var result = new Array();
  66817. var angle = 0;
  66818. var increment = (Math.PI * 2) / numberOfSides;
  66819. for (var i = 0; i < numberOfSides; i++) {
  66820. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66821. angle -= increment;
  66822. }
  66823. return result;
  66824. };
  66825. Polygon.Parse = function (input) {
  66826. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66827. var i, result = [];
  66828. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66829. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66830. }
  66831. return result;
  66832. };
  66833. Polygon.StartingAt = function (x, y) {
  66834. return BABYLON.Path2.StartingAt(x, y);
  66835. };
  66836. return Polygon;
  66837. }());
  66838. BABYLON.Polygon = Polygon;
  66839. var PolygonMeshBuilder = /** @class */ (function () {
  66840. function PolygonMeshBuilder(name, contours, scene) {
  66841. this._points = new PolygonPoints();
  66842. this._outlinepoints = new PolygonPoints();
  66843. this._holes = new Array();
  66844. this._epoints = new Array();
  66845. this._eholes = new Array();
  66846. this._name = name;
  66847. this._scene = scene;
  66848. var points;
  66849. if (contours instanceof BABYLON.Path2) {
  66850. points = contours.getPoints();
  66851. }
  66852. else {
  66853. points = contours;
  66854. }
  66855. this._addToepoint(points);
  66856. this._points.add(points);
  66857. this._outlinepoints.add(points);
  66858. }
  66859. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  66860. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  66861. var p = points_1[_i];
  66862. this._epoints.push(p.x, p.y);
  66863. }
  66864. };
  66865. PolygonMeshBuilder.prototype.addHole = function (hole) {
  66866. this._points.add(hole);
  66867. var holepoints = new PolygonPoints();
  66868. holepoints.add(hole);
  66869. this._holes.push(holepoints);
  66870. this._eholes.push(this._epoints.length / 2);
  66871. this._addToepoint(hole);
  66872. return this;
  66873. };
  66874. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  66875. var _this = this;
  66876. if (updatable === void 0) { updatable = false; }
  66877. if (depth === void 0) { depth = 0; }
  66878. var result = new BABYLON.Mesh(this._name, this._scene);
  66879. var normals = new Array();
  66880. var positions = new Array();
  66881. var uvs = new Array();
  66882. var bounds = this._points.computeBounds();
  66883. this._points.elements.forEach(function (p) {
  66884. normals.push(0, 1.0, 0);
  66885. positions.push(p.x, 0, p.y);
  66886. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  66887. });
  66888. var indices = new Array();
  66889. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  66890. for (var i = 0; i < res.length; i++) {
  66891. indices.push(res[i]);
  66892. }
  66893. if (depth > 0) {
  66894. var positionscount = (positions.length / 3); //get the current pointcount
  66895. this._points.elements.forEach(function (p) {
  66896. normals.push(0, -1.0, 0);
  66897. positions.push(p.x, -depth, p.y);
  66898. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  66899. });
  66900. var totalCount = indices.length;
  66901. for (var i = 0; i < totalCount; i += 3) {
  66902. var i0 = indices[i + 0];
  66903. var i1 = indices[i + 1];
  66904. var i2 = indices[i + 2];
  66905. indices.push(i2 + positionscount);
  66906. indices.push(i1 + positionscount);
  66907. indices.push(i0 + positionscount);
  66908. }
  66909. //Add the sides
  66910. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  66911. this._holes.forEach(function (hole) {
  66912. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  66913. });
  66914. }
  66915. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  66916. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  66917. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  66918. result.setIndices(indices);
  66919. return result;
  66920. };
  66921. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  66922. var StartIndex = positions.length / 3;
  66923. var ulength = 0;
  66924. for (var i = 0; i < points.elements.length; i++) {
  66925. var p = points.elements[i];
  66926. var p1;
  66927. if ((i + 1) > points.elements.length - 1) {
  66928. p1 = points.elements[0];
  66929. }
  66930. else {
  66931. p1 = points.elements[i + 1];
  66932. }
  66933. positions.push(p.x, 0, p.y);
  66934. positions.push(p.x, -depth, p.y);
  66935. positions.push(p1.x, 0, p1.y);
  66936. positions.push(p1.x, -depth, p1.y);
  66937. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  66938. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  66939. var v3 = v2.subtract(v1);
  66940. var v4 = new BABYLON.Vector3(0, 1, 0);
  66941. var vn = BABYLON.Vector3.Cross(v3, v4);
  66942. vn = vn.normalize();
  66943. uvs.push(ulength / bounds.width, 0);
  66944. uvs.push(ulength / bounds.width, 1);
  66945. ulength += v3.length();
  66946. uvs.push((ulength / bounds.width), 0);
  66947. uvs.push((ulength / bounds.width), 1);
  66948. if (!flip) {
  66949. normals.push(-vn.x, -vn.y, -vn.z);
  66950. normals.push(-vn.x, -vn.y, -vn.z);
  66951. normals.push(-vn.x, -vn.y, -vn.z);
  66952. normals.push(-vn.x, -vn.y, -vn.z);
  66953. indices.push(StartIndex);
  66954. indices.push(StartIndex + 1);
  66955. indices.push(StartIndex + 2);
  66956. indices.push(StartIndex + 1);
  66957. indices.push(StartIndex + 3);
  66958. indices.push(StartIndex + 2);
  66959. }
  66960. else {
  66961. normals.push(vn.x, vn.y, vn.z);
  66962. normals.push(vn.x, vn.y, vn.z);
  66963. normals.push(vn.x, vn.y, vn.z);
  66964. normals.push(vn.x, vn.y, vn.z);
  66965. indices.push(StartIndex);
  66966. indices.push(StartIndex + 2);
  66967. indices.push(StartIndex + 1);
  66968. indices.push(StartIndex + 1);
  66969. indices.push(StartIndex + 2);
  66970. indices.push(StartIndex + 3);
  66971. }
  66972. StartIndex += 4;
  66973. }
  66974. ;
  66975. };
  66976. return PolygonMeshBuilder;
  66977. }());
  66978. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  66979. })(BABYLON || (BABYLON = {}));
  66980. //# sourceMappingURL=babylon.polygonMesh.js.map
  66981. var BABYLON;
  66982. (function (BABYLON) {
  66983. // Unique ID when we import meshes from Babylon to CSG
  66984. var currentCSGMeshId = 0;
  66985. // # class Vertex
  66986. // Represents a vertex of a polygon. Use your own vertex class instead of this
  66987. // one to provide additional features like texture coordinates and vertex
  66988. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  66989. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  66990. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  66991. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  66992. // is not used anywhere else.
  66993. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  66994. var Vertex = /** @class */ (function () {
  66995. function Vertex(pos, normal, uv) {
  66996. this.pos = pos;
  66997. this.normal = normal;
  66998. this.uv = uv;
  66999. }
  67000. Vertex.prototype.clone = function () {
  67001. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  67002. };
  67003. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  67004. // orientation of a polygon is flipped.
  67005. Vertex.prototype.flip = function () {
  67006. this.normal = this.normal.scale(-1);
  67007. };
  67008. // Create a new vertex between this vertex and `other` by linearly
  67009. // interpolating all properties using a parameter of `t`. Subclasses should
  67010. // override this to interpolate additional properties.
  67011. Vertex.prototype.interpolate = function (other, t) {
  67012. 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));
  67013. };
  67014. return Vertex;
  67015. }());
  67016. // # class Plane
  67017. // Represents a plane in 3D space.
  67018. var Plane = /** @class */ (function () {
  67019. function Plane(normal, w) {
  67020. this.normal = normal;
  67021. this.w = w;
  67022. }
  67023. Plane.FromPoints = function (a, b, c) {
  67024. var v0 = c.subtract(a);
  67025. var v1 = b.subtract(a);
  67026. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  67027. return null;
  67028. }
  67029. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  67030. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  67031. };
  67032. Plane.prototype.clone = function () {
  67033. return new Plane(this.normal.clone(), this.w);
  67034. };
  67035. Plane.prototype.flip = function () {
  67036. this.normal.scaleInPlace(-1);
  67037. this.w = -this.w;
  67038. };
  67039. // Split `polygon` by this plane if needed, then put the polygon or polygon
  67040. // fragments in the appropriate lists. Coplanar polygons go into either
  67041. // `coplanarFront` or `coplanarBack` depending on their orientation with
  67042. // respect to this plane. Polygons in front or in back of this plane go into
  67043. // either `front` or `back`.
  67044. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  67045. var COPLANAR = 0;
  67046. var FRONT = 1;
  67047. var BACK = 2;
  67048. var SPANNING = 3;
  67049. // Classify each point as well as the entire polygon into one of the above
  67050. // four classes.
  67051. var polygonType = 0;
  67052. var types = [];
  67053. var i;
  67054. var t;
  67055. for (i = 0; i < polygon.vertices.length; i++) {
  67056. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  67057. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  67058. polygonType |= type;
  67059. types.push(type);
  67060. }
  67061. // Put the polygon in the correct list, splitting it when necessary.
  67062. switch (polygonType) {
  67063. case COPLANAR:
  67064. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  67065. break;
  67066. case FRONT:
  67067. front.push(polygon);
  67068. break;
  67069. case BACK:
  67070. back.push(polygon);
  67071. break;
  67072. case SPANNING:
  67073. var f = [], b = [];
  67074. for (i = 0; i < polygon.vertices.length; i++) {
  67075. var j = (i + 1) % polygon.vertices.length;
  67076. var ti = types[i], tj = types[j];
  67077. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  67078. if (ti !== BACK)
  67079. f.push(vi);
  67080. if (ti !== FRONT)
  67081. b.push(ti !== BACK ? vi.clone() : vi);
  67082. if ((ti | tj) === SPANNING) {
  67083. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  67084. var v = vi.interpolate(vj, t);
  67085. f.push(v);
  67086. b.push(v.clone());
  67087. }
  67088. }
  67089. var poly;
  67090. if (f.length >= 3) {
  67091. poly = new Polygon(f, polygon.shared);
  67092. if (poly.plane)
  67093. front.push(poly);
  67094. }
  67095. if (b.length >= 3) {
  67096. poly = new Polygon(b, polygon.shared);
  67097. if (poly.plane)
  67098. back.push(poly);
  67099. }
  67100. break;
  67101. }
  67102. };
  67103. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  67104. // point is on the plane.
  67105. Plane.EPSILON = 1e-5;
  67106. return Plane;
  67107. }());
  67108. // # class Polygon
  67109. // Represents a convex polygon. The vertices used to initialize a polygon must
  67110. // be coplanar and form a convex loop.
  67111. //
  67112. // Each convex polygon has a `shared` property, which is shared between all
  67113. // polygons that are clones of each other or were split from the same polygon.
  67114. // This can be used to define per-polygon properties (such as surface color).
  67115. var Polygon = /** @class */ (function () {
  67116. function Polygon(vertices, shared) {
  67117. this.vertices = vertices;
  67118. this.shared = shared;
  67119. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  67120. }
  67121. Polygon.prototype.clone = function () {
  67122. var vertices = this.vertices.map(function (v) { return v.clone(); });
  67123. return new Polygon(vertices, this.shared);
  67124. };
  67125. Polygon.prototype.flip = function () {
  67126. this.vertices.reverse().map(function (v) { v.flip(); });
  67127. this.plane.flip();
  67128. };
  67129. return Polygon;
  67130. }());
  67131. // # class Node
  67132. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  67133. // by picking a polygon to split along. That polygon (and all other coplanar
  67134. // polygons) are added directly to that node and the other polygons are added to
  67135. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  67136. // no distinction between internal and leaf nodes.
  67137. var Node = /** @class */ (function () {
  67138. function Node(polygons) {
  67139. this.plane = null;
  67140. this.front = null;
  67141. this.back = null;
  67142. this.polygons = new Array();
  67143. if (polygons) {
  67144. this.build(polygons);
  67145. }
  67146. }
  67147. Node.prototype.clone = function () {
  67148. var node = new Node();
  67149. node.plane = this.plane && this.plane.clone();
  67150. node.front = this.front && this.front.clone();
  67151. node.back = this.back && this.back.clone();
  67152. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  67153. return node;
  67154. };
  67155. // Convert solid space to empty space and empty space to solid space.
  67156. Node.prototype.invert = function () {
  67157. for (var i = 0; i < this.polygons.length; i++) {
  67158. this.polygons[i].flip();
  67159. }
  67160. if (this.plane) {
  67161. this.plane.flip();
  67162. }
  67163. if (this.front) {
  67164. this.front.invert();
  67165. }
  67166. if (this.back) {
  67167. this.back.invert();
  67168. }
  67169. var temp = this.front;
  67170. this.front = this.back;
  67171. this.back = temp;
  67172. };
  67173. // Recursively remove all polygons in `polygons` that are inside this BSP
  67174. // tree.
  67175. Node.prototype.clipPolygons = function (polygons) {
  67176. if (!this.plane)
  67177. return polygons.slice();
  67178. var front = new Array(), back = new Array();
  67179. for (var i = 0; i < polygons.length; i++) {
  67180. this.plane.splitPolygon(polygons[i], front, back, front, back);
  67181. }
  67182. if (this.front) {
  67183. front = this.front.clipPolygons(front);
  67184. }
  67185. if (this.back) {
  67186. back = this.back.clipPolygons(back);
  67187. }
  67188. else {
  67189. back = [];
  67190. }
  67191. return front.concat(back);
  67192. };
  67193. // Remove all polygons in this BSP tree that are inside the other BSP tree
  67194. // `bsp`.
  67195. Node.prototype.clipTo = function (bsp) {
  67196. this.polygons = bsp.clipPolygons(this.polygons);
  67197. if (this.front)
  67198. this.front.clipTo(bsp);
  67199. if (this.back)
  67200. this.back.clipTo(bsp);
  67201. };
  67202. // Return a list of all polygons in this BSP tree.
  67203. Node.prototype.allPolygons = function () {
  67204. var polygons = this.polygons.slice();
  67205. if (this.front)
  67206. polygons = polygons.concat(this.front.allPolygons());
  67207. if (this.back)
  67208. polygons = polygons.concat(this.back.allPolygons());
  67209. return polygons;
  67210. };
  67211. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  67212. // new polygons are filtered down to the bottom of the tree and become new
  67213. // nodes there. Each set of polygons is partitioned using the first polygon
  67214. // (no heuristic is used to pick a good split).
  67215. Node.prototype.build = function (polygons) {
  67216. if (!polygons.length)
  67217. return;
  67218. if (!this.plane)
  67219. this.plane = polygons[0].plane.clone();
  67220. var front = new Array(), back = new Array();
  67221. for (var i = 0; i < polygons.length; i++) {
  67222. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  67223. }
  67224. if (front.length) {
  67225. if (!this.front)
  67226. this.front = new Node();
  67227. this.front.build(front);
  67228. }
  67229. if (back.length) {
  67230. if (!this.back)
  67231. this.back = new Node();
  67232. this.back.build(back);
  67233. }
  67234. };
  67235. return Node;
  67236. }());
  67237. var CSG = /** @class */ (function () {
  67238. function CSG() {
  67239. this.polygons = new Array();
  67240. }
  67241. // Convert BABYLON.Mesh to BABYLON.CSG
  67242. CSG.FromMesh = function (mesh) {
  67243. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  67244. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  67245. if (mesh instanceof BABYLON.Mesh) {
  67246. mesh.computeWorldMatrix(true);
  67247. matrix = mesh.getWorldMatrix();
  67248. meshPosition = mesh.position.clone();
  67249. meshRotation = mesh.rotation.clone();
  67250. if (mesh.rotationQuaternion) {
  67251. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  67252. }
  67253. meshScaling = mesh.scaling.clone();
  67254. }
  67255. else {
  67256. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  67257. }
  67258. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67259. var subMeshes = mesh.subMeshes;
  67260. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  67261. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  67262. vertices = [];
  67263. for (var j = 0; j < 3; j++) {
  67264. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  67265. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  67266. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  67267. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  67268. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  67269. vertex = new Vertex(position, normal, uv);
  67270. vertices.push(vertex);
  67271. }
  67272. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  67273. // To handle the case of degenerated triangle
  67274. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  67275. if (polygon.plane)
  67276. polygons.push(polygon);
  67277. }
  67278. }
  67279. var csg = CSG.FromPolygons(polygons);
  67280. csg.matrix = matrix;
  67281. csg.position = meshPosition;
  67282. csg.rotation = meshRotation;
  67283. csg.scaling = meshScaling;
  67284. csg.rotationQuaternion = meshRotationQuaternion;
  67285. currentCSGMeshId++;
  67286. return csg;
  67287. };
  67288. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  67289. CSG.FromPolygons = function (polygons) {
  67290. var csg = new CSG();
  67291. csg.polygons = polygons;
  67292. return csg;
  67293. };
  67294. CSG.prototype.clone = function () {
  67295. var csg = new CSG();
  67296. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  67297. csg.copyTransformAttributes(this);
  67298. return csg;
  67299. };
  67300. CSG.prototype.union = function (csg) {
  67301. var a = new Node(this.clone().polygons);
  67302. var b = new Node(csg.clone().polygons);
  67303. a.clipTo(b);
  67304. b.clipTo(a);
  67305. b.invert();
  67306. b.clipTo(a);
  67307. b.invert();
  67308. a.build(b.allPolygons());
  67309. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67310. };
  67311. CSG.prototype.unionInPlace = function (csg) {
  67312. var a = new Node(this.polygons);
  67313. var b = new Node(csg.polygons);
  67314. a.clipTo(b);
  67315. b.clipTo(a);
  67316. b.invert();
  67317. b.clipTo(a);
  67318. b.invert();
  67319. a.build(b.allPolygons());
  67320. this.polygons = a.allPolygons();
  67321. };
  67322. CSG.prototype.subtract = function (csg) {
  67323. var a = new Node(this.clone().polygons);
  67324. var b = new Node(csg.clone().polygons);
  67325. a.invert();
  67326. a.clipTo(b);
  67327. b.clipTo(a);
  67328. b.invert();
  67329. b.clipTo(a);
  67330. b.invert();
  67331. a.build(b.allPolygons());
  67332. a.invert();
  67333. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67334. };
  67335. CSG.prototype.subtractInPlace = function (csg) {
  67336. var a = new Node(this.polygons);
  67337. var b = new Node(csg.polygons);
  67338. a.invert();
  67339. a.clipTo(b);
  67340. b.clipTo(a);
  67341. b.invert();
  67342. b.clipTo(a);
  67343. b.invert();
  67344. a.build(b.allPolygons());
  67345. a.invert();
  67346. this.polygons = a.allPolygons();
  67347. };
  67348. CSG.prototype.intersect = function (csg) {
  67349. var a = new Node(this.clone().polygons);
  67350. var b = new Node(csg.clone().polygons);
  67351. a.invert();
  67352. b.clipTo(a);
  67353. b.invert();
  67354. a.clipTo(b);
  67355. b.clipTo(a);
  67356. a.build(b.allPolygons());
  67357. a.invert();
  67358. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  67359. };
  67360. CSG.prototype.intersectInPlace = function (csg) {
  67361. var a = new Node(this.polygons);
  67362. var b = new Node(csg.polygons);
  67363. a.invert();
  67364. b.clipTo(a);
  67365. b.invert();
  67366. a.clipTo(b);
  67367. b.clipTo(a);
  67368. a.build(b.allPolygons());
  67369. a.invert();
  67370. this.polygons = a.allPolygons();
  67371. };
  67372. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  67373. // not modified.
  67374. CSG.prototype.inverse = function () {
  67375. var csg = this.clone();
  67376. csg.inverseInPlace();
  67377. return csg;
  67378. };
  67379. CSG.prototype.inverseInPlace = function () {
  67380. this.polygons.map(function (p) { p.flip(); });
  67381. };
  67382. // This is used to keep meshes transformations so they can be restored
  67383. // when we build back a Babylon Mesh
  67384. // NB : All CSG operations are performed in world coordinates
  67385. CSG.prototype.copyTransformAttributes = function (csg) {
  67386. this.matrix = csg.matrix;
  67387. this.position = csg.position;
  67388. this.rotation = csg.rotation;
  67389. this.scaling = csg.scaling;
  67390. this.rotationQuaternion = csg.rotationQuaternion;
  67391. return this;
  67392. };
  67393. // Build Raw mesh from CSG
  67394. // Coordinates here are in world space
  67395. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  67396. var matrix = this.matrix.clone();
  67397. matrix.invert();
  67398. 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;
  67399. if (keepSubMeshes) {
  67400. // Sort Polygons, since subMeshes are indices range
  67401. polygons.sort(function (a, b) {
  67402. if (a.shared.meshId === b.shared.meshId) {
  67403. return a.shared.subMeshId - b.shared.subMeshId;
  67404. }
  67405. else {
  67406. return a.shared.meshId - b.shared.meshId;
  67407. }
  67408. });
  67409. }
  67410. for (var i = 0, il = polygons.length; i < il; i++) {
  67411. polygon = polygons[i];
  67412. // Building SubMeshes
  67413. if (!subMesh_dict[polygon.shared.meshId]) {
  67414. subMesh_dict[polygon.shared.meshId] = {};
  67415. }
  67416. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  67417. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  67418. indexStart: +Infinity,
  67419. indexEnd: -Infinity,
  67420. materialIndex: polygon.shared.materialIndex
  67421. };
  67422. }
  67423. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  67424. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  67425. polygonIndices[0] = 0;
  67426. polygonIndices[1] = j - 1;
  67427. polygonIndices[2] = j;
  67428. for (var k = 0; k < 3; k++) {
  67429. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  67430. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  67431. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  67432. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  67433. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  67434. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  67435. // Check if 2 points can be merged
  67436. if (!(typeof vertex_idx !== 'undefined' &&
  67437. normals[vertex_idx * 3] === localNormal.x &&
  67438. normals[vertex_idx * 3 + 1] === localNormal.y &&
  67439. normals[vertex_idx * 3 + 2] === localNormal.z &&
  67440. uvs[vertex_idx * 2] === uv.x &&
  67441. uvs[vertex_idx * 2 + 1] === uv.y)) {
  67442. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  67443. uvs.push(uv.x, uv.y);
  67444. normals.push(normal.x, normal.y, normal.z);
  67445. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  67446. }
  67447. indices.push(vertex_idx);
  67448. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  67449. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  67450. currentIndex++;
  67451. }
  67452. }
  67453. }
  67454. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  67455. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  67456. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  67457. mesh.setIndices(indices, null);
  67458. if (keepSubMeshes) {
  67459. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  67460. var materialIndexOffset = 0, materialMaxIndex;
  67461. mesh.subMeshes = new Array();
  67462. for (var m in subMesh_dict) {
  67463. materialMaxIndex = -1;
  67464. for (var sm in subMesh_dict[m]) {
  67465. subMesh_obj = subMesh_dict[m][sm];
  67466. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  67467. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  67468. }
  67469. materialIndexOffset += ++materialMaxIndex;
  67470. }
  67471. }
  67472. return mesh;
  67473. };
  67474. // Build Mesh from CSG taking material and transforms into account
  67475. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  67476. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  67477. mesh.material = material;
  67478. mesh.position.copyFrom(this.position);
  67479. mesh.rotation.copyFrom(this.rotation);
  67480. if (this.rotationQuaternion) {
  67481. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  67482. }
  67483. mesh.scaling.copyFrom(this.scaling);
  67484. mesh.computeWorldMatrix(true);
  67485. return mesh;
  67486. };
  67487. return CSG;
  67488. }());
  67489. BABYLON.CSG = CSG;
  67490. })(BABYLON || (BABYLON = {}));
  67491. //# sourceMappingURL=babylon.csg.js.map
  67492. var BABYLON;
  67493. (function (BABYLON) {
  67494. var LensFlare = /** @class */ (function () {
  67495. function LensFlare(size, position, color, imgUrl, system) {
  67496. this.size = size;
  67497. this.position = position;
  67498. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  67499. this.color = color || new BABYLON.Color3(1, 1, 1);
  67500. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  67501. this._system = system;
  67502. system.lensFlares.push(this);
  67503. }
  67504. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  67505. return new LensFlare(size, position, color, imgUrl, system);
  67506. };
  67507. LensFlare.prototype.dispose = function () {
  67508. if (this.texture) {
  67509. this.texture.dispose();
  67510. }
  67511. // Remove from scene
  67512. var index = this._system.lensFlares.indexOf(this);
  67513. this._system.lensFlares.splice(index, 1);
  67514. };
  67515. ;
  67516. return LensFlare;
  67517. }());
  67518. BABYLON.LensFlare = LensFlare;
  67519. })(BABYLON || (BABYLON = {}));
  67520. //# sourceMappingURL=babylon.lensFlare.js.map
  67521. var BABYLON;
  67522. (function (BABYLON) {
  67523. var LensFlareSystem = /** @class */ (function () {
  67524. function LensFlareSystem(name, emitter, scene) {
  67525. this.name = name;
  67526. this.lensFlares = new Array();
  67527. this.borderLimit = 300;
  67528. this.viewportBorder = 0;
  67529. this.layerMask = 0x0FFFFFFF;
  67530. this._vertexBuffers = {};
  67531. this._isEnabled = true;
  67532. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67533. this._emitter = emitter;
  67534. this.id = name;
  67535. scene.lensFlareSystems.push(this);
  67536. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  67537. var engine = scene.getEngine();
  67538. // VBO
  67539. var vertices = [];
  67540. vertices.push(1, 1);
  67541. vertices.push(-1, 1);
  67542. vertices.push(-1, -1);
  67543. vertices.push(1, -1);
  67544. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67545. // Indices
  67546. var indices = [];
  67547. indices.push(0);
  67548. indices.push(1);
  67549. indices.push(2);
  67550. indices.push(0);
  67551. indices.push(2);
  67552. indices.push(3);
  67553. this._indexBuffer = engine.createIndexBuffer(indices);
  67554. // Effects
  67555. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  67556. }
  67557. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  67558. get: function () {
  67559. return this._isEnabled;
  67560. },
  67561. set: function (value) {
  67562. this._isEnabled = value;
  67563. },
  67564. enumerable: true,
  67565. configurable: true
  67566. });
  67567. LensFlareSystem.prototype.getScene = function () {
  67568. return this._scene;
  67569. };
  67570. LensFlareSystem.prototype.getEmitter = function () {
  67571. return this._emitter;
  67572. };
  67573. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  67574. this._emitter = newEmitter;
  67575. };
  67576. LensFlareSystem.prototype.getEmitterPosition = function () {
  67577. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  67578. };
  67579. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  67580. var position = this.getEmitterPosition();
  67581. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  67582. this._positionX = position.x;
  67583. this._positionY = position.y;
  67584. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  67585. if (this.viewportBorder > 0) {
  67586. globalViewport.x -= this.viewportBorder;
  67587. globalViewport.y -= this.viewportBorder;
  67588. globalViewport.width += this.viewportBorder * 2;
  67589. globalViewport.height += this.viewportBorder * 2;
  67590. position.x += this.viewportBorder;
  67591. position.y += this.viewportBorder;
  67592. this._positionX += this.viewportBorder;
  67593. this._positionY += this.viewportBorder;
  67594. }
  67595. if (position.z > 0) {
  67596. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  67597. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  67598. return true;
  67599. }
  67600. return true;
  67601. }
  67602. return false;
  67603. };
  67604. LensFlareSystem.prototype._isVisible = function () {
  67605. if (!this._isEnabled || !this._scene.activeCamera) {
  67606. return false;
  67607. }
  67608. var emitterPosition = this.getEmitterPosition();
  67609. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  67610. var distance = direction.length();
  67611. direction.normalize();
  67612. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  67613. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  67614. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  67615. };
  67616. LensFlareSystem.prototype.render = function () {
  67617. if (!this._effect.isReady() || !this._scene.activeCamera)
  67618. return false;
  67619. var engine = this._scene.getEngine();
  67620. var viewport = this._scene.activeCamera.viewport;
  67621. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  67622. // Position
  67623. if (!this.computeEffectivePosition(globalViewport)) {
  67624. return false;
  67625. }
  67626. // Visibility
  67627. if (!this._isVisible()) {
  67628. return false;
  67629. }
  67630. // Intensity
  67631. var awayX;
  67632. var awayY;
  67633. if (this._positionX < this.borderLimit + globalViewport.x) {
  67634. awayX = this.borderLimit + globalViewport.x - this._positionX;
  67635. }
  67636. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  67637. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  67638. }
  67639. else {
  67640. awayX = 0;
  67641. }
  67642. if (this._positionY < this.borderLimit + globalViewport.y) {
  67643. awayY = this.borderLimit + globalViewport.y - this._positionY;
  67644. }
  67645. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  67646. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  67647. }
  67648. else {
  67649. awayY = 0;
  67650. }
  67651. var away = (awayX > awayY) ? awayX : awayY;
  67652. away -= this.viewportBorder;
  67653. if (away > this.borderLimit) {
  67654. away = this.borderLimit;
  67655. }
  67656. var intensity = 1.0 - (away / this.borderLimit);
  67657. if (intensity < 0) {
  67658. return false;
  67659. }
  67660. if (intensity > 1.0) {
  67661. intensity = 1.0;
  67662. }
  67663. if (this.viewportBorder > 0) {
  67664. globalViewport.x += this.viewportBorder;
  67665. globalViewport.y += this.viewportBorder;
  67666. globalViewport.width -= this.viewportBorder * 2;
  67667. globalViewport.height -= this.viewportBorder * 2;
  67668. this._positionX -= this.viewportBorder;
  67669. this._positionY -= this.viewportBorder;
  67670. }
  67671. // Position
  67672. var centerX = globalViewport.x + globalViewport.width / 2;
  67673. var centerY = globalViewport.y + globalViewport.height / 2;
  67674. var distX = centerX - this._positionX;
  67675. var distY = centerY - this._positionY;
  67676. // Effects
  67677. engine.enableEffect(this._effect);
  67678. engine.setState(false);
  67679. engine.setDepthBuffer(false);
  67680. // VBOs
  67681. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  67682. // Flares
  67683. for (var index = 0; index < this.lensFlares.length; index++) {
  67684. var flare = this.lensFlares[index];
  67685. engine.setAlphaMode(flare.alphaMode);
  67686. var x = centerX - (distX * flare.position);
  67687. var y = centerY - (distY * flare.position);
  67688. var cw = flare.size;
  67689. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  67690. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  67691. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  67692. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  67693. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  67694. // Texture
  67695. this._effect.setTexture("textureSampler", flare.texture);
  67696. // Color
  67697. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67698. // Draw order
  67699. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67700. }
  67701. engine.setDepthBuffer(true);
  67702. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67703. return true;
  67704. };
  67705. LensFlareSystem.prototype.dispose = function () {
  67706. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67707. if (vertexBuffer) {
  67708. vertexBuffer.dispose();
  67709. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67710. }
  67711. if (this._indexBuffer) {
  67712. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67713. this._indexBuffer = null;
  67714. }
  67715. while (this.lensFlares.length) {
  67716. this.lensFlares[0].dispose();
  67717. }
  67718. // Remove from scene
  67719. var index = this._scene.lensFlareSystems.indexOf(this);
  67720. this._scene.lensFlareSystems.splice(index, 1);
  67721. };
  67722. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67723. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67724. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67725. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67726. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67727. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67728. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67729. var parsedFlare = parsedLensFlareSystem.flares[index];
  67730. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67731. }
  67732. return lensFlareSystem;
  67733. };
  67734. LensFlareSystem.prototype.serialize = function () {
  67735. var serializationObject = {};
  67736. serializationObject.id = this.id;
  67737. serializationObject.name = this.name;
  67738. serializationObject.emitterId = this.getEmitter().id;
  67739. serializationObject.borderLimit = this.borderLimit;
  67740. serializationObject.flares = [];
  67741. for (var index = 0; index < this.lensFlares.length; index++) {
  67742. var flare = this.lensFlares[index];
  67743. serializationObject.flares.push({
  67744. size: flare.size,
  67745. position: flare.position,
  67746. color: flare.color.asArray(),
  67747. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67748. });
  67749. }
  67750. return serializationObject;
  67751. };
  67752. return LensFlareSystem;
  67753. }());
  67754. BABYLON.LensFlareSystem = LensFlareSystem;
  67755. })(BABYLON || (BABYLON = {}));
  67756. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67757. var BABYLON;
  67758. (function (BABYLON) {
  67759. /**
  67760. * This is a holder class for the physics joint created by the physics plugin.
  67761. * It holds a set of functions to control the underlying joint.
  67762. */
  67763. var PhysicsJoint = /** @class */ (function () {
  67764. function PhysicsJoint(type, jointData) {
  67765. this.type = type;
  67766. this.jointData = jointData;
  67767. jointData.nativeParams = jointData.nativeParams || {};
  67768. }
  67769. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67770. get: function () {
  67771. return this._physicsJoint;
  67772. },
  67773. set: function (newJoint) {
  67774. if (this._physicsJoint) {
  67775. //remove from the wolrd
  67776. }
  67777. this._physicsJoint = newJoint;
  67778. },
  67779. enumerable: true,
  67780. configurable: true
  67781. });
  67782. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67783. set: function (physicsPlugin) {
  67784. this._physicsPlugin = physicsPlugin;
  67785. },
  67786. enumerable: true,
  67787. configurable: true
  67788. });
  67789. /**
  67790. * Execute a function that is physics-plugin specific.
  67791. * @param {Function} func the function that will be executed.
  67792. * It accepts two parameters: the physics world and the physics joint.
  67793. */
  67794. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67795. func(this._physicsPlugin.world, this._physicsJoint);
  67796. };
  67797. //TODO check if the native joints are the same
  67798. //Joint Types
  67799. PhysicsJoint.DistanceJoint = 0;
  67800. PhysicsJoint.HingeJoint = 1;
  67801. PhysicsJoint.BallAndSocketJoint = 2;
  67802. PhysicsJoint.WheelJoint = 3;
  67803. PhysicsJoint.SliderJoint = 4;
  67804. //OIMO
  67805. PhysicsJoint.PrismaticJoint = 5;
  67806. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67807. PhysicsJoint.UniversalJoint = 6;
  67808. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67809. //Cannon
  67810. //Similar to a Ball-Joint. Different in params
  67811. PhysicsJoint.PointToPointJoint = 8;
  67812. //Cannon only at the moment
  67813. PhysicsJoint.SpringJoint = 9;
  67814. PhysicsJoint.LockJoint = 10;
  67815. return PhysicsJoint;
  67816. }());
  67817. BABYLON.PhysicsJoint = PhysicsJoint;
  67818. /**
  67819. * A class representing a physics distance joint.
  67820. */
  67821. var DistanceJoint = /** @class */ (function (_super) {
  67822. __extends(DistanceJoint, _super);
  67823. function DistanceJoint(jointData) {
  67824. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67825. }
  67826. /**
  67827. * Update the predefined distance.
  67828. */
  67829. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67830. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67831. };
  67832. return DistanceJoint;
  67833. }(PhysicsJoint));
  67834. BABYLON.DistanceJoint = DistanceJoint;
  67835. var MotorEnabledJoint = /** @class */ (function (_super) {
  67836. __extends(MotorEnabledJoint, _super);
  67837. function MotorEnabledJoint(type, jointData) {
  67838. return _super.call(this, type, jointData) || this;
  67839. }
  67840. /**
  67841. * Set the motor values.
  67842. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67843. * @param {number} force the force to apply
  67844. * @param {number} maxForce max force for this motor.
  67845. */
  67846. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  67847. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67848. };
  67849. /**
  67850. * Set the motor's limits.
  67851. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67852. */
  67853. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67854. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67855. };
  67856. return MotorEnabledJoint;
  67857. }(PhysicsJoint));
  67858. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  67859. /**
  67860. * This class represents a single hinge physics joint
  67861. */
  67862. var HingeJoint = /** @class */ (function (_super) {
  67863. __extends(HingeJoint, _super);
  67864. function HingeJoint(jointData) {
  67865. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  67866. }
  67867. /**
  67868. * Set the motor values.
  67869. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67870. * @param {number} force the force to apply
  67871. * @param {number} maxForce max force for this motor.
  67872. */
  67873. HingeJoint.prototype.setMotor = function (force, maxForce) {
  67874. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67875. };
  67876. /**
  67877. * Set the motor's limits.
  67878. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67879. */
  67880. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67881. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67882. };
  67883. return HingeJoint;
  67884. }(MotorEnabledJoint));
  67885. BABYLON.HingeJoint = HingeJoint;
  67886. /**
  67887. * This class represents a dual hinge physics joint (same as wheel joint)
  67888. */
  67889. var Hinge2Joint = /** @class */ (function (_super) {
  67890. __extends(Hinge2Joint, _super);
  67891. function Hinge2Joint(jointData) {
  67892. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  67893. }
  67894. /**
  67895. * Set the motor values.
  67896. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67897. * @param {number} force the force to apply
  67898. * @param {number} maxForce max force for this motor.
  67899. * @param {motorIndex} the motor's index, 0 or 1.
  67900. */
  67901. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  67902. if (motorIndex === void 0) { motorIndex = 0; }
  67903. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  67904. };
  67905. /**
  67906. * Set the motor limits.
  67907. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67908. * @param {number} upperLimit the upper limit
  67909. * @param {number} lowerLimit lower limit
  67910. * @param {motorIndex} the motor's index, 0 or 1.
  67911. */
  67912. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  67913. if (motorIndex === void 0) { motorIndex = 0; }
  67914. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  67915. };
  67916. return Hinge2Joint;
  67917. }(MotorEnabledJoint));
  67918. BABYLON.Hinge2Joint = Hinge2Joint;
  67919. })(BABYLON || (BABYLON = {}));
  67920. //# sourceMappingURL=babylon.physicsJoint.js.map
  67921. var BABYLON;
  67922. (function (BABYLON) {
  67923. var PhysicsImpostor = /** @class */ (function () {
  67924. function PhysicsImpostor(object, type, _options, _scene) {
  67925. if (_options === void 0) { _options = { mass: 0 }; }
  67926. var _this = this;
  67927. this.object = object;
  67928. this.type = type;
  67929. this._options = _options;
  67930. this._scene = _scene;
  67931. this._bodyUpdateRequired = false;
  67932. this._onBeforePhysicsStepCallbacks = new Array();
  67933. this._onAfterPhysicsStepCallbacks = new Array();
  67934. this._onPhysicsCollideCallbacks = [];
  67935. this._deltaPosition = BABYLON.Vector3.Zero();
  67936. this._isDisposed = false;
  67937. //temp variables for parent rotation calculations
  67938. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  67939. this._tmpQuat = new BABYLON.Quaternion();
  67940. this._tmpQuat2 = new BABYLON.Quaternion();
  67941. /**
  67942. * this function is executed by the physics engine.
  67943. */
  67944. this.beforeStep = function () {
  67945. if (!_this._physicsEngine) {
  67946. return;
  67947. }
  67948. _this.object.translate(_this._deltaPosition, -1);
  67949. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  67950. _this.object.computeWorldMatrix(false);
  67951. if (_this.object.parent && _this.object.rotationQuaternion) {
  67952. _this.getParentsRotation();
  67953. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  67954. }
  67955. else {
  67956. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  67957. }
  67958. if (!_this._options.disableBidirectionalTransformation) {
  67959. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  67960. }
  67961. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  67962. func(_this);
  67963. });
  67964. };
  67965. /**
  67966. * this function is executed by the physics engine.
  67967. */
  67968. this.afterStep = function () {
  67969. if (!_this._physicsEngine) {
  67970. return;
  67971. }
  67972. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  67973. func(_this);
  67974. });
  67975. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  67976. // object has now its world rotation. needs to be converted to local.
  67977. if (_this.object.parent && _this.object.rotationQuaternion) {
  67978. _this.getParentsRotation();
  67979. _this._tmpQuat.conjugateInPlace();
  67980. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  67981. }
  67982. // take the position set and make it the absolute position of this object.
  67983. _this.object.setAbsolutePosition(_this.object.position);
  67984. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  67985. _this.object.translate(_this._deltaPosition, 1);
  67986. };
  67987. /**
  67988. * Legacy collision detection event support
  67989. */
  67990. this.onCollideEvent = null;
  67991. //event and body object due to cannon's event-based architecture.
  67992. this.onCollide = function (e) {
  67993. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  67994. return;
  67995. }
  67996. if (!_this._physicsEngine) {
  67997. return;
  67998. }
  67999. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  68000. if (otherImpostor) {
  68001. // Legacy collision detection event support
  68002. if (_this.onCollideEvent) {
  68003. _this.onCollideEvent(_this, otherImpostor);
  68004. }
  68005. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  68006. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  68007. }).forEach(function (obj) {
  68008. obj.callback(_this, otherImpostor);
  68009. });
  68010. }
  68011. };
  68012. //sanity check!
  68013. if (!this.object) {
  68014. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  68015. return;
  68016. }
  68017. //legacy support for old syntax.
  68018. if (!this._scene && object.getScene) {
  68019. this._scene = object.getScene();
  68020. }
  68021. if (!this._scene) {
  68022. return;
  68023. }
  68024. this._physicsEngine = this._scene.getPhysicsEngine();
  68025. if (!this._physicsEngine) {
  68026. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  68027. }
  68028. else {
  68029. //set the object's quaternion, if not set
  68030. if (!this.object.rotationQuaternion) {
  68031. if (this.object.rotation) {
  68032. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  68033. }
  68034. else {
  68035. this.object.rotationQuaternion = new BABYLON.Quaternion();
  68036. }
  68037. }
  68038. //default options params
  68039. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  68040. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  68041. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  68042. this._joints = [];
  68043. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  68044. if (!this.object.parent || this._options.ignoreParent) {
  68045. this._init();
  68046. }
  68047. else if (this.object.parent.physicsImpostor) {
  68048. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  68049. }
  68050. }
  68051. }
  68052. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  68053. get: function () {
  68054. return this._isDisposed;
  68055. },
  68056. enumerable: true,
  68057. configurable: true
  68058. });
  68059. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  68060. get: function () {
  68061. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  68062. },
  68063. set: function (value) {
  68064. this.setMass(value);
  68065. },
  68066. enumerable: true,
  68067. configurable: true
  68068. });
  68069. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  68070. get: function () {
  68071. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  68072. },
  68073. set: function (value) {
  68074. if (!this._physicsEngine) {
  68075. return;
  68076. }
  68077. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  68078. },
  68079. enumerable: true,
  68080. configurable: true
  68081. });
  68082. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  68083. get: function () {
  68084. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  68085. },
  68086. set: function (value) {
  68087. if (!this._physicsEngine) {
  68088. return;
  68089. }
  68090. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  68091. },
  68092. enumerable: true,
  68093. configurable: true
  68094. });
  68095. /**
  68096. * This function will completly initialize this impostor.
  68097. * It will create a new body - but only if this mesh has no parent.
  68098. * If it has, this impostor will not be used other than to define the impostor
  68099. * of the child mesh.
  68100. */
  68101. PhysicsImpostor.prototype._init = function () {
  68102. if (!this._physicsEngine) {
  68103. return;
  68104. }
  68105. this._physicsEngine.removeImpostor(this);
  68106. this.physicsBody = null;
  68107. this._parent = this._parent || this._getPhysicsParent();
  68108. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  68109. this._physicsEngine.addImpostor(this);
  68110. }
  68111. };
  68112. PhysicsImpostor.prototype._getPhysicsParent = function () {
  68113. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  68114. var parentMesh = this.object.parent;
  68115. return parentMesh.physicsImpostor;
  68116. }
  68117. return null;
  68118. };
  68119. /**
  68120. * Should a new body be generated.
  68121. */
  68122. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  68123. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  68124. };
  68125. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  68126. this.forceUpdate();
  68127. };
  68128. /**
  68129. * Force a regeneration of this or the parent's impostor's body.
  68130. * Use under cautious - This will remove all joints already implemented.
  68131. */
  68132. PhysicsImpostor.prototype.forceUpdate = function () {
  68133. this._init();
  68134. if (this.parent && !this._options.ignoreParent) {
  68135. this.parent.forceUpdate();
  68136. }
  68137. };
  68138. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  68139. /*public get mesh(): AbstractMesh {
  68140. return this._mesh;
  68141. }*/
  68142. /**
  68143. * Gets the body that holds this impostor. Either its own, or its parent.
  68144. */
  68145. get: function () {
  68146. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  68147. },
  68148. /**
  68149. * Set the physics body. Used mainly by the physics engine/plugin
  68150. */
  68151. set: function (physicsBody) {
  68152. if (this._physicsBody && this._physicsEngine) {
  68153. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  68154. }
  68155. this._physicsBody = physicsBody;
  68156. this.resetUpdateFlags();
  68157. },
  68158. enumerable: true,
  68159. configurable: true
  68160. });
  68161. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  68162. get: function () {
  68163. return !this._options.ignoreParent && this._parent ? this._parent : null;
  68164. },
  68165. set: function (value) {
  68166. this._parent = value;
  68167. },
  68168. enumerable: true,
  68169. configurable: true
  68170. });
  68171. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  68172. this._bodyUpdateRequired = false;
  68173. };
  68174. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  68175. if (this.object.getBoundingInfo) {
  68176. var q = this.object.rotationQuaternion;
  68177. //reset rotation
  68178. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  68179. //calculate the world matrix with no rotation
  68180. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68181. var boundingInfo = this.object.getBoundingInfo();
  68182. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  68183. //bring back the rotation
  68184. this.object.rotationQuaternion = q;
  68185. //calculate the world matrix with the new rotation
  68186. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  68187. return size;
  68188. }
  68189. else {
  68190. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  68191. }
  68192. };
  68193. PhysicsImpostor.prototype.getObjectCenter = function () {
  68194. if (this.object.getBoundingInfo) {
  68195. var boundingInfo = this.object.getBoundingInfo();
  68196. return boundingInfo.boundingBox.centerWorld;
  68197. }
  68198. else {
  68199. return this.object.position;
  68200. }
  68201. };
  68202. /**
  68203. * Get a specific parametes from the options parameter.
  68204. */
  68205. PhysicsImpostor.prototype.getParam = function (paramName) {
  68206. return this._options[paramName];
  68207. };
  68208. /**
  68209. * Sets a specific parameter in the options given to the physics plugin
  68210. */
  68211. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  68212. this._options[paramName] = value;
  68213. this._bodyUpdateRequired = true;
  68214. };
  68215. /**
  68216. * Specifically change the body's mass option. Won't recreate the physics body object
  68217. */
  68218. PhysicsImpostor.prototype.setMass = function (mass) {
  68219. if (this.getParam("mass") !== mass) {
  68220. this.setParam("mass", mass);
  68221. }
  68222. if (this._physicsEngine) {
  68223. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  68224. }
  68225. };
  68226. PhysicsImpostor.prototype.getLinearVelocity = function () {
  68227. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  68228. };
  68229. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  68230. if (this._physicsEngine) {
  68231. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  68232. }
  68233. };
  68234. PhysicsImpostor.prototype.getAngularVelocity = function () {
  68235. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  68236. };
  68237. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  68238. if (this._physicsEngine) {
  68239. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  68240. }
  68241. };
  68242. /**
  68243. * Execute a function with the physics plugin native code.
  68244. * Provide a function the will have two variables - the world object and the physics body object.
  68245. */
  68246. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  68247. if (this._physicsEngine) {
  68248. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  68249. }
  68250. };
  68251. /**
  68252. * Register a function that will be executed before the physics world is stepping forward.
  68253. */
  68254. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  68255. this._onBeforePhysicsStepCallbacks.push(func);
  68256. };
  68257. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  68258. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  68259. if (index > -1) {
  68260. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  68261. }
  68262. else {
  68263. BABYLON.Tools.Warn("Function to remove was not found");
  68264. }
  68265. };
  68266. /**
  68267. * Register a function that will be executed after the physics step
  68268. */
  68269. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  68270. this._onAfterPhysicsStepCallbacks.push(func);
  68271. };
  68272. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  68273. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  68274. if (index > -1) {
  68275. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  68276. }
  68277. else {
  68278. BABYLON.Tools.Warn("Function to remove was not found");
  68279. }
  68280. };
  68281. /**
  68282. * register a function that will be executed when this impostor collides against a different body.
  68283. */
  68284. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  68285. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68286. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  68287. };
  68288. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  68289. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  68290. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  68291. if (index > -1) {
  68292. this._onPhysicsCollideCallbacks.splice(index, 1);
  68293. }
  68294. else {
  68295. BABYLON.Tools.Warn("Function to remove was not found");
  68296. }
  68297. };
  68298. PhysicsImpostor.prototype.getParentsRotation = function () {
  68299. var parent = this.object.parent;
  68300. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  68301. while (parent) {
  68302. if (parent.rotationQuaternion) {
  68303. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  68304. }
  68305. else {
  68306. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  68307. }
  68308. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  68309. parent = parent.parent;
  68310. }
  68311. return this._tmpQuat;
  68312. };
  68313. /**
  68314. * Apply a force
  68315. */
  68316. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  68317. if (this._physicsEngine) {
  68318. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  68319. }
  68320. return this;
  68321. };
  68322. /**
  68323. * Apply an impulse
  68324. */
  68325. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  68326. if (this._physicsEngine) {
  68327. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  68328. }
  68329. return this;
  68330. };
  68331. /**
  68332. * A help function to create a joint.
  68333. */
  68334. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  68335. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  68336. this.addJoint(otherImpostor, joint);
  68337. return this;
  68338. };
  68339. /**
  68340. * Add a joint to this impostor with a different impostor.
  68341. */
  68342. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  68343. this._joints.push({
  68344. otherImpostor: otherImpostor,
  68345. joint: joint
  68346. });
  68347. if (this._physicsEngine) {
  68348. this._physicsEngine.addJoint(this, otherImpostor, joint);
  68349. }
  68350. return this;
  68351. };
  68352. /**
  68353. * Will keep this body still, in a sleep mode.
  68354. */
  68355. PhysicsImpostor.prototype.sleep = function () {
  68356. if (this._physicsEngine) {
  68357. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  68358. }
  68359. return this;
  68360. };
  68361. /**
  68362. * Wake the body up.
  68363. */
  68364. PhysicsImpostor.prototype.wakeUp = function () {
  68365. if (this._physicsEngine) {
  68366. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  68367. }
  68368. return this;
  68369. };
  68370. PhysicsImpostor.prototype.clone = function (newObject) {
  68371. if (!newObject)
  68372. return null;
  68373. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  68374. };
  68375. PhysicsImpostor.prototype.dispose = function () {
  68376. var _this = this;
  68377. //no dispose if no physics engine is available.
  68378. if (!this._physicsEngine) {
  68379. return;
  68380. }
  68381. this._joints.forEach(function (j) {
  68382. if (_this._physicsEngine) {
  68383. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  68384. }
  68385. });
  68386. //dispose the physics body
  68387. this._physicsEngine.removeImpostor(this);
  68388. if (this.parent) {
  68389. this.parent.forceUpdate();
  68390. }
  68391. else {
  68392. /*this._object.getChildMeshes().forEach(function(mesh) {
  68393. if (mesh.physicsImpostor) {
  68394. if (disposeChildren) {
  68395. mesh.physicsImpostor.dispose();
  68396. mesh.physicsImpostor = null;
  68397. }
  68398. }
  68399. })*/
  68400. }
  68401. this._isDisposed = true;
  68402. };
  68403. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  68404. this._deltaPosition.copyFrom(position);
  68405. };
  68406. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  68407. if (!this._deltaRotation) {
  68408. this._deltaRotation = new BABYLON.Quaternion();
  68409. }
  68410. this._deltaRotation.copyFrom(rotation);
  68411. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  68412. };
  68413. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  68414. if (this._physicsEngine) {
  68415. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  68416. }
  68417. return this;
  68418. };
  68419. PhysicsImpostor.prototype.getRadius = function () {
  68420. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  68421. };
  68422. /**
  68423. * Sync a bone with this impostor
  68424. * @param bone The bone to sync to the impostor.
  68425. * @param boneMesh The mesh that the bone is influencing.
  68426. * @param jointPivot The pivot of the joint / bone in local space.
  68427. * @param distToJoint Optional distance from the impostor to the joint.
  68428. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68429. */
  68430. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  68431. var tempVec = PhysicsImpostor._tmpVecs[0];
  68432. var mesh = this.object;
  68433. if (mesh.rotationQuaternion) {
  68434. if (adjustRotation) {
  68435. var tempQuat = PhysicsImpostor._tmpQuat;
  68436. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  68437. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  68438. }
  68439. else {
  68440. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  68441. }
  68442. }
  68443. tempVec.x = 0;
  68444. tempVec.y = 0;
  68445. tempVec.z = 0;
  68446. if (jointPivot) {
  68447. tempVec.x = jointPivot.x;
  68448. tempVec.y = jointPivot.y;
  68449. tempVec.z = jointPivot.z;
  68450. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  68451. if (distToJoint === undefined || distToJoint === null) {
  68452. distToJoint = jointPivot.length();
  68453. }
  68454. tempVec.x *= distToJoint;
  68455. tempVec.y *= distToJoint;
  68456. tempVec.z *= distToJoint;
  68457. }
  68458. if (bone.getParent()) {
  68459. tempVec.addInPlace(mesh.getAbsolutePosition());
  68460. bone.setAbsolutePosition(tempVec, boneMesh);
  68461. }
  68462. else {
  68463. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  68464. boneMesh.position.x -= tempVec.x;
  68465. boneMesh.position.y -= tempVec.y;
  68466. boneMesh.position.z -= tempVec.z;
  68467. }
  68468. };
  68469. /**
  68470. * Sync impostor to a bone
  68471. * @param bone The bone that the impostor will be synced to.
  68472. * @param boneMesh The mesh that the bone is influencing.
  68473. * @param jointPivot The pivot of the joint / bone in local space.
  68474. * @param distToJoint Optional distance from the impostor to the joint.
  68475. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  68476. * @param boneAxis Optional vector3 axis the bone is aligned with
  68477. */
  68478. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  68479. var mesh = this.object;
  68480. if (mesh.rotationQuaternion) {
  68481. if (adjustRotation) {
  68482. var tempQuat = PhysicsImpostor._tmpQuat;
  68483. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  68484. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  68485. }
  68486. else {
  68487. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  68488. }
  68489. }
  68490. var pos = PhysicsImpostor._tmpVecs[0];
  68491. var boneDir = PhysicsImpostor._tmpVecs[1];
  68492. if (!boneAxis) {
  68493. boneAxis = PhysicsImpostor._tmpVecs[2];
  68494. boneAxis.x = 0;
  68495. boneAxis.y = 1;
  68496. boneAxis.z = 0;
  68497. }
  68498. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  68499. bone.getAbsolutePositionToRef(boneMesh, pos);
  68500. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  68501. distToJoint = jointPivot.length();
  68502. }
  68503. if (distToJoint !== undefined && distToJoint !== null) {
  68504. pos.x += boneDir.x * distToJoint;
  68505. pos.y += boneDir.y * distToJoint;
  68506. pos.z += boneDir.z * distToJoint;
  68507. }
  68508. mesh.setAbsolutePosition(pos);
  68509. };
  68510. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  68511. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  68512. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  68513. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  68514. //Impostor types
  68515. PhysicsImpostor.NoImpostor = 0;
  68516. PhysicsImpostor.SphereImpostor = 1;
  68517. PhysicsImpostor.BoxImpostor = 2;
  68518. PhysicsImpostor.PlaneImpostor = 3;
  68519. PhysicsImpostor.MeshImpostor = 4;
  68520. PhysicsImpostor.CylinderImpostor = 7;
  68521. PhysicsImpostor.ParticleImpostor = 8;
  68522. PhysicsImpostor.HeightmapImpostor = 9;
  68523. return PhysicsImpostor;
  68524. }());
  68525. BABYLON.PhysicsImpostor = PhysicsImpostor;
  68526. })(BABYLON || (BABYLON = {}));
  68527. //# sourceMappingURL=babylon.physicsImpostor.js.map
  68528. var BABYLON;
  68529. (function (BABYLON) {
  68530. var PhysicsEngine = /** @class */ (function () {
  68531. function PhysicsEngine(gravity, _physicsPlugin) {
  68532. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  68533. this._physicsPlugin = _physicsPlugin;
  68534. //new methods and parameters
  68535. this._impostors = [];
  68536. this._joints = [];
  68537. if (!this._physicsPlugin.isSupported()) {
  68538. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  68539. + "Please make sure it is included.");
  68540. }
  68541. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  68542. this.setGravity(gravity);
  68543. this.setTimeStep();
  68544. }
  68545. PhysicsEngine.prototype.setGravity = function (gravity) {
  68546. this.gravity = gravity;
  68547. this._physicsPlugin.setGravity(this.gravity);
  68548. };
  68549. /**
  68550. * Set the time step of the physics engine.
  68551. * default is 1/60.
  68552. * To slow it down, enter 1/600 for example.
  68553. * To speed it up, 1/30
  68554. * @param {number} newTimeStep the new timestep to apply to this world.
  68555. */
  68556. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  68557. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  68558. this._physicsPlugin.setTimeStep(newTimeStep);
  68559. };
  68560. /**
  68561. * Get the time step of the physics engine.
  68562. */
  68563. PhysicsEngine.prototype.getTimeStep = function () {
  68564. return this._physicsPlugin.getTimeStep();
  68565. };
  68566. PhysicsEngine.prototype.dispose = function () {
  68567. this._impostors.forEach(function (impostor) {
  68568. impostor.dispose();
  68569. });
  68570. this._physicsPlugin.dispose();
  68571. };
  68572. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  68573. return this._physicsPlugin.name;
  68574. };
  68575. /**
  68576. * Adding a new impostor for the impostor tracking.
  68577. * This will be done by the impostor itself.
  68578. * @param {PhysicsImpostor} impostor the impostor to add
  68579. */
  68580. PhysicsEngine.prototype.addImpostor = function (impostor) {
  68581. impostor.uniqueId = this._impostors.push(impostor);
  68582. //if no parent, generate the body
  68583. if (!impostor.parent) {
  68584. this._physicsPlugin.generatePhysicsBody(impostor);
  68585. }
  68586. };
  68587. /**
  68588. * Remove an impostor from the engine.
  68589. * This impostor and its mesh will not longer be updated by the physics engine.
  68590. * @param {PhysicsImpostor} impostor the impostor to remove
  68591. */
  68592. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  68593. var index = this._impostors.indexOf(impostor);
  68594. if (index > -1) {
  68595. var removed = this._impostors.splice(index, 1);
  68596. //Is it needed?
  68597. if (removed.length) {
  68598. //this will also remove it from the world.
  68599. removed[0].physicsBody = null;
  68600. }
  68601. }
  68602. };
  68603. /**
  68604. * Add a joint to the physics engine
  68605. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  68606. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  68607. * @param {PhysicsJoint} the joint that will connect both impostors.
  68608. */
  68609. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  68610. var impostorJoint = {
  68611. mainImpostor: mainImpostor,
  68612. connectedImpostor: connectedImpostor,
  68613. joint: joint
  68614. };
  68615. joint.physicsPlugin = this._physicsPlugin;
  68616. this._joints.push(impostorJoint);
  68617. this._physicsPlugin.generateJoint(impostorJoint);
  68618. };
  68619. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  68620. var matchingJoints = this._joints.filter(function (impostorJoint) {
  68621. return (impostorJoint.connectedImpostor === connectedImpostor
  68622. && impostorJoint.joint === joint
  68623. && impostorJoint.mainImpostor === mainImpostor);
  68624. });
  68625. if (matchingJoints.length) {
  68626. this._physicsPlugin.removeJoint(matchingJoints[0]);
  68627. //TODO remove it from the list as well
  68628. }
  68629. };
  68630. /**
  68631. * Called by the scene. no need to call it.
  68632. */
  68633. PhysicsEngine.prototype._step = function (delta) {
  68634. var _this = this;
  68635. //check if any mesh has no body / requires an update
  68636. this._impostors.forEach(function (impostor) {
  68637. if (impostor.isBodyInitRequired()) {
  68638. _this._physicsPlugin.generatePhysicsBody(impostor);
  68639. }
  68640. });
  68641. if (delta > 0.1) {
  68642. delta = 0.1;
  68643. }
  68644. else if (delta <= 0) {
  68645. delta = 1.0 / 60.0;
  68646. }
  68647. this._physicsPlugin.executeStep(delta, this._impostors);
  68648. };
  68649. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  68650. return this._physicsPlugin;
  68651. };
  68652. PhysicsEngine.prototype.getImpostors = function () {
  68653. return this._impostors;
  68654. };
  68655. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  68656. for (var i = 0; i < this._impostors.length; ++i) {
  68657. if (this._impostors[i].object === object) {
  68658. return this._impostors[i];
  68659. }
  68660. }
  68661. return null;
  68662. };
  68663. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  68664. for (var i = 0; i < this._impostors.length; ++i) {
  68665. if (this._impostors[i].physicsBody === body) {
  68666. return this._impostors[i];
  68667. }
  68668. }
  68669. return null;
  68670. };
  68671. // Statics
  68672. PhysicsEngine.Epsilon = 0.001;
  68673. return PhysicsEngine;
  68674. }());
  68675. BABYLON.PhysicsEngine = PhysicsEngine;
  68676. })(BABYLON || (BABYLON = {}));
  68677. //# sourceMappingURL=babylon.physicsEngine.js.map
  68678. var BABYLON;
  68679. (function (BABYLON) {
  68680. var PhysicsHelper = /** @class */ (function () {
  68681. function PhysicsHelper(scene) {
  68682. this._scene = scene;
  68683. this._physicsEngine = this._scene.getPhysicsEngine();
  68684. if (!this._physicsEngine) {
  68685. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  68686. }
  68687. }
  68688. /**
  68689. * @param {Vector3} origin the origin of the explosion
  68690. * @param {number} radius the explosion radius
  68691. * @param {number} strength the explosion strength
  68692. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68693. */
  68694. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  68695. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68696. if (!this._physicsEngine) {
  68697. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68698. return null;
  68699. }
  68700. var impostors = this._physicsEngine.getImpostors();
  68701. if (impostors.length === 0) {
  68702. return null;
  68703. }
  68704. var event = new PhysicsRadialExplosionEvent(this._scene);
  68705. impostors.forEach(function (impostor) {
  68706. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68707. if (!impostorForceAndContactPoint) {
  68708. return;
  68709. }
  68710. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68711. });
  68712. event.dispose(false);
  68713. return event;
  68714. };
  68715. /**
  68716. * @param {Vector3} origin the origin of the explosion
  68717. * @param {number} radius the explosion radius
  68718. * @param {number} strength the explosion strength
  68719. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68720. */
  68721. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68722. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68723. if (!this._physicsEngine) {
  68724. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68725. return null;
  68726. }
  68727. var impostors = this._physicsEngine.getImpostors();
  68728. if (impostors.length === 0) {
  68729. return null;
  68730. }
  68731. var event = new PhysicsRadialExplosionEvent(this._scene);
  68732. impostors.forEach(function (impostor) {
  68733. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68734. if (!impostorForceAndContactPoint) {
  68735. return;
  68736. }
  68737. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68738. });
  68739. event.dispose(false);
  68740. return event;
  68741. };
  68742. /**
  68743. * @param {Vector3} origin the origin of the explosion
  68744. * @param {number} radius the explosion radius
  68745. * @param {number} strength the explosion strength
  68746. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68747. */
  68748. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68749. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68750. if (!this._physicsEngine) {
  68751. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68752. return null;
  68753. }
  68754. var impostors = this._physicsEngine.getImpostors();
  68755. if (impostors.length === 0) {
  68756. return null;
  68757. }
  68758. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68759. event.dispose(false);
  68760. return event;
  68761. };
  68762. /**
  68763. * @param {Vector3} origin the origin of the updraft
  68764. * @param {number} radius the radius of the updraft
  68765. * @param {number} strength the strength of the updraft
  68766. * @param {number} height the height of the updraft
  68767. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68768. */
  68769. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68770. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68771. if (!this._physicsEngine) {
  68772. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68773. return null;
  68774. }
  68775. if (this._physicsEngine.getImpostors().length === 0) {
  68776. return null;
  68777. }
  68778. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68779. event.dispose(false);
  68780. return event;
  68781. };
  68782. /**
  68783. * @param {Vector3} origin the of the vortex
  68784. * @param {number} radius the radius of the vortex
  68785. * @param {number} strength the strength of the vortex
  68786. * @param {number} height the height of the vortex
  68787. */
  68788. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68789. if (!this._physicsEngine) {
  68790. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68791. return null;
  68792. }
  68793. if (this._physicsEngine.getImpostors().length === 0) {
  68794. return null;
  68795. }
  68796. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68797. event.dispose(false);
  68798. return event;
  68799. };
  68800. return PhysicsHelper;
  68801. }());
  68802. BABYLON.PhysicsHelper = PhysicsHelper;
  68803. /***** Radial explosion *****/
  68804. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68805. function PhysicsRadialExplosionEvent(scene) {
  68806. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68807. this._rays = [];
  68808. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68809. this._scene = scene;
  68810. }
  68811. /**
  68812. * Returns the data related to the radial explosion event (sphere & rays).
  68813. * @returns {PhysicsRadialExplosionEventData}
  68814. */
  68815. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68816. this._dataFetched = true;
  68817. return {
  68818. sphere: this._sphere,
  68819. rays: this._rays,
  68820. };
  68821. };
  68822. /**
  68823. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68824. * @param impostor
  68825. * @param {Vector3} origin the origin of the explosion
  68826. * @param {number} radius the explosion radius
  68827. * @param {number} strength the explosion strength
  68828. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68829. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68830. */
  68831. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68832. if (impostor.mass === 0) {
  68833. return null;
  68834. }
  68835. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  68836. return null;
  68837. }
  68838. if (impostor.object.getClassName() !== 'Mesh') {
  68839. return null;
  68840. }
  68841. var impostorObject = impostor.object;
  68842. var impostorObjectCenter = impostor.getObjectCenter();
  68843. var direction = impostorObjectCenter.subtract(origin);
  68844. var ray = new BABYLON.Ray(origin, direction, radius);
  68845. this._rays.push(ray);
  68846. var hit = ray.intersectsMesh(impostorObject);
  68847. var contactPoint = hit.pickedPoint;
  68848. if (!contactPoint) {
  68849. return null;
  68850. }
  68851. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  68852. if (distanceFromOrigin > radius) {
  68853. return null;
  68854. }
  68855. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  68856. ? strength
  68857. : strength * (1 - (distanceFromOrigin / radius));
  68858. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68859. return { force: force, contactPoint: contactPoint };
  68860. };
  68861. /**
  68862. * Disposes the sphere.
  68863. * @param {bolean} force
  68864. */
  68865. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  68866. var _this = this;
  68867. if (force === void 0) { force = true; }
  68868. if (force) {
  68869. this._sphere.dispose();
  68870. }
  68871. else {
  68872. setTimeout(function () {
  68873. if (!_this._dataFetched) {
  68874. _this._sphere.dispose();
  68875. }
  68876. }, 0);
  68877. }
  68878. };
  68879. /*** Helpers ***/
  68880. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  68881. if (!this._sphere) {
  68882. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  68883. this._sphere.isVisible = false;
  68884. }
  68885. };
  68886. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  68887. var impostorObject = impostor.object;
  68888. this._prepareSphere();
  68889. this._sphere.position = origin;
  68890. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  68891. this._sphere._updateBoundingInfo();
  68892. this._sphere.computeWorldMatrix(true);
  68893. return this._sphere.intersectsMesh(impostorObject, true);
  68894. };
  68895. return PhysicsRadialExplosionEvent;
  68896. }());
  68897. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  68898. /***** Gravitational Field *****/
  68899. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  68900. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  68901. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68902. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68903. this._physicsHelper = physicsHelper;
  68904. this._scene = scene;
  68905. this._origin = origin;
  68906. this._radius = radius;
  68907. this._strength = strength;
  68908. this._falloff = falloff;
  68909. this._tickCallback = this._tick.bind(this);
  68910. }
  68911. /**
  68912. * Returns the data related to the gravitational field event (sphere).
  68913. * @returns {PhysicsGravitationalFieldEventData}
  68914. */
  68915. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  68916. this._dataFetched = true;
  68917. return {
  68918. sphere: this._sphere,
  68919. };
  68920. };
  68921. /**
  68922. * Enables the gravitational field.
  68923. */
  68924. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  68925. this._tickCallback.call(this);
  68926. this._scene.registerBeforeRender(this._tickCallback);
  68927. };
  68928. /**
  68929. * Disables the gravitational field.
  68930. */
  68931. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  68932. this._scene.unregisterBeforeRender(this._tickCallback);
  68933. };
  68934. /**
  68935. * Disposes the sphere.
  68936. * @param {bolean} force
  68937. */
  68938. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  68939. var _this = this;
  68940. if (force === void 0) { force = true; }
  68941. if (force) {
  68942. this._sphere.dispose();
  68943. }
  68944. else {
  68945. setTimeout(function () {
  68946. if (!_this._dataFetched) {
  68947. _this._sphere.dispose();
  68948. }
  68949. }, 0);
  68950. }
  68951. };
  68952. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  68953. // Since the params won't change, we fetch the event only once
  68954. if (this._sphere) {
  68955. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68956. }
  68957. else {
  68958. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68959. if (radialExplosionEvent) {
  68960. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  68961. }
  68962. }
  68963. };
  68964. return PhysicsGravitationalFieldEvent;
  68965. }());
  68966. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  68967. /***** Updraft *****/
  68968. var PhysicsUpdraftEvent = /** @class */ (function () {
  68969. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  68970. this._scene = _scene;
  68971. this._origin = _origin;
  68972. this._radius = _radius;
  68973. this._strength = _strength;
  68974. this._height = _height;
  68975. this._updraftMode = _updraftMode;
  68976. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68977. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  68978. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68979. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68980. this._physicsEngine = this._scene.getPhysicsEngine();
  68981. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68982. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68983. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68984. this._originDirection = this._origin.subtract(this._originTop).normalize();
  68985. }
  68986. this._tickCallback = this._tick.bind(this);
  68987. }
  68988. /**
  68989. * Returns the data related to the updraft event (cylinder).
  68990. * @returns {PhysicsUpdraftEventData}
  68991. */
  68992. PhysicsUpdraftEvent.prototype.getData = function () {
  68993. this._dataFetched = true;
  68994. return {
  68995. cylinder: this._cylinder,
  68996. };
  68997. };
  68998. /**
  68999. * Enables the updraft.
  69000. */
  69001. PhysicsUpdraftEvent.prototype.enable = function () {
  69002. this._tickCallback.call(this);
  69003. this._scene.registerBeforeRender(this._tickCallback);
  69004. };
  69005. /**
  69006. * Disables the cortex.
  69007. */
  69008. PhysicsUpdraftEvent.prototype.disable = function () {
  69009. this._scene.unregisterBeforeRender(this._tickCallback);
  69010. };
  69011. /**
  69012. * Disposes the sphere.
  69013. * @param {bolean} force
  69014. */
  69015. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  69016. var _this = this;
  69017. if (force === void 0) { force = true; }
  69018. if (force) {
  69019. this._cylinder.dispose();
  69020. }
  69021. else {
  69022. setTimeout(function () {
  69023. if (!_this._dataFetched) {
  69024. _this._cylinder.dispose();
  69025. }
  69026. }, 0);
  69027. }
  69028. };
  69029. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69030. if (impostor.mass === 0) {
  69031. return null;
  69032. }
  69033. if (!this._intersectsWithCylinder(impostor)) {
  69034. return null;
  69035. }
  69036. var impostorObjectCenter = impostor.getObjectCenter();
  69037. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  69038. var direction = this._originDirection;
  69039. }
  69040. else {
  69041. var direction = impostorObjectCenter.subtract(this._originTop);
  69042. }
  69043. var multiplier = this._strength * -1;
  69044. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  69045. return { force: force, contactPoint: impostorObjectCenter };
  69046. };
  69047. PhysicsUpdraftEvent.prototype._tick = function () {
  69048. var _this = this;
  69049. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69050. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69051. if (!impostorForceAndContactPoint) {
  69052. return;
  69053. }
  69054. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69055. });
  69056. };
  69057. /*** Helpers ***/
  69058. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  69059. if (!this._cylinder) {
  69060. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  69061. height: this._height,
  69062. diameter: this._radius * 2,
  69063. }, this._scene);
  69064. this._cylinder.isVisible = false;
  69065. }
  69066. };
  69067. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  69068. var impostorObject = impostor.object;
  69069. this._prepareCylinder();
  69070. this._cylinder.position = this._cylinderPosition;
  69071. return this._cylinder.intersectsMesh(impostorObject, true);
  69072. };
  69073. return PhysicsUpdraftEvent;
  69074. }());
  69075. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  69076. /***** Vortex *****/
  69077. var PhysicsVortexEvent = /** @class */ (function () {
  69078. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  69079. this._scene = _scene;
  69080. this._origin = _origin;
  69081. this._radius = _radius;
  69082. this._strength = _strength;
  69083. this._height = _height;
  69084. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  69085. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  69086. this._updraftMultiplier = 0.02;
  69087. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  69088. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  69089. this._physicsEngine = this._scene.getPhysicsEngine();
  69090. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  69091. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  69092. this._tickCallback = this._tick.bind(this);
  69093. }
  69094. /**
  69095. * Returns the data related to the vortex event (cylinder).
  69096. * @returns {PhysicsVortexEventData}
  69097. */
  69098. PhysicsVortexEvent.prototype.getData = function () {
  69099. this._dataFetched = true;
  69100. return {
  69101. cylinder: this._cylinder,
  69102. };
  69103. };
  69104. /**
  69105. * Enables the vortex.
  69106. */
  69107. PhysicsVortexEvent.prototype.enable = function () {
  69108. this._tickCallback.call(this);
  69109. this._scene.registerBeforeRender(this._tickCallback);
  69110. };
  69111. /**
  69112. * Disables the cortex.
  69113. */
  69114. PhysicsVortexEvent.prototype.disable = function () {
  69115. this._scene.unregisterBeforeRender(this._tickCallback);
  69116. };
  69117. /**
  69118. * Disposes the sphere.
  69119. * @param {bolean} force
  69120. */
  69121. PhysicsVortexEvent.prototype.dispose = function (force) {
  69122. var _this = this;
  69123. if (force === void 0) { force = true; }
  69124. if (force) {
  69125. this._cylinder.dispose();
  69126. }
  69127. else {
  69128. setTimeout(function () {
  69129. if (!_this._dataFetched) {
  69130. _this._cylinder.dispose();
  69131. }
  69132. }, 0);
  69133. }
  69134. };
  69135. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  69136. if (impostor.mass === 0) {
  69137. return null;
  69138. }
  69139. if (!this._intersectsWithCylinder(impostor)) {
  69140. return null;
  69141. }
  69142. if (impostor.object.getClassName() !== 'Mesh') {
  69143. return null;
  69144. }
  69145. var impostorObject = impostor.object;
  69146. var impostorObjectCenter = impostor.getObjectCenter();
  69147. 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)
  69148. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  69149. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  69150. var hit = ray.intersectsMesh(impostorObject);
  69151. var contactPoint = hit.pickedPoint;
  69152. if (!contactPoint) {
  69153. return null;
  69154. }
  69155. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  69156. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  69157. var directionToOrigin = contactPoint.normalize();
  69158. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69159. directionToOrigin = directionToOrigin.negate();
  69160. }
  69161. // TODO: find a more physically based solution
  69162. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  69163. var forceX = directionToOrigin.x * this._strength / 8;
  69164. var forceY = directionToOrigin.y * this._updraftMultiplier;
  69165. var forceZ = directionToOrigin.z * this._strength / 8;
  69166. }
  69167. else {
  69168. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  69169. var forceY = this._originTop.y * this._updraftMultiplier;
  69170. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  69171. }
  69172. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  69173. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  69174. return { force: force, contactPoint: impostorObjectCenter };
  69175. };
  69176. PhysicsVortexEvent.prototype._tick = function () {
  69177. var _this = this;
  69178. this._physicsEngine.getImpostors().forEach(function (impostor) {
  69179. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  69180. if (!impostorForceAndContactPoint) {
  69181. return;
  69182. }
  69183. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  69184. });
  69185. };
  69186. /*** Helpers ***/
  69187. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  69188. if (!this._cylinder) {
  69189. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  69190. height: this._height,
  69191. diameter: this._radius * 2,
  69192. }, this._scene);
  69193. this._cylinder.isVisible = false;
  69194. }
  69195. };
  69196. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  69197. var impostorObject = impostor.object;
  69198. this._prepareCylinder();
  69199. this._cylinder.position = this._cylinderPosition;
  69200. return this._cylinder.intersectsMesh(impostorObject, true);
  69201. };
  69202. return PhysicsVortexEvent;
  69203. }());
  69204. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  69205. /***** Enums *****/
  69206. /**
  69207. * The strenght of the force in correspondence to the distance of the affected object
  69208. */
  69209. var PhysicsRadialImpulseFalloff;
  69210. (function (PhysicsRadialImpulseFalloff) {
  69211. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  69212. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  69213. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  69214. /**
  69215. * The strenght of the force in correspondence to the distance of the affected object
  69216. */
  69217. var PhysicsUpdraftMode;
  69218. (function (PhysicsUpdraftMode) {
  69219. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  69220. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  69221. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  69222. })(BABYLON || (BABYLON = {}));
  69223. //# sourceMappingURL=babylon.physicsHelper.js.map
  69224. var BABYLON;
  69225. (function (BABYLON) {
  69226. var CannonJSPlugin = /** @class */ (function () {
  69227. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  69228. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  69229. if (iterations === void 0) { iterations = 10; }
  69230. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  69231. this.name = "CannonJSPlugin";
  69232. this._physicsMaterials = new Array();
  69233. this._fixedTimeStep = 1 / 60;
  69234. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  69235. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  69236. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  69237. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  69238. this._tmpPosition = BABYLON.Vector3.Zero();
  69239. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  69240. this._tmpUnityRotation = new BABYLON.Quaternion();
  69241. if (!this.isSupported()) {
  69242. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  69243. return;
  69244. }
  69245. this._extendNamespace();
  69246. this.world = new this.BJSCANNON.World();
  69247. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  69248. this.world.solver.iterations = iterations;
  69249. }
  69250. CannonJSPlugin.prototype.setGravity = function (gravity) {
  69251. this.world.gravity.copy(gravity);
  69252. };
  69253. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  69254. this._fixedTimeStep = timeStep;
  69255. };
  69256. CannonJSPlugin.prototype.getTimeStep = function () {
  69257. return this._fixedTimeStep;
  69258. };
  69259. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  69260. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  69261. };
  69262. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69263. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69264. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69265. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  69266. };
  69267. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69268. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  69269. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  69270. impostor.physicsBody.applyForce(impulse, worldPoint);
  69271. };
  69272. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69273. //parent-child relationship. Does this impostor has a parent impostor?
  69274. if (impostor.parent) {
  69275. if (impostor.physicsBody) {
  69276. this.removePhysicsBody(impostor);
  69277. //TODO is that needed?
  69278. impostor.forceUpdate();
  69279. }
  69280. return;
  69281. }
  69282. //should a new body be created for this impostor?
  69283. if (impostor.isBodyInitRequired()) {
  69284. var shape = this._createShape(impostor);
  69285. //unregister events, if body is being changed
  69286. var oldBody = impostor.physicsBody;
  69287. if (oldBody) {
  69288. this.removePhysicsBody(impostor);
  69289. }
  69290. //create the body and material
  69291. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  69292. var bodyCreationObject = {
  69293. mass: impostor.getParam("mass"),
  69294. material: material
  69295. };
  69296. // A simple extend, in case native options were used.
  69297. var nativeOptions = impostor.getParam("nativeOptions");
  69298. for (var key in nativeOptions) {
  69299. if (nativeOptions.hasOwnProperty(key)) {
  69300. bodyCreationObject[key] = nativeOptions[key];
  69301. }
  69302. }
  69303. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  69304. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  69305. this.world.addEventListener("preStep", impostor.beforeStep);
  69306. this.world.addEventListener("postStep", impostor.afterStep);
  69307. impostor.physicsBody.addShape(shape);
  69308. this.world.add(impostor.physicsBody);
  69309. //try to keep the body moving in the right direction by taking old properties.
  69310. //Should be tested!
  69311. if (oldBody) {
  69312. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  69313. impostor.physicsBody[param].copy(oldBody[param]);
  69314. });
  69315. }
  69316. this._processChildMeshes(impostor);
  69317. }
  69318. //now update the body's transformation
  69319. this._updatePhysicsBodyTransformation(impostor);
  69320. };
  69321. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  69322. var _this = this;
  69323. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  69324. var currentRotation = mainImpostor.object.rotationQuaternion;
  69325. if (meshChildren.length) {
  69326. var processMesh = function (localPosition, mesh) {
  69327. if (!currentRotation || !mesh.rotationQuaternion) {
  69328. return;
  69329. }
  69330. var childImpostor = mesh.getPhysicsImpostor();
  69331. if (childImpostor) {
  69332. var parent = childImpostor.parent;
  69333. if (parent !== mainImpostor) {
  69334. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  69335. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  69336. if (childImpostor.physicsBody) {
  69337. _this.removePhysicsBody(childImpostor);
  69338. childImpostor.physicsBody = null;
  69339. }
  69340. childImpostor.parent = mainImpostor;
  69341. childImpostor.resetUpdateFlags();
  69342. 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));
  69343. //Add the mass of the children.
  69344. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  69345. }
  69346. }
  69347. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  69348. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  69349. };
  69350. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  69351. }
  69352. };
  69353. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69354. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  69355. this.world.removeEventListener("preStep", impostor.beforeStep);
  69356. this.world.removeEventListener("postStep", impostor.afterStep);
  69357. this.world.remove(impostor.physicsBody);
  69358. };
  69359. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69360. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69361. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69362. if (!mainBody || !connectedBody) {
  69363. return;
  69364. }
  69365. var constraint;
  69366. var jointData = impostorJoint.joint.jointData;
  69367. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  69368. var constraintData = {
  69369. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  69370. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  69371. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  69372. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  69373. maxForce: jointData.nativeParams.maxForce,
  69374. collideConnected: !!jointData.collision
  69375. };
  69376. switch (impostorJoint.joint.type) {
  69377. case BABYLON.PhysicsJoint.HingeJoint:
  69378. case BABYLON.PhysicsJoint.Hinge2Joint:
  69379. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  69380. break;
  69381. case BABYLON.PhysicsJoint.DistanceJoint:
  69382. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  69383. break;
  69384. case BABYLON.PhysicsJoint.SpringJoint:
  69385. var springData = jointData;
  69386. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  69387. restLength: springData.length,
  69388. stiffness: springData.stiffness,
  69389. damping: springData.damping,
  69390. localAnchorA: constraintData.pivotA,
  69391. localAnchorB: constraintData.pivotB
  69392. });
  69393. break;
  69394. case BABYLON.PhysicsJoint.LockJoint:
  69395. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  69396. break;
  69397. case BABYLON.PhysicsJoint.PointToPointJoint:
  69398. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69399. default:
  69400. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  69401. break;
  69402. }
  69403. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  69404. constraint.collideConnected = !!jointData.collision;
  69405. impostorJoint.joint.physicsJoint = constraint;
  69406. //don't add spring as constraint, as it is not one.
  69407. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  69408. this.world.addConstraint(constraint);
  69409. }
  69410. else {
  69411. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  69412. constraint.applyForce();
  69413. });
  69414. }
  69415. };
  69416. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69417. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  69418. };
  69419. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  69420. var index;
  69421. var mat;
  69422. for (index = 0; index < this._physicsMaterials.length; index++) {
  69423. mat = this._physicsMaterials[index];
  69424. if (mat.friction === friction && mat.restitution === restitution) {
  69425. return mat;
  69426. }
  69427. }
  69428. var currentMat = new this.BJSCANNON.Material(name);
  69429. currentMat.friction = friction;
  69430. currentMat.restitution = restitution;
  69431. this._physicsMaterials.push(currentMat);
  69432. return currentMat;
  69433. };
  69434. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  69435. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  69436. };
  69437. CannonJSPlugin.prototype._createShape = function (impostor) {
  69438. var object = impostor.object;
  69439. var returnValue;
  69440. var extendSize = impostor.getObjectExtendSize();
  69441. switch (impostor.type) {
  69442. case BABYLON.PhysicsImpostor.SphereImpostor:
  69443. var radiusX = extendSize.x;
  69444. var radiusY = extendSize.y;
  69445. var radiusZ = extendSize.z;
  69446. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  69447. break;
  69448. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  69449. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69450. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  69451. break;
  69452. case BABYLON.PhysicsImpostor.BoxImpostor:
  69453. var box = extendSize.scale(0.5);
  69454. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  69455. break;
  69456. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69457. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  69458. returnValue = new this.BJSCANNON.Plane();
  69459. break;
  69460. case BABYLON.PhysicsImpostor.MeshImpostor:
  69461. // should transform the vertex data to world coordinates!!
  69462. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  69463. var rawFaces = object.getIndices ? object.getIndices() : [];
  69464. if (!rawVerts)
  69465. return;
  69466. // get only scale! so the object could transform correctly.
  69467. var oldPosition = object.position.clone();
  69468. var oldRotation = object.rotation && object.rotation.clone();
  69469. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  69470. object.position.copyFromFloats(0, 0, 0);
  69471. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69472. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69473. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69474. var transform = object.computeWorldMatrix(true);
  69475. // convert rawVerts to object space
  69476. var temp = new Array();
  69477. var index;
  69478. for (index = 0; index < rawVerts.length; index += 3) {
  69479. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  69480. }
  69481. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  69482. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  69483. //now set back the transformation!
  69484. object.position.copyFrom(oldPosition);
  69485. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  69486. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  69487. break;
  69488. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  69489. var oldPosition2 = object.position.clone();
  69490. var oldRotation2 = object.rotation && object.rotation.clone();
  69491. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  69492. object.position.copyFromFloats(0, 0, 0);
  69493. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  69494. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  69495. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  69496. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  69497. returnValue = this._createHeightmap(object);
  69498. object.position.copyFrom(oldPosition2);
  69499. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  69500. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  69501. object.computeWorldMatrix(true);
  69502. break;
  69503. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69504. returnValue = new this.BJSCANNON.Particle();
  69505. break;
  69506. }
  69507. return returnValue;
  69508. };
  69509. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  69510. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  69511. var transform = object.computeWorldMatrix(true);
  69512. // convert rawVerts to object space
  69513. var temp = new Array();
  69514. var index;
  69515. for (index = 0; index < pos.length; index += 3) {
  69516. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  69517. }
  69518. pos = temp;
  69519. var matrix = new Array();
  69520. //For now pointDepth will not be used and will be automatically calculated.
  69521. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  69522. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  69523. var boundingInfo = object.getBoundingInfo();
  69524. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  69525. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  69526. var elementSize = dim * 2 / arraySize;
  69527. for (var i = 0; i < pos.length; i = i + 3) {
  69528. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  69529. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  69530. var y = -pos[i + 2] + minY;
  69531. if (!matrix[x]) {
  69532. matrix[x] = [];
  69533. }
  69534. if (!matrix[x][z]) {
  69535. matrix[x][z] = y;
  69536. }
  69537. matrix[x][z] = Math.max(y, matrix[x][z]);
  69538. }
  69539. for (var x = 0; x <= arraySize; ++x) {
  69540. if (!matrix[x]) {
  69541. var loc = 1;
  69542. while (!matrix[(x + loc) % arraySize]) {
  69543. loc++;
  69544. }
  69545. matrix[x] = matrix[(x + loc) % arraySize].slice();
  69546. //console.log("missing x", x);
  69547. }
  69548. for (var z = 0; z <= arraySize; ++z) {
  69549. if (!matrix[x][z]) {
  69550. var loc = 1;
  69551. var newValue;
  69552. while (newValue === undefined) {
  69553. newValue = matrix[x][(z + loc++) % arraySize];
  69554. }
  69555. matrix[x][z] = newValue;
  69556. }
  69557. }
  69558. }
  69559. var shape = new this.BJSCANNON.Heightfield(matrix, {
  69560. elementSize: elementSize
  69561. });
  69562. //For future reference, needed for body transformation
  69563. shape.minY = minY;
  69564. return shape;
  69565. };
  69566. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  69567. var object = impostor.object;
  69568. //make sure it is updated...
  69569. object.computeWorldMatrix && object.computeWorldMatrix(true);
  69570. // The delta between the mesh position and the mesh bounding box center
  69571. var bInfo = object.getBoundingInfo();
  69572. if (!bInfo)
  69573. return;
  69574. var center = impostor.getObjectCenter();
  69575. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  69576. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  69577. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  69578. this._tmpPosition.copyFrom(center);
  69579. var quaternion = object.rotationQuaternion;
  69580. if (!quaternion) {
  69581. return;
  69582. }
  69583. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  69584. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  69585. //-90 DEG in X, precalculated
  69586. quaternion = quaternion.multiply(this._minus90X);
  69587. //Invert! (Precalculated, 90 deg in X)
  69588. //No need to clone. this will never change.
  69589. impostor.setDeltaRotation(this._plus90X);
  69590. }
  69591. //If it is a heightfield, if should be centered.
  69592. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  69593. var mesh = object;
  69594. var boundingInfo = mesh.getBoundingInfo();
  69595. //calculate the correct body position:
  69596. var rotationQuaternion = mesh.rotationQuaternion;
  69597. mesh.rotationQuaternion = this._tmpUnityRotation;
  69598. mesh.computeWorldMatrix(true);
  69599. //get original center with no rotation
  69600. var c = center.clone();
  69601. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  69602. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  69603. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  69604. mesh.setPivotMatrix(p);
  69605. mesh.computeWorldMatrix(true);
  69606. //calculate the translation
  69607. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  69608. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  69609. //add it inverted to the delta
  69610. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  69611. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  69612. //rotation is back
  69613. mesh.rotationQuaternion = rotationQuaternion;
  69614. mesh.setPivotMatrix(oldPivot);
  69615. mesh.computeWorldMatrix(true);
  69616. }
  69617. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  69618. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  69619. //this._tmpPosition.copyFrom(object.position);
  69620. }
  69621. impostor.setDeltaPosition(this._tmpDeltaPosition);
  69622. //Now update the impostor object
  69623. impostor.physicsBody.position.copy(this._tmpPosition);
  69624. impostor.physicsBody.quaternion.copy(quaternion);
  69625. };
  69626. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69627. impostor.object.position.copyFrom(impostor.physicsBody.position);
  69628. if (impostor.object.rotationQuaternion) {
  69629. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  69630. }
  69631. };
  69632. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69633. impostor.physicsBody.position.copy(newPosition);
  69634. impostor.physicsBody.quaternion.copy(newRotation);
  69635. };
  69636. CannonJSPlugin.prototype.isSupported = function () {
  69637. return this.BJSCANNON !== undefined;
  69638. };
  69639. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69640. impostor.physicsBody.velocity.copy(velocity);
  69641. };
  69642. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69643. impostor.physicsBody.angularVelocity.copy(velocity);
  69644. };
  69645. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69646. var v = impostor.physicsBody.velocity;
  69647. if (!v) {
  69648. return null;
  69649. }
  69650. return new BABYLON.Vector3(v.x, v.y, v.z);
  69651. };
  69652. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69653. var v = impostor.physicsBody.angularVelocity;
  69654. if (!v) {
  69655. return null;
  69656. }
  69657. return new BABYLON.Vector3(v.x, v.y, v.z);
  69658. };
  69659. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69660. impostor.physicsBody.mass = mass;
  69661. impostor.physicsBody.updateMassProperties();
  69662. };
  69663. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  69664. return impostor.physicsBody.mass;
  69665. };
  69666. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  69667. return impostor.physicsBody.material.friction;
  69668. };
  69669. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69670. impostor.physicsBody.material.friction = friction;
  69671. };
  69672. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69673. return impostor.physicsBody.material.restitution;
  69674. };
  69675. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69676. impostor.physicsBody.material.restitution = restitution;
  69677. };
  69678. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  69679. impostor.physicsBody.sleep();
  69680. };
  69681. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  69682. impostor.physicsBody.wakeUp();
  69683. };
  69684. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69685. joint.physicsJoint.distance = maxDistance;
  69686. };
  69687. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69688. // if (!motorIndex) {
  69689. // joint.physicsJoint.enableMotor();
  69690. // }
  69691. // }
  69692. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  69693. // if (!motorIndex) {
  69694. // joint.physicsJoint.disableMotor();
  69695. // }
  69696. // }
  69697. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69698. if (!motorIndex) {
  69699. joint.physicsJoint.enableMotor();
  69700. joint.physicsJoint.setMotorSpeed(speed);
  69701. if (maxForce) {
  69702. this.setLimit(joint, maxForce);
  69703. }
  69704. }
  69705. };
  69706. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69707. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69708. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69709. };
  69710. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69711. var body = impostor.physicsBody;
  69712. mesh.position.x = body.position.x;
  69713. mesh.position.y = body.position.y;
  69714. mesh.position.z = body.position.z;
  69715. if (mesh.rotationQuaternion) {
  69716. mesh.rotationQuaternion.x = body.quaternion.x;
  69717. mesh.rotationQuaternion.y = body.quaternion.y;
  69718. mesh.rotationQuaternion.z = body.quaternion.z;
  69719. mesh.rotationQuaternion.w = body.quaternion.w;
  69720. }
  69721. };
  69722. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69723. var shape = impostor.physicsBody.shapes[0];
  69724. return shape.boundingSphereRadius;
  69725. };
  69726. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69727. var shape = impostor.physicsBody.shapes[0];
  69728. result.x = shape.halfExtents.x * 2;
  69729. result.y = shape.halfExtents.y * 2;
  69730. result.z = shape.halfExtents.z * 2;
  69731. };
  69732. CannonJSPlugin.prototype.dispose = function () {
  69733. };
  69734. CannonJSPlugin.prototype._extendNamespace = function () {
  69735. //this will force cannon to execute at least one step when using interpolation
  69736. var step_tmp1 = new this.BJSCANNON.Vec3();
  69737. var Engine = this.BJSCANNON;
  69738. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69739. maxSubSteps = maxSubSteps || 10;
  69740. timeSinceLastCalled = timeSinceLastCalled || 0;
  69741. if (timeSinceLastCalled === 0) {
  69742. this.internalStep(dt);
  69743. this.time += dt;
  69744. }
  69745. else {
  69746. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69747. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69748. var t0 = performance.now();
  69749. for (var i = 0; i !== internalSteps; i++) {
  69750. this.internalStep(dt);
  69751. if (performance.now() - t0 > dt * 1000) {
  69752. break;
  69753. }
  69754. }
  69755. this.time += timeSinceLastCalled;
  69756. var h = this.time % dt;
  69757. var h_div_dt = h / dt;
  69758. var interpvelo = step_tmp1;
  69759. var bodies = this.bodies;
  69760. for (var j = 0; j !== bodies.length; j++) {
  69761. var b = bodies[j];
  69762. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69763. b.position.vsub(b.previousPosition, interpvelo);
  69764. interpvelo.scale(h_div_dt, interpvelo);
  69765. b.position.vadd(interpvelo, b.interpolatedPosition);
  69766. }
  69767. else {
  69768. b.interpolatedPosition.copy(b.position);
  69769. b.interpolatedQuaternion.copy(b.quaternion);
  69770. }
  69771. }
  69772. }
  69773. };
  69774. };
  69775. return CannonJSPlugin;
  69776. }());
  69777. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69778. })(BABYLON || (BABYLON = {}));
  69779. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69780. var BABYLON;
  69781. (function (BABYLON) {
  69782. var OimoJSPlugin = /** @class */ (function () {
  69783. function OimoJSPlugin(iterations) {
  69784. this.name = "OimoJSPlugin";
  69785. this._tmpImpostorsArray = [];
  69786. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69787. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69788. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69789. this.world.worldscale(1);
  69790. this.world.clear();
  69791. //making sure no stats are calculated
  69792. this.world.isNoStat = true;
  69793. }
  69794. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69795. this.world.gravity.copy(gravity);
  69796. };
  69797. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69798. this.world.timeStep = timeStep;
  69799. };
  69800. OimoJSPlugin.prototype.getTimeStep = function () {
  69801. return this.world.timeStep;
  69802. };
  69803. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69804. var _this = this;
  69805. impostors.forEach(function (impostor) {
  69806. impostor.beforeStep();
  69807. });
  69808. this.world.step();
  69809. impostors.forEach(function (impostor) {
  69810. impostor.afterStep();
  69811. //update the ordered impostors array
  69812. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69813. });
  69814. //check for collisions
  69815. var contact = this.world.contacts;
  69816. while (contact !== null) {
  69817. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69818. contact = contact.next;
  69819. continue;
  69820. }
  69821. //is this body colliding with any other? get the impostor
  69822. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69823. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69824. if (!mainImpostor || !collidingImpostor) {
  69825. contact = contact.next;
  69826. continue;
  69827. }
  69828. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69829. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69830. contact = contact.next;
  69831. }
  69832. };
  69833. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69834. var mass = impostor.physicsBody.massInfo.mass;
  69835. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  69836. };
  69837. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69838. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  69839. this.applyImpulse(impostor, force, contactPoint);
  69840. };
  69841. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69842. var _this = this;
  69843. //parent-child relationship. Does this impostor has a parent impostor?
  69844. if (impostor.parent) {
  69845. if (impostor.physicsBody) {
  69846. this.removePhysicsBody(impostor);
  69847. //TODO is that needed?
  69848. impostor.forceUpdate();
  69849. }
  69850. return;
  69851. }
  69852. if (impostor.isBodyInitRequired()) {
  69853. var bodyConfig = {
  69854. name: impostor.uniqueId,
  69855. //Oimo must have mass, also for static objects.
  69856. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  69857. size: [],
  69858. type: [],
  69859. pos: [],
  69860. rot: [],
  69861. move: impostor.getParam("mass") !== 0,
  69862. //Supporting older versions of Oimo
  69863. world: this.world
  69864. };
  69865. var impostors = [impostor];
  69866. var addToArray = function (parent) {
  69867. if (!parent.getChildMeshes)
  69868. return;
  69869. parent.getChildMeshes().forEach(function (m) {
  69870. if (m.physicsImpostor) {
  69871. impostors.push(m.physicsImpostor);
  69872. //m.physicsImpostor._init();
  69873. }
  69874. });
  69875. };
  69876. addToArray(impostor.object);
  69877. var checkWithEpsilon_1 = function (value) {
  69878. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  69879. };
  69880. impostors.forEach(function (i) {
  69881. if (!impostor.object.rotationQuaternion) {
  69882. return;
  69883. }
  69884. //get the correct bounding box
  69885. var oldQuaternion = i.object.rotationQuaternion;
  69886. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  69887. x: impostor.object.rotationQuaternion.x,
  69888. y: impostor.object.rotationQuaternion.y,
  69889. z: impostor.object.rotationQuaternion.z,
  69890. s: impostor.object.rotationQuaternion.w
  69891. });
  69892. var extendSize = i.getObjectExtendSize();
  69893. if (i === impostor) {
  69894. var center = impostor.getObjectCenter();
  69895. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  69896. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  69897. //Can also use Array.prototype.push.apply
  69898. bodyConfig.pos.push(center.x);
  69899. bodyConfig.pos.push(center.y);
  69900. bodyConfig.pos.push(center.z);
  69901. //tmp solution
  69902. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69903. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69904. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69905. }
  69906. else {
  69907. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  69908. bodyConfig.pos.push(localPosition.x);
  69909. bodyConfig.pos.push(localPosition.y);
  69910. bodyConfig.pos.push(localPosition.z);
  69911. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  69912. bodyConfig.rot.push(0);
  69913. bodyConfig.rot.push(0);
  69914. bodyConfig.rot.push(0);
  69915. }
  69916. // register mesh
  69917. switch (i.type) {
  69918. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69919. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  69920. case BABYLON.PhysicsImpostor.SphereImpostor:
  69921. var radiusX = extendSize.x;
  69922. var radiusY = extendSize.y;
  69923. var radiusZ = extendSize.z;
  69924. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  69925. bodyConfig.type.push('sphere');
  69926. //due to the way oimo works with compounds, add 3 times
  69927. bodyConfig.size.push(size);
  69928. bodyConfig.size.push(size);
  69929. bodyConfig.size.push(size);
  69930. break;
  69931. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69932. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  69933. var sizeY = checkWithEpsilon_1(extendSize.y);
  69934. bodyConfig.type.push('cylinder');
  69935. bodyConfig.size.push(sizeX);
  69936. bodyConfig.size.push(sizeY);
  69937. //due to the way oimo works with compounds, add one more value.
  69938. bodyConfig.size.push(sizeY);
  69939. break;
  69940. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69941. case BABYLON.PhysicsImpostor.BoxImpostor:
  69942. default:
  69943. var sizeX = checkWithEpsilon_1(extendSize.x);
  69944. var sizeY = checkWithEpsilon_1(extendSize.y);
  69945. var sizeZ = checkWithEpsilon_1(extendSize.z);
  69946. bodyConfig.type.push('box');
  69947. bodyConfig.size.push(sizeX);
  69948. bodyConfig.size.push(sizeY);
  69949. bodyConfig.size.push(sizeZ);
  69950. break;
  69951. }
  69952. //actually not needed, but hey...
  69953. i.object.rotationQuaternion = oldQuaternion;
  69954. });
  69955. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  69956. }
  69957. else {
  69958. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  69959. }
  69960. impostor.setDeltaPosition(this._tmpPositionVector);
  69961. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  69962. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  69963. };
  69964. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69965. //impostor.physicsBody.dispose();
  69966. //Same as : (older oimo versions)
  69967. this.world.removeRigidBody(impostor.physicsBody);
  69968. };
  69969. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69970. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69971. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69972. if (!mainBody || !connectedBody) {
  69973. return;
  69974. }
  69975. var jointData = impostorJoint.joint.jointData;
  69976. var options = jointData.nativeParams || {};
  69977. var type;
  69978. var nativeJointData = {
  69979. body1: mainBody,
  69980. body2: connectedBody,
  69981. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  69982. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  69983. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  69984. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  69985. min: options.min,
  69986. max: options.max,
  69987. collision: options.collision || jointData.collision,
  69988. spring: options.spring,
  69989. //supporting older version of Oimo
  69990. world: this.world
  69991. };
  69992. switch (impostorJoint.joint.type) {
  69993. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69994. type = "jointBall";
  69995. break;
  69996. case BABYLON.PhysicsJoint.SpringJoint:
  69997. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  69998. var springData = jointData;
  69999. nativeJointData.min = springData.length || nativeJointData.min;
  70000. //Max should also be set, just make sure it is at least min
  70001. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  70002. case BABYLON.PhysicsJoint.DistanceJoint:
  70003. type = "jointDistance";
  70004. nativeJointData.max = jointData.maxDistance;
  70005. break;
  70006. case BABYLON.PhysicsJoint.PrismaticJoint:
  70007. type = "jointPrisme";
  70008. break;
  70009. case BABYLON.PhysicsJoint.SliderJoint:
  70010. type = "jointSlide";
  70011. break;
  70012. case BABYLON.PhysicsJoint.WheelJoint:
  70013. type = "jointWheel";
  70014. break;
  70015. case BABYLON.PhysicsJoint.HingeJoint:
  70016. default:
  70017. type = "jointHinge";
  70018. break;
  70019. }
  70020. nativeJointData.type = type;
  70021. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  70022. };
  70023. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  70024. //Bug in Oimo prevents us from disposing a joint in the playground
  70025. //joint.joint.physicsJoint.dispose();
  70026. //So we will bruteforce it!
  70027. try {
  70028. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  70029. }
  70030. catch (e) {
  70031. BABYLON.Tools.Warn(e);
  70032. }
  70033. };
  70034. OimoJSPlugin.prototype.isSupported = function () {
  70035. return this.BJSOIMO !== undefined;
  70036. };
  70037. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  70038. if (!impostor.physicsBody.sleeping) {
  70039. //TODO check that
  70040. if (impostor.physicsBody.shapes.next) {
  70041. var parentShape = this._getLastShape(impostor.physicsBody);
  70042. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  70043. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  70044. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  70045. }
  70046. else {
  70047. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  70048. }
  70049. if (impostor.object.rotationQuaternion) {
  70050. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  70051. impostor.object.rotationQuaternion.normalize();
  70052. }
  70053. }
  70054. };
  70055. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  70056. var body = impostor.physicsBody;
  70057. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  70058. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  70059. body.syncShapes();
  70060. body.awake();
  70061. };
  70062. OimoJSPlugin.prototype._getLastShape = function (body) {
  70063. var lastShape = body.shapes;
  70064. while (lastShape.next) {
  70065. lastShape = lastShape.next;
  70066. }
  70067. return lastShape;
  70068. };
  70069. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  70070. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  70071. };
  70072. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  70073. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  70074. };
  70075. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  70076. var v = impostor.physicsBody.linearVelocity;
  70077. if (!v) {
  70078. return null;
  70079. }
  70080. return new BABYLON.Vector3(v.x, v.y, v.z);
  70081. };
  70082. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  70083. var v = impostor.physicsBody.angularVelocity;
  70084. if (!v) {
  70085. return null;
  70086. }
  70087. return new BABYLON.Vector3(v.x, v.y, v.z);
  70088. };
  70089. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  70090. var staticBody = mass === 0;
  70091. //this will actually set the body's density and not its mass.
  70092. //But this is how oimo treats the mass variable.
  70093. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  70094. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  70095. };
  70096. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  70097. return impostor.physicsBody.shapes.density;
  70098. };
  70099. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  70100. return impostor.physicsBody.shapes.friction;
  70101. };
  70102. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  70103. impostor.physicsBody.shapes.friction = friction;
  70104. };
  70105. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  70106. return impostor.physicsBody.shapes.restitution;
  70107. };
  70108. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  70109. impostor.physicsBody.shapes.restitution = restitution;
  70110. };
  70111. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  70112. impostor.physicsBody.sleep();
  70113. };
  70114. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  70115. impostor.physicsBody.awake();
  70116. };
  70117. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  70118. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  70119. if (minDistance !== void 0) {
  70120. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  70121. }
  70122. };
  70123. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  70124. //TODO separate rotational and transational motors.
  70125. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70126. if (motor) {
  70127. motor.setMotor(speed, maxForce);
  70128. }
  70129. };
  70130. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  70131. //TODO separate rotational and transational motors.
  70132. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  70133. if (motor) {
  70134. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  70135. }
  70136. };
  70137. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  70138. var body = impostor.physicsBody;
  70139. mesh.position.x = body.position.x;
  70140. mesh.position.y = body.position.y;
  70141. mesh.position.z = body.position.z;
  70142. if (mesh.rotationQuaternion) {
  70143. mesh.rotationQuaternion.x = body.orientation.x;
  70144. mesh.rotationQuaternion.y = body.orientation.y;
  70145. mesh.rotationQuaternion.z = body.orientation.z;
  70146. mesh.rotationQuaternion.w = body.orientation.s;
  70147. }
  70148. };
  70149. OimoJSPlugin.prototype.getRadius = function (impostor) {
  70150. return impostor.physicsBody.shapes.radius;
  70151. };
  70152. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  70153. var shape = impostor.physicsBody.shapes;
  70154. result.x = shape.halfWidth * 2;
  70155. result.y = shape.halfHeight * 2;
  70156. result.z = shape.halfDepth * 2;
  70157. };
  70158. OimoJSPlugin.prototype.dispose = function () {
  70159. this.world.clear();
  70160. };
  70161. return OimoJSPlugin;
  70162. }());
  70163. BABYLON.OimoJSPlugin = OimoJSPlugin;
  70164. })(BABYLON || (BABYLON = {}));
  70165. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  70166. var BABYLON;
  70167. (function (BABYLON) {
  70168. /*
  70169. * Based on jsTGALoader - Javascript loader for TGA file
  70170. * By Vincent Thibault
  70171. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  70172. */
  70173. var TGATools = /** @class */ (function () {
  70174. function TGATools() {
  70175. }
  70176. TGATools.GetTGAHeader = function (data) {
  70177. var offset = 0;
  70178. var header = {
  70179. id_length: data[offset++],
  70180. colormap_type: data[offset++],
  70181. image_type: data[offset++],
  70182. colormap_index: data[offset++] | data[offset++] << 8,
  70183. colormap_length: data[offset++] | data[offset++] << 8,
  70184. colormap_size: data[offset++],
  70185. origin: [
  70186. data[offset++] | data[offset++] << 8,
  70187. data[offset++] | data[offset++] << 8
  70188. ],
  70189. width: data[offset++] | data[offset++] << 8,
  70190. height: data[offset++] | data[offset++] << 8,
  70191. pixel_size: data[offset++],
  70192. flags: data[offset++]
  70193. };
  70194. return header;
  70195. };
  70196. TGATools.UploadContent = function (gl, data) {
  70197. // Not enough data to contain header ?
  70198. if (data.length < 19) {
  70199. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  70200. return;
  70201. }
  70202. // Read Header
  70203. var offset = 18;
  70204. var header = TGATools.GetTGAHeader(data);
  70205. // Assume it's a valid Targa file.
  70206. if (header.id_length + offset > data.length) {
  70207. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  70208. return;
  70209. }
  70210. // Skip not needed data
  70211. offset += header.id_length;
  70212. var use_rle = false;
  70213. var use_pal = false;
  70214. var use_grey = false;
  70215. // Get some informations.
  70216. switch (header.image_type) {
  70217. case TGATools._TYPE_RLE_INDEXED:
  70218. use_rle = true;
  70219. case TGATools._TYPE_INDEXED:
  70220. use_pal = true;
  70221. break;
  70222. case TGATools._TYPE_RLE_RGB:
  70223. use_rle = true;
  70224. case TGATools._TYPE_RGB:
  70225. // use_rgb = true;
  70226. break;
  70227. case TGATools._TYPE_RLE_GREY:
  70228. use_rle = true;
  70229. case TGATools._TYPE_GREY:
  70230. use_grey = true;
  70231. break;
  70232. }
  70233. var pixel_data;
  70234. // var numAlphaBits = header.flags & 0xf;
  70235. var pixel_size = header.pixel_size >> 3;
  70236. var pixel_total = header.width * header.height * pixel_size;
  70237. // Read palettes
  70238. var palettes;
  70239. if (use_pal) {
  70240. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  70241. }
  70242. // Read LRE
  70243. if (use_rle) {
  70244. pixel_data = new Uint8Array(pixel_total);
  70245. var c, count, i;
  70246. var localOffset = 0;
  70247. var pixels = new Uint8Array(pixel_size);
  70248. while (offset < pixel_total && localOffset < pixel_total) {
  70249. c = data[offset++];
  70250. count = (c & 0x7f) + 1;
  70251. // RLE pixels
  70252. if (c & 0x80) {
  70253. // Bind pixel tmp array
  70254. for (i = 0; i < pixel_size; ++i) {
  70255. pixels[i] = data[offset++];
  70256. }
  70257. // Copy pixel array
  70258. for (i = 0; i < count; ++i) {
  70259. pixel_data.set(pixels, localOffset + i * pixel_size);
  70260. }
  70261. localOffset += pixel_size * count;
  70262. }
  70263. else {
  70264. count *= pixel_size;
  70265. for (i = 0; i < count; ++i) {
  70266. pixel_data[localOffset + i] = data[offset++];
  70267. }
  70268. localOffset += count;
  70269. }
  70270. }
  70271. }
  70272. else {
  70273. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  70274. }
  70275. // Load to texture
  70276. var x_start, y_start, x_step, y_step, y_end, x_end;
  70277. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  70278. default:
  70279. case TGATools._ORIGIN_UL:
  70280. x_start = 0;
  70281. x_step = 1;
  70282. x_end = header.width;
  70283. y_start = 0;
  70284. y_step = 1;
  70285. y_end = header.height;
  70286. break;
  70287. case TGATools._ORIGIN_BL:
  70288. x_start = 0;
  70289. x_step = 1;
  70290. x_end = header.width;
  70291. y_start = header.height - 1;
  70292. y_step = -1;
  70293. y_end = -1;
  70294. break;
  70295. case TGATools._ORIGIN_UR:
  70296. x_start = header.width - 1;
  70297. x_step = -1;
  70298. x_end = -1;
  70299. y_start = 0;
  70300. y_step = 1;
  70301. y_end = header.height;
  70302. break;
  70303. case TGATools._ORIGIN_BR:
  70304. x_start = header.width - 1;
  70305. x_step = -1;
  70306. x_end = -1;
  70307. y_start = header.height - 1;
  70308. y_step = -1;
  70309. y_end = -1;
  70310. break;
  70311. }
  70312. // Load the specify method
  70313. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  70314. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  70315. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  70316. };
  70317. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70318. var image = pixel_data, colormap = palettes;
  70319. var width = header.width, height = header.height;
  70320. var color, i = 0, x, y;
  70321. var imageData = new Uint8Array(width * height * 4);
  70322. for (y = y_start; y !== y_end; y += y_step) {
  70323. for (x = x_start; x !== x_end; x += x_step, i++) {
  70324. color = image[i];
  70325. imageData[(x + width * y) * 4 + 3] = 255;
  70326. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  70327. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  70328. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  70329. }
  70330. }
  70331. return imageData;
  70332. };
  70333. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70334. var image = pixel_data;
  70335. var width = header.width, height = header.height;
  70336. var color, i = 0, x, y;
  70337. var imageData = new Uint8Array(width * height * 4);
  70338. for (y = y_start; y !== y_end; y += y_step) {
  70339. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70340. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  70341. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  70342. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  70343. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  70344. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  70345. }
  70346. }
  70347. return imageData;
  70348. };
  70349. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70350. var image = pixel_data;
  70351. var width = header.width, height = header.height;
  70352. var i = 0, x, y;
  70353. var imageData = new Uint8Array(width * height * 4);
  70354. for (y = y_start; y !== y_end; y += y_step) {
  70355. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  70356. imageData[(x + width * y) * 4 + 3] = 255;
  70357. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70358. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70359. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70360. }
  70361. }
  70362. return imageData;
  70363. };
  70364. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70365. var image = pixel_data;
  70366. var width = header.width, height = header.height;
  70367. var i = 0, x, y;
  70368. var imageData = new Uint8Array(width * height * 4);
  70369. for (y = y_start; y !== y_end; y += y_step) {
  70370. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  70371. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70372. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  70373. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  70374. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  70375. }
  70376. }
  70377. return imageData;
  70378. };
  70379. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70380. var image = pixel_data;
  70381. var width = header.width, height = header.height;
  70382. var color, i = 0, x, y;
  70383. var imageData = new Uint8Array(width * height * 4);
  70384. for (y = y_start; y !== y_end; y += y_step) {
  70385. for (x = x_start; x !== x_end; x += x_step, i++) {
  70386. color = image[i];
  70387. imageData[(x + width * y) * 4 + 0] = color;
  70388. imageData[(x + width * y) * 4 + 1] = color;
  70389. imageData[(x + width * y) * 4 + 2] = color;
  70390. imageData[(x + width * y) * 4 + 3] = 255;
  70391. }
  70392. }
  70393. return imageData;
  70394. };
  70395. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  70396. var image = pixel_data;
  70397. var width = header.width, height = header.height;
  70398. var i = 0, x, y;
  70399. var imageData = new Uint8Array(width * height * 4);
  70400. for (y = y_start; y !== y_end; y += y_step) {
  70401. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  70402. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  70403. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  70404. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  70405. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  70406. }
  70407. }
  70408. return imageData;
  70409. };
  70410. //private static _TYPE_NO_DATA = 0;
  70411. TGATools._TYPE_INDEXED = 1;
  70412. TGATools._TYPE_RGB = 2;
  70413. TGATools._TYPE_GREY = 3;
  70414. TGATools._TYPE_RLE_INDEXED = 9;
  70415. TGATools._TYPE_RLE_RGB = 10;
  70416. TGATools._TYPE_RLE_GREY = 11;
  70417. TGATools._ORIGIN_MASK = 0x30;
  70418. TGATools._ORIGIN_SHIFT = 0x04;
  70419. TGATools._ORIGIN_BL = 0x00;
  70420. TGATools._ORIGIN_BR = 0x01;
  70421. TGATools._ORIGIN_UL = 0x02;
  70422. TGATools._ORIGIN_UR = 0x03;
  70423. return TGATools;
  70424. }());
  70425. BABYLON.TGATools = TGATools;
  70426. })(BABYLON || (BABYLON = {}));
  70427. //# sourceMappingURL=babylon.tga.js.map
  70428. var BABYLON;
  70429. (function (BABYLON) {
  70430. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  70431. // All values and structures referenced from:
  70432. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  70433. var DDS_MAGIC = 0x20534444;
  70434. var
  70435. //DDSD_CAPS = 0x1,
  70436. //DDSD_HEIGHT = 0x2,
  70437. //DDSD_WIDTH = 0x4,
  70438. //DDSD_PITCH = 0x8,
  70439. //DDSD_PIXELFORMAT = 0x1000,
  70440. DDSD_MIPMAPCOUNT = 0x20000;
  70441. //DDSD_LINEARSIZE = 0x80000,
  70442. //DDSD_DEPTH = 0x800000;
  70443. // var DDSCAPS_COMPLEX = 0x8,
  70444. // DDSCAPS_MIPMAP = 0x400000,
  70445. // DDSCAPS_TEXTURE = 0x1000;
  70446. var DDSCAPS2_CUBEMAP = 0x200;
  70447. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  70448. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  70449. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  70450. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  70451. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  70452. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  70453. // DDSCAPS2_VOLUME = 0x200000;
  70454. var
  70455. //DDPF_ALPHAPIXELS = 0x1,
  70456. //DDPF_ALPHA = 0x2,
  70457. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  70458. //DDPF_YUV = 0x200,
  70459. DDPF_LUMINANCE = 0x20000;
  70460. function FourCCToInt32(value) {
  70461. return value.charCodeAt(0) +
  70462. (value.charCodeAt(1) << 8) +
  70463. (value.charCodeAt(2) << 16) +
  70464. (value.charCodeAt(3) << 24);
  70465. }
  70466. function Int32ToFourCC(value) {
  70467. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  70468. }
  70469. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  70470. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  70471. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  70472. var FOURCC_DX10 = FourCCToInt32("DX10");
  70473. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  70474. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  70475. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  70476. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  70477. var headerLengthInt = 31; // The header length in 32 bit ints
  70478. // Offsets into the header array
  70479. var off_magic = 0;
  70480. var off_size = 1;
  70481. var off_flags = 2;
  70482. var off_height = 3;
  70483. var off_width = 4;
  70484. var off_mipmapCount = 7;
  70485. var off_pfFlags = 20;
  70486. var off_pfFourCC = 21;
  70487. var off_RGBbpp = 22;
  70488. // var off_RMask = 23;
  70489. // var off_GMask = 24;
  70490. // var off_BMask = 25;
  70491. // var off_AMask = 26;
  70492. // var off_caps1 = 27;
  70493. var off_caps2 = 28;
  70494. // var off_caps3 = 29;
  70495. // var off_caps4 = 30;
  70496. var off_dxgiFormat = 32;
  70497. ;
  70498. var DDSTools = /** @class */ (function () {
  70499. function DDSTools() {
  70500. }
  70501. DDSTools.GetDDSInfo = function (arrayBuffer) {
  70502. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70503. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  70504. var mipmapCount = 1;
  70505. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  70506. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70507. }
  70508. var fourCC = header[off_pfFourCC];
  70509. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  70510. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70511. switch (fourCC) {
  70512. case FOURCC_D3DFMT_R16G16B16A16F:
  70513. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70514. break;
  70515. case FOURCC_D3DFMT_R32G32B32A32F:
  70516. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70517. break;
  70518. case FOURCC_DX10:
  70519. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  70520. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70521. break;
  70522. }
  70523. }
  70524. return {
  70525. width: header[off_width],
  70526. height: header[off_height],
  70527. mipmapCount: mipmapCount,
  70528. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  70529. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  70530. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  70531. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  70532. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  70533. dxgiFormat: dxgiFormat,
  70534. textureType: textureType
  70535. };
  70536. };
  70537. DDSTools._ToHalfFloat = function (value) {
  70538. if (!DDSTools._FloatView) {
  70539. DDSTools._FloatView = new Float32Array(1);
  70540. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  70541. }
  70542. DDSTools._FloatView[0] = value;
  70543. var x = DDSTools._Int32View[0];
  70544. var bits = (x >> 16) & 0x8000; /* Get the sign */
  70545. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  70546. var e = (x >> 23) & 0xff; /* Using int is faster here */
  70547. /* If zero, or denormal, or exponent underflows too much for a denormal
  70548. * half, return signed zero. */
  70549. if (e < 103) {
  70550. return bits;
  70551. }
  70552. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  70553. if (e > 142) {
  70554. bits |= 0x7c00;
  70555. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  70556. * not Inf, so make sure we set one mantissa bit too. */
  70557. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  70558. return bits;
  70559. }
  70560. /* If exponent underflows but not too much, return a denormal */
  70561. if (e < 113) {
  70562. m |= 0x0800;
  70563. /* Extra rounding may overflow and set mantissa to 0 and exponent
  70564. * to 1, which is OK. */
  70565. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  70566. return bits;
  70567. }
  70568. bits |= ((e - 112) << 10) | (m >> 1);
  70569. bits += m & 1;
  70570. return bits;
  70571. };
  70572. DDSTools._FromHalfFloat = function (value) {
  70573. var s = (value & 0x8000) >> 15;
  70574. var e = (value & 0x7C00) >> 10;
  70575. var f = value & 0x03FF;
  70576. if (e === 0) {
  70577. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  70578. }
  70579. else if (e == 0x1F) {
  70580. return f ? NaN : ((s ? -1 : 1) * Infinity);
  70581. }
  70582. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  70583. };
  70584. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70585. var destArray = new Float32Array(dataLength);
  70586. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70587. var index = 0;
  70588. for (var y = 0; y < height; y++) {
  70589. for (var x = 0; x < width; x++) {
  70590. var srcPos = (x + y * width) * 4;
  70591. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  70592. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  70593. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  70594. if (DDSTools.StoreLODInAlphaChannel) {
  70595. destArray[index + 3] = lod;
  70596. }
  70597. else {
  70598. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  70599. }
  70600. index += 4;
  70601. }
  70602. }
  70603. return destArray;
  70604. };
  70605. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70606. if (DDSTools.StoreLODInAlphaChannel) {
  70607. var destArray = new Uint16Array(dataLength);
  70608. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70609. var index = 0;
  70610. for (var y = 0; y < height; y++) {
  70611. for (var x = 0; x < width; x++) {
  70612. var srcPos = (x + y * width) * 4;
  70613. destArray[index] = srcData[srcPos];
  70614. destArray[index + 1] = srcData[srcPos + 1];
  70615. destArray[index + 2] = srcData[srcPos + 2];
  70616. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  70617. index += 4;
  70618. }
  70619. }
  70620. return destArray;
  70621. }
  70622. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  70623. };
  70624. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70625. if (DDSTools.StoreLODInAlphaChannel) {
  70626. var destArray = new Float32Array(dataLength);
  70627. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70628. var index = 0;
  70629. for (var y = 0; y < height; y++) {
  70630. for (var x = 0; x < width; x++) {
  70631. var srcPos = (x + y * width) * 4;
  70632. destArray[index] = srcData[srcPos];
  70633. destArray[index + 1] = srcData[srcPos + 1];
  70634. destArray[index + 2] = srcData[srcPos + 2];
  70635. destArray[index + 3] = lod;
  70636. index += 4;
  70637. }
  70638. }
  70639. return destArray;
  70640. }
  70641. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  70642. };
  70643. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70644. var destArray = new Uint8Array(dataLength);
  70645. var srcData = new Float32Array(arrayBuffer, dataOffset);
  70646. var index = 0;
  70647. for (var y = 0; y < height; y++) {
  70648. for (var x = 0; x < width; x++) {
  70649. var srcPos = (x + y * width) * 4;
  70650. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  70651. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  70652. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  70653. if (DDSTools.StoreLODInAlphaChannel) {
  70654. destArray[index + 3] = lod;
  70655. }
  70656. else {
  70657. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  70658. }
  70659. index += 4;
  70660. }
  70661. }
  70662. return destArray;
  70663. };
  70664. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  70665. var destArray = new Uint8Array(dataLength);
  70666. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  70667. var index = 0;
  70668. for (var y = 0; y < height; y++) {
  70669. for (var x = 0; x < width; x++) {
  70670. var srcPos = (x + y * width) * 4;
  70671. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  70672. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  70673. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  70674. if (DDSTools.StoreLODInAlphaChannel) {
  70675. destArray[index + 3] = lod;
  70676. }
  70677. else {
  70678. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  70679. }
  70680. index += 4;
  70681. }
  70682. }
  70683. return destArray;
  70684. };
  70685. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70686. var byteArray = new Uint8Array(dataLength);
  70687. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70688. var index = 0;
  70689. for (var y = 0; y < height; y++) {
  70690. for (var x = 0; x < width; x++) {
  70691. var srcPos = (x + y * width) * 4;
  70692. byteArray[index] = srcData[srcPos + 2];
  70693. byteArray[index + 1] = srcData[srcPos + 1];
  70694. byteArray[index + 2] = srcData[srcPos];
  70695. byteArray[index + 3] = srcData[srcPos + 3];
  70696. index += 4;
  70697. }
  70698. }
  70699. return byteArray;
  70700. };
  70701. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70702. var byteArray = new Uint8Array(dataLength);
  70703. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70704. var index = 0;
  70705. for (var y = 0; y < height; y++) {
  70706. for (var x = 0; x < width; x++) {
  70707. var srcPos = (x + y * width) * 3;
  70708. byteArray[index] = srcData[srcPos + 2];
  70709. byteArray[index + 1] = srcData[srcPos + 1];
  70710. byteArray[index + 2] = srcData[srcPos];
  70711. index += 3;
  70712. }
  70713. }
  70714. return byteArray;
  70715. };
  70716. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70717. var byteArray = new Uint8Array(dataLength);
  70718. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70719. var index = 0;
  70720. for (var y = 0; y < height; y++) {
  70721. for (var x = 0; x < width; x++) {
  70722. var srcPos = (x + y * width);
  70723. byteArray[index] = srcData[srcPos];
  70724. index++;
  70725. }
  70726. }
  70727. return byteArray;
  70728. };
  70729. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70730. if (lodIndex === void 0) { lodIndex = -1; }
  70731. var ext = engine.getCaps().s3tc;
  70732. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70733. var fourCC, width, height, dataLength = 0, dataOffset;
  70734. var byteArray, mipmapCount, mip;
  70735. var internalFormat = 0;
  70736. var format = 0;
  70737. var blockBytes = 1;
  70738. if (header[off_magic] !== DDS_MAGIC) {
  70739. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70740. return;
  70741. }
  70742. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70743. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70744. return;
  70745. }
  70746. if (info.isCompressed && !ext) {
  70747. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70748. return;
  70749. }
  70750. var bpp = header[off_RGBbpp];
  70751. dataOffset = header[off_size] + 4;
  70752. var computeFormats = false;
  70753. if (info.isFourCC) {
  70754. fourCC = header[off_pfFourCC];
  70755. switch (fourCC) {
  70756. case FOURCC_DXT1:
  70757. blockBytes = 8;
  70758. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70759. break;
  70760. case FOURCC_DXT3:
  70761. blockBytes = 16;
  70762. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70763. break;
  70764. case FOURCC_DXT5:
  70765. blockBytes = 16;
  70766. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70767. break;
  70768. case FOURCC_D3DFMT_R16G16B16A16F:
  70769. computeFormats = true;
  70770. break;
  70771. case FOURCC_D3DFMT_R32G32B32A32F:
  70772. computeFormats = true;
  70773. break;
  70774. case FOURCC_DX10:
  70775. // There is an additionnal header so dataOffset need to be changed
  70776. dataOffset += 5 * 4; // 5 uints
  70777. var supported = false;
  70778. switch (info.dxgiFormat) {
  70779. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70780. computeFormats = true;
  70781. supported = true;
  70782. break;
  70783. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70784. info.isRGB = true;
  70785. info.isFourCC = false;
  70786. bpp = 32;
  70787. supported = true;
  70788. break;
  70789. }
  70790. if (supported) {
  70791. break;
  70792. }
  70793. default:
  70794. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70795. return;
  70796. }
  70797. }
  70798. if (computeFormats) {
  70799. format = engine._getWebGLTextureType(info.textureType);
  70800. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70801. }
  70802. mipmapCount = 1;
  70803. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70804. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70805. }
  70806. for (var face = 0; face < faces; face++) {
  70807. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70808. width = header[off_width];
  70809. height = header[off_height];
  70810. for (mip = 0; mip < mipmapCount; ++mip) {
  70811. if (lodIndex === -1 || lodIndex === mip) {
  70812. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70813. var i = (lodIndex === -1) ? mip : 0;
  70814. if (!info.isCompressed && info.isFourCC) {
  70815. dataLength = width * height * 4;
  70816. var floatArray = null;
  70817. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70818. if (bpp === 128) {
  70819. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70820. }
  70821. else if (bpp === 64) {
  70822. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70823. }
  70824. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70825. format = engine._getWebGLTextureType(info.textureType);
  70826. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70827. }
  70828. else {
  70829. if (bpp === 128) {
  70830. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70831. }
  70832. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70833. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70834. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70835. format = engine._getWebGLTextureType(info.textureType);
  70836. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70837. }
  70838. else {
  70839. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70840. }
  70841. }
  70842. if (floatArray) {
  70843. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  70844. }
  70845. }
  70846. else if (info.isRGB) {
  70847. if (bpp === 24) {
  70848. dataLength = width * height * 3;
  70849. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70850. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  70851. }
  70852. else {
  70853. dataLength = width * height * 4;
  70854. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70855. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  70856. }
  70857. }
  70858. else if (info.isLuminance) {
  70859. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  70860. var unpaddedRowSize = width;
  70861. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  70862. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  70863. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70864. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  70865. }
  70866. else {
  70867. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  70868. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  70869. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  70870. }
  70871. }
  70872. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  70873. width *= 0.5;
  70874. height *= 0.5;
  70875. width = Math.max(1.0, width);
  70876. height = Math.max(1.0, height);
  70877. }
  70878. if (currentFace !== undefined) {
  70879. // Loading a single face
  70880. break;
  70881. }
  70882. }
  70883. };
  70884. DDSTools.StoreLODInAlphaChannel = false;
  70885. return DDSTools;
  70886. }());
  70887. BABYLON.DDSTools = DDSTools;
  70888. })(BABYLON || (BABYLON = {}));
  70889. //# sourceMappingURL=babylon.dds.js.map
  70890. var BABYLON;
  70891. (function (BABYLON) {
  70892. /**
  70893. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  70894. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  70895. */
  70896. var KhronosTextureContainer = /** @class */ (function () {
  70897. /**
  70898. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  70899. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  70900. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  70901. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  70902. */
  70903. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  70904. this.arrayBuffer = arrayBuffer;
  70905. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  70906. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  70907. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  70908. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  70909. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  70910. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  70911. BABYLON.Tools.Error("texture missing KTX identifier");
  70912. return;
  70913. }
  70914. // load the reset of the header in native 32 bit int
  70915. var header = new Int32Array(this.arrayBuffer, 12, 13);
  70916. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  70917. var oppositeEndianess = header[0] === 0x01020304;
  70918. // read all the header elements in order they exist in the file, without modification (sans endainness)
  70919. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  70920. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  70921. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  70922. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  70923. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  70924. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  70925. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  70926. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  70927. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  70928. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  70929. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  70930. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  70931. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  70932. if (this.glType !== 0) {
  70933. BABYLON.Tools.Error("only compressed formats currently supported");
  70934. return;
  70935. }
  70936. else {
  70937. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  70938. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  70939. }
  70940. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  70941. BABYLON.Tools.Error("only 2D textures currently supported");
  70942. return;
  70943. }
  70944. if (this.numberOfArrayElements !== 0) {
  70945. BABYLON.Tools.Error("texture arrays not currently supported");
  70946. return;
  70947. }
  70948. if (this.numberOfFaces !== facesExpected) {
  70949. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  70950. return;
  70951. }
  70952. // we now have a completely validated file, so could use existence of loadType as success
  70953. // would need to make this more elaborate & adjust checks above to support more than one load type
  70954. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  70955. }
  70956. // not as fast hardware based, but will probably never need to use
  70957. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  70958. return ((val & 0xFF) << 24)
  70959. | ((val & 0xFF00) << 8)
  70960. | ((val >> 8) & 0xFF00)
  70961. | ((val >> 24) & 0xFF);
  70962. };
  70963. /**
  70964. * It is assumed that the texture has already been created & is currently bound
  70965. */
  70966. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  70967. switch (this.loadType) {
  70968. case KhronosTextureContainer.COMPRESSED_2D:
  70969. this._upload2DCompressedLevels(gl, loadMipmaps);
  70970. break;
  70971. case KhronosTextureContainer.TEX_2D:
  70972. case KhronosTextureContainer.COMPRESSED_3D:
  70973. case KhronosTextureContainer.TEX_3D:
  70974. }
  70975. };
  70976. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  70977. // initialize width & height for level 1
  70978. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  70979. var width = this.pixelWidth;
  70980. var height = this.pixelHeight;
  70981. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  70982. for (var level = 0; level < mipmapCount; level++) {
  70983. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  70984. for (var face = 0; face < this.numberOfFaces; face++) {
  70985. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  70986. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  70987. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  70988. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  70989. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  70990. }
  70991. width = Math.max(1.0, width * 0.5);
  70992. height = Math.max(1.0, height * 0.5);
  70993. }
  70994. };
  70995. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  70996. // load types
  70997. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  70998. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  70999. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  71000. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  71001. return KhronosTextureContainer;
  71002. }());
  71003. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  71004. })(BABYLON || (BABYLON = {}));
  71005. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  71006. var BABYLON;
  71007. (function (BABYLON) {
  71008. var Debug = /** @class */ (function () {
  71009. function Debug() {
  71010. }
  71011. Debug.AxesViewer = /** @class */ (function () {
  71012. function AxesViewer(scene, scaleLines) {
  71013. if (scaleLines === void 0) { scaleLines = 1; }
  71014. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71015. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71016. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71017. this.scaleLines = 1;
  71018. this.scaleLines = scaleLines;
  71019. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  71020. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  71021. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  71022. this._xmesh.renderingGroupId = 2;
  71023. this._ymesh.renderingGroupId = 2;
  71024. this._zmesh.renderingGroupId = 2;
  71025. this._xmesh.material.checkReadyOnlyOnce = true;
  71026. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  71027. this._ymesh.material.checkReadyOnlyOnce = true;
  71028. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  71029. this._zmesh.material.checkReadyOnlyOnce = true;
  71030. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  71031. this.scene = scene;
  71032. }
  71033. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  71034. var scaleLines = this.scaleLines;
  71035. if (this._xmesh) {
  71036. this._xmesh.position.copyFrom(position);
  71037. }
  71038. if (this._ymesh) {
  71039. this._ymesh.position.copyFrom(position);
  71040. }
  71041. if (this._zmesh) {
  71042. this._zmesh.position.copyFrom(position);
  71043. }
  71044. var point2 = this._xline[1];
  71045. point2.x = xaxis.x * scaleLines;
  71046. point2.y = xaxis.y * scaleLines;
  71047. point2.z = xaxis.z * scaleLines;
  71048. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  71049. point2 = this._yline[1];
  71050. point2.x = yaxis.x * scaleLines;
  71051. point2.y = yaxis.y * scaleLines;
  71052. point2.z = yaxis.z * scaleLines;
  71053. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  71054. point2 = this._zline[1];
  71055. point2.x = zaxis.x * scaleLines;
  71056. point2.y = zaxis.y * scaleLines;
  71057. point2.z = zaxis.z * scaleLines;
  71058. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  71059. };
  71060. AxesViewer.prototype.dispose = function () {
  71061. if (this._xmesh) {
  71062. this._xmesh.dispose();
  71063. }
  71064. if (this._ymesh) {
  71065. this._ymesh.dispose();
  71066. }
  71067. if (this._zmesh) {
  71068. this._zmesh.dispose();
  71069. }
  71070. this._xmesh = null;
  71071. this._ymesh = null;
  71072. this._zmesh = null;
  71073. this.scene = null;
  71074. };
  71075. return AxesViewer;
  71076. }());
  71077. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  71078. __extends(BoneAxesViewer, _super);
  71079. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  71080. if (scaleLines === void 0) { scaleLines = 1; }
  71081. var _this = _super.call(this, scene, scaleLines) || this;
  71082. _this.pos = BABYLON.Vector3.Zero();
  71083. _this.xaxis = BABYLON.Vector3.Zero();
  71084. _this.yaxis = BABYLON.Vector3.Zero();
  71085. _this.zaxis = BABYLON.Vector3.Zero();
  71086. _this.mesh = mesh;
  71087. _this.bone = bone;
  71088. return _this;
  71089. }
  71090. BoneAxesViewer.prototype.update = function () {
  71091. if (!this.mesh || !this.bone) {
  71092. return;
  71093. }
  71094. var bone = this.bone;
  71095. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  71096. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  71097. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  71098. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  71099. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  71100. };
  71101. BoneAxesViewer.prototype.dispose = function () {
  71102. if (this.mesh) {
  71103. this.mesh = null;
  71104. this.bone = null;
  71105. _super.prototype.dispose.call(this);
  71106. }
  71107. };
  71108. return BoneAxesViewer;
  71109. }(Debug.AxesViewer));
  71110. Debug.PhysicsViewer = /** @class */ (function () {
  71111. function PhysicsViewer(scene) {
  71112. this._impostors = [];
  71113. this._meshes = [];
  71114. this._numMeshes = 0;
  71115. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71116. var physicEngine = this._scene.getPhysicsEngine();
  71117. if (physicEngine) {
  71118. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  71119. }
  71120. }
  71121. PhysicsViewer.prototype._updateDebugMeshes = function () {
  71122. var plugin = this._physicsEnginePlugin;
  71123. for (var i = 0; i < this._numMeshes; i++) {
  71124. var impostor = this._impostors[i];
  71125. if (!impostor) {
  71126. continue;
  71127. }
  71128. if (impostor.isDisposed) {
  71129. this.hideImpostor(this._impostors[i--]);
  71130. }
  71131. else {
  71132. var mesh = this._meshes[i];
  71133. if (mesh && plugin) {
  71134. plugin.syncMeshWithImpostor(mesh, impostor);
  71135. }
  71136. }
  71137. }
  71138. };
  71139. PhysicsViewer.prototype.showImpostor = function (impostor) {
  71140. if (!this._scene) {
  71141. return;
  71142. }
  71143. for (var i = 0; i < this._numMeshes; i++) {
  71144. if (this._impostors[i] == impostor) {
  71145. return;
  71146. }
  71147. }
  71148. var debugMesh = this._getDebugMesh(impostor, this._scene);
  71149. if (debugMesh) {
  71150. this._impostors[this._numMeshes] = impostor;
  71151. this._meshes[this._numMeshes] = debugMesh;
  71152. if (this._numMeshes === 0) {
  71153. this._renderFunction = this._updateDebugMeshes.bind(this);
  71154. this._scene.registerBeforeRender(this._renderFunction);
  71155. }
  71156. this._numMeshes++;
  71157. }
  71158. };
  71159. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  71160. if (!impostor || !this._scene) {
  71161. return;
  71162. }
  71163. var removed = false;
  71164. for (var i = 0; i < this._numMeshes; i++) {
  71165. if (this._impostors[i] == impostor) {
  71166. var mesh = this._meshes[i];
  71167. if (!mesh) {
  71168. continue;
  71169. }
  71170. this._scene.removeMesh(mesh);
  71171. mesh.dispose();
  71172. this._numMeshes--;
  71173. if (this._numMeshes > 0) {
  71174. this._meshes[i] = this._meshes[this._numMeshes];
  71175. this._impostors[i] = this._impostors[this._numMeshes];
  71176. this._meshes[this._numMeshes] = null;
  71177. this._impostors[this._numMeshes] = null;
  71178. }
  71179. else {
  71180. this._meshes[0] = null;
  71181. this._impostors[0] = null;
  71182. }
  71183. removed = true;
  71184. break;
  71185. }
  71186. }
  71187. if (removed && this._numMeshes === 0) {
  71188. this._scene.unregisterBeforeRender(this._renderFunction);
  71189. }
  71190. };
  71191. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  71192. if (!this._debugMaterial) {
  71193. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  71194. this._debugMaterial.wireframe = true;
  71195. }
  71196. return this._debugMaterial;
  71197. };
  71198. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  71199. if (!this._debugBoxMesh) {
  71200. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  71201. this._debugBoxMesh.renderingGroupId = 1;
  71202. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71203. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  71204. scene.removeMesh(this._debugBoxMesh);
  71205. }
  71206. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  71207. };
  71208. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  71209. if (!this._debugSphereMesh) {
  71210. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  71211. this._debugSphereMesh.renderingGroupId = 1;
  71212. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  71213. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  71214. scene.removeMesh(this._debugSphereMesh);
  71215. }
  71216. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  71217. };
  71218. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  71219. var mesh = null;
  71220. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  71221. mesh = this._getDebugBoxMesh(scene);
  71222. impostor.getBoxSizeToRef(mesh.scaling);
  71223. }
  71224. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  71225. mesh = this._getDebugSphereMesh(scene);
  71226. var radius = impostor.getRadius();
  71227. mesh.scaling.x = radius * 2;
  71228. mesh.scaling.y = radius * 2;
  71229. mesh.scaling.z = radius * 2;
  71230. }
  71231. return mesh;
  71232. };
  71233. PhysicsViewer.prototype.dispose = function () {
  71234. for (var i = 0; i < this._numMeshes; i++) {
  71235. this.hideImpostor(this._impostors[i]);
  71236. }
  71237. if (this._debugBoxMesh) {
  71238. this._debugBoxMesh.dispose();
  71239. }
  71240. if (this._debugSphereMesh) {
  71241. this._debugSphereMesh.dispose();
  71242. }
  71243. if (this._debugMaterial) {
  71244. this._debugMaterial.dispose();
  71245. }
  71246. this._impostors.length = 0;
  71247. this._scene = null;
  71248. this._physicsEnginePlugin = null;
  71249. };
  71250. return PhysicsViewer;
  71251. }());
  71252. Debug.SkeletonViewer = /** @class */ (function () {
  71253. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  71254. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  71255. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  71256. this.skeleton = skeleton;
  71257. this.mesh = mesh;
  71258. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  71259. this.renderingGroupId = renderingGroupId;
  71260. this.color = BABYLON.Color3.White();
  71261. this._debugLines = new Array();
  71262. this._isEnabled = false;
  71263. this._scene = scene;
  71264. this.update();
  71265. this._renderFunction = this.update.bind(this);
  71266. }
  71267. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  71268. get: function () {
  71269. return this._isEnabled;
  71270. },
  71271. set: function (value) {
  71272. if (this._isEnabled === value) {
  71273. return;
  71274. }
  71275. this._isEnabled = value;
  71276. if (value) {
  71277. this._scene.registerBeforeRender(this._renderFunction);
  71278. }
  71279. else {
  71280. this._scene.unregisterBeforeRender(this._renderFunction);
  71281. }
  71282. },
  71283. enumerable: true,
  71284. configurable: true
  71285. });
  71286. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  71287. if (x === void 0) { x = 0; }
  71288. if (y === void 0) { y = 0; }
  71289. if (z === void 0) { z = 0; }
  71290. var tmat = BABYLON.Tmp.Matrix[0];
  71291. var parentBone = bone.getParent();
  71292. tmat.copyFrom(bone.getLocalMatrix());
  71293. if (x !== 0 || y !== 0 || z !== 0) {
  71294. var tmat2 = BABYLON.Tmp.Matrix[1];
  71295. BABYLON.Matrix.IdentityToRef(tmat2);
  71296. tmat2.m[12] = x;
  71297. tmat2.m[13] = y;
  71298. tmat2.m[14] = z;
  71299. tmat2.multiplyToRef(tmat, tmat);
  71300. }
  71301. if (parentBone) {
  71302. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  71303. }
  71304. tmat.multiplyToRef(meshMat, tmat);
  71305. position.x = tmat.m[12];
  71306. position.y = tmat.m[13];
  71307. position.z = tmat.m[14];
  71308. };
  71309. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  71310. var len = bones.length;
  71311. var meshPos = this.mesh.position;
  71312. for (var i = 0; i < len; i++) {
  71313. var bone = bones[i];
  71314. var points = this._debugLines[i];
  71315. if (!points) {
  71316. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71317. this._debugLines[i] = points;
  71318. }
  71319. this._getBonePosition(points[0], bone, meshMat);
  71320. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  71321. points[0].subtractInPlace(meshPos);
  71322. points[1].subtractInPlace(meshPos);
  71323. }
  71324. };
  71325. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  71326. var len = bones.length;
  71327. var boneNum = 0;
  71328. var meshPos = this.mesh.position;
  71329. for (var i = len - 1; i >= 0; i--) {
  71330. var childBone = bones[i];
  71331. var parentBone = childBone.getParent();
  71332. if (!parentBone) {
  71333. continue;
  71334. }
  71335. var points = this._debugLines[boneNum];
  71336. if (!points) {
  71337. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  71338. this._debugLines[boneNum] = points;
  71339. }
  71340. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  71341. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  71342. points[0].subtractInPlace(meshPos);
  71343. points[1].subtractInPlace(meshPos);
  71344. boneNum++;
  71345. }
  71346. };
  71347. SkeletonViewer.prototype.update = function () {
  71348. if (this.autoUpdateBonesMatrices) {
  71349. this.skeleton.computeAbsoluteTransforms();
  71350. }
  71351. if (this.skeleton.bones[0].length === undefined) {
  71352. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71353. }
  71354. else {
  71355. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  71356. }
  71357. if (!this._debugMesh) {
  71358. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  71359. this._debugMesh.renderingGroupId = this.renderingGroupId;
  71360. }
  71361. else {
  71362. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  71363. }
  71364. this._debugMesh.position.copyFrom(this.mesh.position);
  71365. this._debugMesh.color = this.color;
  71366. };
  71367. SkeletonViewer.prototype.dispose = function () {
  71368. if (this._debugMesh) {
  71369. this.isEnabled = false;
  71370. this._debugMesh.dispose();
  71371. this._debugMesh = null;
  71372. }
  71373. };
  71374. return SkeletonViewer;
  71375. }());
  71376. return Debug;
  71377. }());
  71378. BABYLON.Debug = Debug;
  71379. })(BABYLON || (BABYLON = {}));
  71380. //# sourceMappingURL=babylon.debugModules.js.map
  71381. var BABYLON;
  71382. (function (BABYLON) {
  71383. var RayHelper = /** @class */ (function () {
  71384. function RayHelper(ray) {
  71385. this.ray = ray;
  71386. }
  71387. RayHelper.CreateAndShow = function (ray, scene, color) {
  71388. var helper = new RayHelper(ray);
  71389. helper.show(scene, color);
  71390. return helper;
  71391. };
  71392. RayHelper.prototype.show = function (scene, color) {
  71393. if (!this._renderFunction && this.ray) {
  71394. var ray = this.ray;
  71395. this._renderFunction = this._render.bind(this);
  71396. this._scene = scene;
  71397. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  71398. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  71399. if (this._renderFunction) {
  71400. this._scene.registerBeforeRender(this._renderFunction);
  71401. }
  71402. }
  71403. if (color && this._renderLine) {
  71404. this._renderLine.color.copyFrom(color);
  71405. }
  71406. };
  71407. RayHelper.prototype.hide = function () {
  71408. if (this._renderFunction && this._scene) {
  71409. this._scene.unregisterBeforeRender(this._renderFunction);
  71410. this._scene = null;
  71411. this._renderFunction = null;
  71412. if (this._renderLine) {
  71413. this._renderLine.dispose();
  71414. this._renderLine = null;
  71415. }
  71416. this._renderPoints = [];
  71417. }
  71418. };
  71419. RayHelper.prototype._render = function () {
  71420. var ray = this.ray;
  71421. if (!ray) {
  71422. return;
  71423. }
  71424. var point = this._renderPoints[1];
  71425. var len = Math.min(ray.length, 1000000);
  71426. point.copyFrom(ray.direction);
  71427. point.scaleInPlace(len);
  71428. point.addInPlace(ray.origin);
  71429. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  71430. };
  71431. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  71432. this._attachedToMesh = mesh;
  71433. var ray = this.ray;
  71434. if (!ray) {
  71435. return;
  71436. }
  71437. if (!ray.direction) {
  71438. ray.direction = BABYLON.Vector3.Zero();
  71439. }
  71440. if (!ray.origin) {
  71441. ray.origin = BABYLON.Vector3.Zero();
  71442. }
  71443. if (length) {
  71444. ray.length = length;
  71445. }
  71446. if (!meshSpaceOrigin) {
  71447. meshSpaceOrigin = BABYLON.Vector3.Zero();
  71448. }
  71449. if (!meshSpaceDirection) {
  71450. // -1 so that this will work with Mesh.lookAt
  71451. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  71452. }
  71453. if (!this._meshSpaceDirection) {
  71454. this._meshSpaceDirection = meshSpaceDirection.clone();
  71455. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  71456. }
  71457. else {
  71458. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  71459. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  71460. }
  71461. if (!this._updateToMeshFunction) {
  71462. this._updateToMeshFunction = this._updateToMesh.bind(this);
  71463. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  71464. }
  71465. this._updateToMesh();
  71466. };
  71467. RayHelper.prototype.detachFromMesh = function () {
  71468. if (this._attachedToMesh) {
  71469. if (this._updateToMeshFunction) {
  71470. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  71471. }
  71472. this._attachedToMesh = null;
  71473. this._updateToMeshFunction = null;
  71474. }
  71475. };
  71476. RayHelper.prototype._updateToMesh = function () {
  71477. var ray = this.ray;
  71478. if (!this._attachedToMesh || !ray) {
  71479. return;
  71480. }
  71481. if (this._attachedToMesh._isDisposed) {
  71482. this.detachFromMesh();
  71483. return;
  71484. }
  71485. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  71486. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  71487. };
  71488. RayHelper.prototype.dispose = function () {
  71489. this.hide();
  71490. this.detachFromMesh();
  71491. this.ray = null;
  71492. };
  71493. return RayHelper;
  71494. }());
  71495. BABYLON.RayHelper = RayHelper;
  71496. })(BABYLON || (BABYLON = {}));
  71497. //# sourceMappingURL=babylon.rayHelper.js.map
  71498. var BABYLON;
  71499. (function (BABYLON) {
  71500. // load the inspector using require, if not present in the global namespace.
  71501. var DebugLayer = /** @class */ (function () {
  71502. function DebugLayer(scene) {
  71503. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71504. this._scene = scene;
  71505. // load inspector using require, if it doesn't exist on the global namespace.
  71506. }
  71507. /** Creates the inspector window. */
  71508. DebugLayer.prototype._createInspector = function (config) {
  71509. if (config === void 0) { config = {}; }
  71510. var popup = config.popup || false;
  71511. var initialTab = config.initialTab || 0;
  71512. var parentElement = config.parentElement || null;
  71513. if (!this._inspector) {
  71514. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  71515. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  71516. } // else nothing to do,; instance is already existing
  71517. };
  71518. DebugLayer.prototype.isVisible = function () {
  71519. if (!this._inspector) {
  71520. return false;
  71521. }
  71522. return true;
  71523. };
  71524. DebugLayer.prototype.hide = function () {
  71525. if (this._inspector) {
  71526. try {
  71527. this._inspector.dispose();
  71528. }
  71529. catch (e) {
  71530. // If the inspector has been removed directly from the inspector tool
  71531. }
  71532. this._inspector = null;
  71533. }
  71534. };
  71535. DebugLayer.prototype.show = function (config) {
  71536. if (config === void 0) { config = {}; }
  71537. if (typeof this.BJSINSPECTOR == 'undefined') {
  71538. // Load inspector and add it to the DOM
  71539. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  71540. }
  71541. else {
  71542. // Otherwise creates the inspector
  71543. this._createInspector(config);
  71544. }
  71545. };
  71546. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  71547. return DebugLayer;
  71548. }());
  71549. BABYLON.DebugLayer = DebugLayer;
  71550. })(BABYLON || (BABYLON = {}));
  71551. //# sourceMappingURL=babylon.debugLayer.js.map
  71552. var BABYLON;
  71553. (function (BABYLON) {
  71554. var BoundingBoxRenderer = /** @class */ (function () {
  71555. function BoundingBoxRenderer(scene) {
  71556. this.frontColor = new BABYLON.Color3(1, 1, 1);
  71557. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  71558. this.showBackLines = true;
  71559. this.renderList = new BABYLON.SmartArray(32);
  71560. this._vertexBuffers = {};
  71561. this._scene = scene;
  71562. }
  71563. BoundingBoxRenderer.prototype._prepareRessources = function () {
  71564. if (this._colorShader) {
  71565. return;
  71566. }
  71567. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  71568. attributes: [BABYLON.VertexBuffer.PositionKind],
  71569. uniforms: ["world", "viewProjection", "color"]
  71570. });
  71571. var engine = this._scene.getEngine();
  71572. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  71573. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  71574. this._createIndexBuffer();
  71575. };
  71576. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  71577. var engine = this._scene.getEngine();
  71578. 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]);
  71579. };
  71580. BoundingBoxRenderer.prototype._rebuild = function () {
  71581. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71582. if (vb) {
  71583. vb._rebuild();
  71584. }
  71585. this._createIndexBuffer();
  71586. };
  71587. BoundingBoxRenderer.prototype.reset = function () {
  71588. this.renderList.reset();
  71589. };
  71590. BoundingBoxRenderer.prototype.render = function () {
  71591. if (this.renderList.length === 0) {
  71592. return;
  71593. }
  71594. this._prepareRessources();
  71595. if (!this._colorShader.isReady()) {
  71596. return;
  71597. }
  71598. var engine = this._scene.getEngine();
  71599. engine.setDepthWrite(false);
  71600. this._colorShader._preBind();
  71601. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  71602. var boundingBox = this.renderList.data[boundingBoxIndex];
  71603. var min = boundingBox.minimum;
  71604. var max = boundingBox.maximum;
  71605. var diff = max.subtract(min);
  71606. var median = min.add(diff.scale(0.5));
  71607. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71608. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71609. .multiply(boundingBox.getWorldMatrix());
  71610. // VBOs
  71611. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71612. if (this.showBackLines) {
  71613. // Back
  71614. engine.setDepthFunctionToGreaterOrEqual();
  71615. this._scene.resetCachedMaterial();
  71616. this._colorShader.setColor4("color", this.backColor.toColor4());
  71617. this._colorShader.bind(worldMatrix);
  71618. // Draw order
  71619. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71620. }
  71621. // Front
  71622. engine.setDepthFunctionToLess();
  71623. this._scene.resetCachedMaterial();
  71624. this._colorShader.setColor4("color", this.frontColor.toColor4());
  71625. this._colorShader.bind(worldMatrix);
  71626. // Draw order
  71627. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  71628. }
  71629. this._colorShader.unbind();
  71630. engine.setDepthFunctionToLessOrEqual();
  71631. engine.setDepthWrite(true);
  71632. };
  71633. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  71634. this._prepareRessources();
  71635. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  71636. return;
  71637. }
  71638. var engine = this._scene.getEngine();
  71639. engine.setDepthWrite(false);
  71640. engine.setColorWrite(false);
  71641. this._colorShader._preBind();
  71642. var boundingBox = mesh._boundingInfo.boundingBox;
  71643. var min = boundingBox.minimum;
  71644. var max = boundingBox.maximum;
  71645. var diff = max.subtract(min);
  71646. var median = min.add(diff.scale(0.5));
  71647. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  71648. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  71649. .multiply(boundingBox.getWorldMatrix());
  71650. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  71651. engine.setDepthFunctionToLess();
  71652. this._scene.resetCachedMaterial();
  71653. this._colorShader.bind(worldMatrix);
  71654. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  71655. this._colorShader.unbind();
  71656. engine.setDepthFunctionToLessOrEqual();
  71657. engine.setDepthWrite(true);
  71658. engine.setColorWrite(true);
  71659. };
  71660. BoundingBoxRenderer.prototype.dispose = function () {
  71661. if (!this._colorShader) {
  71662. return;
  71663. }
  71664. this.renderList.dispose();
  71665. this._colorShader.dispose();
  71666. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71667. if (buffer) {
  71668. buffer.dispose();
  71669. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71670. }
  71671. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71672. };
  71673. return BoundingBoxRenderer;
  71674. }());
  71675. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71676. })(BABYLON || (BABYLON = {}));
  71677. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71678. var BABYLON;
  71679. (function (BABYLON) {
  71680. var MorphTarget = /** @class */ (function () {
  71681. function MorphTarget(name, influence) {
  71682. if (influence === void 0) { influence = 0; }
  71683. this.name = name;
  71684. this.animations = new Array();
  71685. this._positions = null;
  71686. this._normals = null;
  71687. this._tangents = null;
  71688. this.onInfluenceChanged = new BABYLON.Observable();
  71689. this.influence = influence;
  71690. }
  71691. Object.defineProperty(MorphTarget.prototype, "influence", {
  71692. get: function () {
  71693. return this._influence;
  71694. },
  71695. set: function (influence) {
  71696. if (this._influence === influence) {
  71697. return;
  71698. }
  71699. var previous = this._influence;
  71700. this._influence = influence;
  71701. if (this.onInfluenceChanged.hasObservers) {
  71702. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71703. }
  71704. },
  71705. enumerable: true,
  71706. configurable: true
  71707. });
  71708. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71709. get: function () {
  71710. return !!this._positions;
  71711. },
  71712. enumerable: true,
  71713. configurable: true
  71714. });
  71715. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71716. get: function () {
  71717. return !!this._normals;
  71718. },
  71719. enumerable: true,
  71720. configurable: true
  71721. });
  71722. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71723. get: function () {
  71724. return !!this._tangents;
  71725. },
  71726. enumerable: true,
  71727. configurable: true
  71728. });
  71729. MorphTarget.prototype.setPositions = function (data) {
  71730. this._positions = data;
  71731. };
  71732. MorphTarget.prototype.getPositions = function () {
  71733. return this._positions;
  71734. };
  71735. MorphTarget.prototype.setNormals = function (data) {
  71736. this._normals = data;
  71737. };
  71738. MorphTarget.prototype.getNormals = function () {
  71739. return this._normals;
  71740. };
  71741. MorphTarget.prototype.setTangents = function (data) {
  71742. this._tangents = data;
  71743. };
  71744. MorphTarget.prototype.getTangents = function () {
  71745. return this._tangents;
  71746. };
  71747. /**
  71748. * Serializes the current target into a Serialization object.
  71749. * Returns the serialized object.
  71750. */
  71751. MorphTarget.prototype.serialize = function () {
  71752. var serializationObject = {};
  71753. serializationObject.name = this.name;
  71754. serializationObject.influence = this.influence;
  71755. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71756. if (this.hasNormals) {
  71757. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71758. }
  71759. if (this.hasTangents) {
  71760. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71761. }
  71762. // Animations
  71763. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71764. return serializationObject;
  71765. };
  71766. // Statics
  71767. MorphTarget.Parse = function (serializationObject) {
  71768. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71769. result.setPositions(serializationObject.positions);
  71770. if (serializationObject.normals) {
  71771. result.setNormals(serializationObject.normals);
  71772. }
  71773. if (serializationObject.tangents) {
  71774. result.setTangents(serializationObject.tangents);
  71775. }
  71776. // Animations
  71777. if (serializationObject.animations) {
  71778. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71779. var parsedAnimation = serializationObject.animations[animationIndex];
  71780. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71781. }
  71782. }
  71783. return result;
  71784. };
  71785. MorphTarget.FromMesh = function (mesh, name, influence) {
  71786. if (!name) {
  71787. name = mesh.name;
  71788. }
  71789. var result = new MorphTarget(name, influence);
  71790. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71791. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71792. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71793. }
  71794. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71795. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71796. }
  71797. return result;
  71798. };
  71799. return MorphTarget;
  71800. }());
  71801. BABYLON.MorphTarget = MorphTarget;
  71802. })(BABYLON || (BABYLON = {}));
  71803. //# sourceMappingURL=babylon.morphTarget.js.map
  71804. var BABYLON;
  71805. (function (BABYLON) {
  71806. var MorphTargetManager = /** @class */ (function () {
  71807. function MorphTargetManager(scene) {
  71808. if (scene === void 0) { scene = null; }
  71809. this._targets = new Array();
  71810. this._targetObservable = new Array();
  71811. this._activeTargets = new BABYLON.SmartArray(16);
  71812. this._supportsNormals = false;
  71813. this._supportsTangents = false;
  71814. this._vertexCount = 0;
  71815. this._uniqueId = 0;
  71816. this._tempInfluences = new Array();
  71817. if (!scene) {
  71818. scene = BABYLON.Engine.LastCreatedScene;
  71819. }
  71820. this._scene = scene;
  71821. if (this._scene) {
  71822. this._scene.morphTargetManagers.push(this);
  71823. this._uniqueId = this._scene.getUniqueId();
  71824. }
  71825. }
  71826. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71827. get: function () {
  71828. return this._uniqueId;
  71829. },
  71830. enumerable: true,
  71831. configurable: true
  71832. });
  71833. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  71834. get: function () {
  71835. return this._vertexCount;
  71836. },
  71837. enumerable: true,
  71838. configurable: true
  71839. });
  71840. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  71841. get: function () {
  71842. return this._supportsNormals;
  71843. },
  71844. enumerable: true,
  71845. configurable: true
  71846. });
  71847. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  71848. get: function () {
  71849. return this._supportsTangents;
  71850. },
  71851. enumerable: true,
  71852. configurable: true
  71853. });
  71854. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  71855. get: function () {
  71856. return this._targets.length;
  71857. },
  71858. enumerable: true,
  71859. configurable: true
  71860. });
  71861. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  71862. get: function () {
  71863. return this._activeTargets.length;
  71864. },
  71865. enumerable: true,
  71866. configurable: true
  71867. });
  71868. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  71869. get: function () {
  71870. return this._influences;
  71871. },
  71872. enumerable: true,
  71873. configurable: true
  71874. });
  71875. MorphTargetManager.prototype.getActiveTarget = function (index) {
  71876. return this._activeTargets.data[index];
  71877. };
  71878. MorphTargetManager.prototype.getTarget = function (index) {
  71879. return this._targets[index];
  71880. };
  71881. MorphTargetManager.prototype.addTarget = function (target) {
  71882. var _this = this;
  71883. this._targets.push(target);
  71884. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  71885. _this._syncActiveTargets(needUpdate);
  71886. }));
  71887. this._syncActiveTargets(true);
  71888. };
  71889. MorphTargetManager.prototype.removeTarget = function (target) {
  71890. var index = this._targets.indexOf(target);
  71891. if (index >= 0) {
  71892. this._targets.splice(index, 1);
  71893. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  71894. this._syncActiveTargets(true);
  71895. }
  71896. };
  71897. /**
  71898. * Serializes the current manager into a Serialization object.
  71899. * Returns the serialized object.
  71900. */
  71901. MorphTargetManager.prototype.serialize = function () {
  71902. var serializationObject = {};
  71903. serializationObject.id = this.uniqueId;
  71904. serializationObject.targets = [];
  71905. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71906. var target = _a[_i];
  71907. serializationObject.targets.push(target.serialize());
  71908. }
  71909. return serializationObject;
  71910. };
  71911. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  71912. var influenceCount = 0;
  71913. this._activeTargets.reset();
  71914. this._supportsNormals = true;
  71915. this._supportsTangents = true;
  71916. this._vertexCount = 0;
  71917. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71918. var target = _a[_i];
  71919. this._activeTargets.push(target);
  71920. this._tempInfluences[influenceCount++] = target.influence;
  71921. var positions = target.getPositions();
  71922. if (positions) {
  71923. this._supportsNormals = this._supportsNormals && target.hasNormals;
  71924. this._supportsTangents = this._supportsTangents && target.hasTangents;
  71925. var vertexCount = positions.length / 3;
  71926. if (this._vertexCount === 0) {
  71927. this._vertexCount = vertexCount;
  71928. }
  71929. else if (this._vertexCount !== vertexCount) {
  71930. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  71931. return;
  71932. }
  71933. }
  71934. }
  71935. if (!this._influences || this._influences.length !== influenceCount) {
  71936. this._influences = new Float32Array(influenceCount);
  71937. }
  71938. for (var index = 0; index < influenceCount; index++) {
  71939. this._influences[index] = this._tempInfluences[index];
  71940. }
  71941. if (needUpdate && this._scene) {
  71942. // Flag meshes as dirty to resync with the active targets
  71943. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  71944. var mesh = _c[_b];
  71945. if (mesh.morphTargetManager === this) {
  71946. mesh._syncGeometryWithMorphTargetManager();
  71947. }
  71948. }
  71949. }
  71950. };
  71951. // Statics
  71952. MorphTargetManager.Parse = function (serializationObject, scene) {
  71953. var result = new MorphTargetManager(scene);
  71954. result._uniqueId = serializationObject.id;
  71955. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  71956. var targetData = _a[_i];
  71957. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  71958. }
  71959. return result;
  71960. };
  71961. return MorphTargetManager;
  71962. }());
  71963. BABYLON.MorphTargetManager = MorphTargetManager;
  71964. })(BABYLON || (BABYLON = {}));
  71965. //# sourceMappingURL=babylon.morphTargetManager.js.map
  71966. var BABYLON;
  71967. (function (BABYLON) {
  71968. var Octree = /** @class */ (function () {
  71969. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  71970. if (maxDepth === void 0) { maxDepth = 2; }
  71971. this.maxDepth = maxDepth;
  71972. this.dynamicContent = new Array();
  71973. this._maxBlockCapacity = maxBlockCapacity || 64;
  71974. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  71975. this._creationFunc = creationFunc;
  71976. }
  71977. // Methods
  71978. Octree.prototype.update = function (worldMin, worldMax, entries) {
  71979. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  71980. };
  71981. Octree.prototype.addMesh = function (entry) {
  71982. for (var index = 0; index < this.blocks.length; index++) {
  71983. var block = this.blocks[index];
  71984. block.addEntry(entry);
  71985. }
  71986. };
  71987. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  71988. this._selectionContent.reset();
  71989. for (var index = 0; index < this.blocks.length; index++) {
  71990. var block = this.blocks[index];
  71991. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  71992. }
  71993. if (allowDuplicate) {
  71994. this._selectionContent.concat(this.dynamicContent);
  71995. }
  71996. else {
  71997. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71998. }
  71999. return this._selectionContent;
  72000. };
  72001. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  72002. this._selectionContent.reset();
  72003. for (var index = 0; index < this.blocks.length; index++) {
  72004. var block = this.blocks[index];
  72005. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  72006. }
  72007. if (allowDuplicate) {
  72008. this._selectionContent.concat(this.dynamicContent);
  72009. }
  72010. else {
  72011. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72012. }
  72013. return this._selectionContent;
  72014. };
  72015. Octree.prototype.intersectsRay = function (ray) {
  72016. this._selectionContent.reset();
  72017. for (var index = 0; index < this.blocks.length; index++) {
  72018. var block = this.blocks[index];
  72019. block.intersectsRay(ray, this._selectionContent);
  72020. }
  72021. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  72022. return this._selectionContent;
  72023. };
  72024. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  72025. target.blocks = new Array();
  72026. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  72027. // Segmenting space
  72028. for (var x = 0; x < 2; x++) {
  72029. for (var y = 0; y < 2; y++) {
  72030. for (var z = 0; z < 2; z++) {
  72031. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  72032. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  72033. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  72034. block.addEntries(entries);
  72035. target.blocks.push(block);
  72036. }
  72037. }
  72038. }
  72039. };
  72040. Octree.CreationFuncForMeshes = function (entry, block) {
  72041. var boundingInfo = entry.getBoundingInfo();
  72042. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72043. block.entries.push(entry);
  72044. }
  72045. };
  72046. Octree.CreationFuncForSubMeshes = function (entry, block) {
  72047. var boundingInfo = entry.getBoundingInfo();
  72048. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  72049. block.entries.push(entry);
  72050. }
  72051. };
  72052. return Octree;
  72053. }());
  72054. BABYLON.Octree = Octree;
  72055. })(BABYLON || (BABYLON = {}));
  72056. //# sourceMappingURL=babylon.octree.js.map
  72057. var BABYLON;
  72058. (function (BABYLON) {
  72059. var OctreeBlock = /** @class */ (function () {
  72060. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  72061. this.entries = new Array();
  72062. this._boundingVectors = new Array();
  72063. this._capacity = capacity;
  72064. this._depth = depth;
  72065. this._maxDepth = maxDepth;
  72066. this._creationFunc = creationFunc;
  72067. this._minPoint = minPoint;
  72068. this._maxPoint = maxPoint;
  72069. this._boundingVectors.push(minPoint.clone());
  72070. this._boundingVectors.push(maxPoint.clone());
  72071. this._boundingVectors.push(minPoint.clone());
  72072. this._boundingVectors[2].x = maxPoint.x;
  72073. this._boundingVectors.push(minPoint.clone());
  72074. this._boundingVectors[3].y = maxPoint.y;
  72075. this._boundingVectors.push(minPoint.clone());
  72076. this._boundingVectors[4].z = maxPoint.z;
  72077. this._boundingVectors.push(maxPoint.clone());
  72078. this._boundingVectors[5].z = minPoint.z;
  72079. this._boundingVectors.push(maxPoint.clone());
  72080. this._boundingVectors[6].x = minPoint.x;
  72081. this._boundingVectors.push(maxPoint.clone());
  72082. this._boundingVectors[7].y = minPoint.y;
  72083. }
  72084. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  72085. // Property
  72086. get: function () {
  72087. return this._capacity;
  72088. },
  72089. enumerable: true,
  72090. configurable: true
  72091. });
  72092. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  72093. get: function () {
  72094. return this._minPoint;
  72095. },
  72096. enumerable: true,
  72097. configurable: true
  72098. });
  72099. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  72100. get: function () {
  72101. return this._maxPoint;
  72102. },
  72103. enumerable: true,
  72104. configurable: true
  72105. });
  72106. // Methods
  72107. OctreeBlock.prototype.addEntry = function (entry) {
  72108. if (this.blocks) {
  72109. for (var index = 0; index < this.blocks.length; index++) {
  72110. var block = this.blocks[index];
  72111. block.addEntry(entry);
  72112. }
  72113. return;
  72114. }
  72115. this._creationFunc(entry, this);
  72116. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  72117. this.createInnerBlocks();
  72118. }
  72119. };
  72120. OctreeBlock.prototype.addEntries = function (entries) {
  72121. for (var index = 0; index < entries.length; index++) {
  72122. var mesh = entries[index];
  72123. this.addEntry(mesh);
  72124. }
  72125. };
  72126. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  72127. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  72128. if (this.blocks) {
  72129. for (var index = 0; index < this.blocks.length; index++) {
  72130. var block = this.blocks[index];
  72131. block.select(frustumPlanes, selection, allowDuplicate);
  72132. }
  72133. return;
  72134. }
  72135. if (allowDuplicate) {
  72136. selection.concat(this.entries);
  72137. }
  72138. else {
  72139. selection.concatWithNoDuplicate(this.entries);
  72140. }
  72141. }
  72142. };
  72143. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  72144. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  72145. if (this.blocks) {
  72146. for (var index = 0; index < this.blocks.length; index++) {
  72147. var block = this.blocks[index];
  72148. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  72149. }
  72150. return;
  72151. }
  72152. if (allowDuplicate) {
  72153. selection.concat(this.entries);
  72154. }
  72155. else {
  72156. selection.concatWithNoDuplicate(this.entries);
  72157. }
  72158. }
  72159. };
  72160. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  72161. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  72162. if (this.blocks) {
  72163. for (var index = 0; index < this.blocks.length; index++) {
  72164. var block = this.blocks[index];
  72165. block.intersectsRay(ray, selection);
  72166. }
  72167. return;
  72168. }
  72169. selection.concatWithNoDuplicate(this.entries);
  72170. }
  72171. };
  72172. OctreeBlock.prototype.createInnerBlocks = function () {
  72173. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  72174. };
  72175. return OctreeBlock;
  72176. }());
  72177. BABYLON.OctreeBlock = OctreeBlock;
  72178. })(BABYLON || (BABYLON = {}));
  72179. //# sourceMappingURL=babylon.octreeBlock.js.map
  72180. var BABYLON;
  72181. (function (BABYLON) {
  72182. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  72183. __extends(VRDistortionCorrectionPostProcess, _super);
  72184. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  72185. var _this = _super.call(this, name, "vrDistortionCorrection", [
  72186. 'LensCenter',
  72187. 'Scale',
  72188. 'ScaleIn',
  72189. 'HmdWarpParam'
  72190. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  72191. _this._isRightEye = isRightEye;
  72192. _this._distortionFactors = vrMetrics.distortionK;
  72193. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  72194. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  72195. _this.adaptScaleToCurrentViewport = true;
  72196. _this.onSizeChangedObservable.add(function () {
  72197. _this.aspectRatio = _this.width * .5 / _this.height;
  72198. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  72199. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  72200. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  72201. });
  72202. _this.onApplyObservable.add(function (effect) {
  72203. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  72204. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  72205. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  72206. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  72207. });
  72208. return _this;
  72209. }
  72210. return VRDistortionCorrectionPostProcess;
  72211. }(BABYLON.PostProcess));
  72212. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  72213. })(BABYLON || (BABYLON = {}));
  72214. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  72215. var BABYLON;
  72216. (function (BABYLON) {
  72217. var AnaglyphPostProcess = /** @class */ (function (_super) {
  72218. __extends(AnaglyphPostProcess, _super);
  72219. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  72220. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  72221. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72222. _this.onApplyObservable.add(function (effect) {
  72223. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  72224. });
  72225. return _this;
  72226. }
  72227. return AnaglyphPostProcess;
  72228. }(BABYLON.PostProcess));
  72229. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  72230. })(BABYLON || (BABYLON = {}));
  72231. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  72232. var BABYLON;
  72233. (function (BABYLON) {
  72234. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  72235. __extends(StereoscopicInterlacePostProcess, _super);
  72236. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  72237. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  72238. _this._passedProcess = rigCameras[0]._rigPostProcess;
  72239. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72240. _this.onSizeChangedObservable.add(function () {
  72241. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  72242. });
  72243. _this.onApplyObservable.add(function (effect) {
  72244. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  72245. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  72246. });
  72247. return _this;
  72248. }
  72249. return StereoscopicInterlacePostProcess;
  72250. }(BABYLON.PostProcess));
  72251. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  72252. })(BABYLON || (BABYLON = {}));
  72253. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  72254. var BABYLON;
  72255. (function (BABYLON) {
  72256. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  72257. function FreeCameraDeviceOrientationInput() {
  72258. var _this = this;
  72259. this._screenOrientationAngle = 0;
  72260. this._screenQuaternion = new BABYLON.Quaternion();
  72261. this._alpha = 0;
  72262. this._beta = 0;
  72263. this._gamma = 0;
  72264. this._orientationChanged = function () {
  72265. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  72266. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  72267. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  72268. };
  72269. this._deviceOrientation = function (evt) {
  72270. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  72271. _this._beta = evt.beta !== null ? evt.beta : 0;
  72272. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  72273. };
  72274. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  72275. this._orientationChanged();
  72276. }
  72277. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  72278. get: function () {
  72279. return this._camera;
  72280. },
  72281. set: function (camera) {
  72282. this._camera = camera;
  72283. if (this._camera != null && !this._camera.rotationQuaternion) {
  72284. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  72285. }
  72286. },
  72287. enumerable: true,
  72288. configurable: true
  72289. });
  72290. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72291. window.addEventListener("orientationchange", this._orientationChanged);
  72292. window.addEventListener("deviceorientation", this._deviceOrientation);
  72293. //In certain cases, the attach control is called AFTER orientation was changed,
  72294. //So this is needed.
  72295. this._orientationChanged();
  72296. };
  72297. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  72298. window.removeEventListener("orientationchange", this._orientationChanged);
  72299. window.removeEventListener("deviceorientation", this._deviceOrientation);
  72300. };
  72301. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  72302. //if no device orientation provided, don't update the rotation.
  72303. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  72304. if (!this._alpha)
  72305. return;
  72306. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  72307. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  72308. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  72309. //Mirror on XY Plane
  72310. this._camera.rotationQuaternion.z *= -1;
  72311. this._camera.rotationQuaternion.w *= -1;
  72312. };
  72313. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  72314. return "FreeCameraDeviceOrientationInput";
  72315. };
  72316. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  72317. return "deviceOrientation";
  72318. };
  72319. return FreeCameraDeviceOrientationInput;
  72320. }());
  72321. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  72322. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  72323. })(BABYLON || (BABYLON = {}));
  72324. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  72325. var BABYLON;
  72326. (function (BABYLON) {
  72327. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  72328. function ArcRotateCameraVRDeviceOrientationInput() {
  72329. this.alphaCorrection = 1;
  72330. this.betaCorrection = 1;
  72331. this.gammaCorrection = 1;
  72332. this._alpha = 0;
  72333. this._gamma = 0;
  72334. this._dirty = false;
  72335. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  72336. }
  72337. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  72338. this.camera.attachControl(element, noPreventDefault);
  72339. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  72340. };
  72341. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  72342. if (evt.alpha !== null) {
  72343. this._alpha = +evt.alpha | 0;
  72344. }
  72345. if (evt.gamma !== null) {
  72346. this._gamma = +evt.gamma | 0;
  72347. }
  72348. this._dirty = true;
  72349. };
  72350. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  72351. if (this._dirty) {
  72352. this._dirty = false;
  72353. if (this._gamma < 0) {
  72354. this._gamma = 180 + this._gamma;
  72355. }
  72356. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  72357. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  72358. }
  72359. };
  72360. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  72361. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  72362. };
  72363. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  72364. return "ArcRotateCameraVRDeviceOrientationInput";
  72365. };
  72366. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  72367. return "VRDeviceOrientation";
  72368. };
  72369. return ArcRotateCameraVRDeviceOrientationInput;
  72370. }());
  72371. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  72372. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  72373. })(BABYLON || (BABYLON = {}));
  72374. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  72375. var BABYLON;
  72376. (function (BABYLON) {
  72377. var VRCameraMetrics = /** @class */ (function () {
  72378. function VRCameraMetrics() {
  72379. this.compensateDistortion = true;
  72380. }
  72381. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  72382. get: function () {
  72383. return this.hResolution / (2 * this.vResolution);
  72384. },
  72385. enumerable: true,
  72386. configurable: true
  72387. });
  72388. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  72389. get: function () {
  72390. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  72391. },
  72392. enumerable: true,
  72393. configurable: true
  72394. });
  72395. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  72396. get: function () {
  72397. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72398. var h = (4 * meters) / this.hScreenSize;
  72399. return BABYLON.Matrix.Translation(h, 0, 0);
  72400. },
  72401. enumerable: true,
  72402. configurable: true
  72403. });
  72404. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  72405. get: function () {
  72406. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  72407. var h = (4 * meters) / this.hScreenSize;
  72408. return BABYLON.Matrix.Translation(-h, 0, 0);
  72409. },
  72410. enumerable: true,
  72411. configurable: true
  72412. });
  72413. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  72414. get: function () {
  72415. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  72416. },
  72417. enumerable: true,
  72418. configurable: true
  72419. });
  72420. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72421. get: function () {
  72422. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72423. },
  72424. enumerable: true,
  72425. configurable: true
  72426. });
  72427. VRCameraMetrics.GetDefault = function () {
  72428. var result = new VRCameraMetrics();
  72429. result.hResolution = 1280;
  72430. result.vResolution = 800;
  72431. result.hScreenSize = 0.149759993;
  72432. result.vScreenSize = 0.0935999975;
  72433. result.vScreenCenter = 0.0467999987;
  72434. result.eyeToScreenDistance = 0.0410000011;
  72435. result.lensSeparationDistance = 0.0635000020;
  72436. result.interpupillaryDistance = 0.0640000030;
  72437. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72438. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72439. result.postProcessScaleFactor = 1.714605507808412;
  72440. result.lensCenterOffset = 0.151976421;
  72441. return result;
  72442. };
  72443. return VRCameraMetrics;
  72444. }());
  72445. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72446. })(BABYLON || (BABYLON = {}));
  72447. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72448. var BABYLON;
  72449. (function (BABYLON) {
  72450. var WebVRFreeCamera = /** @class */ (function (_super) {
  72451. __extends(WebVRFreeCamera, _super);
  72452. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72453. if (webVROptions === void 0) { webVROptions = {}; }
  72454. var _this = _super.call(this, name, position, scene) || this;
  72455. _this.webVROptions = webVROptions;
  72456. _this._vrDevice = null;
  72457. _this.rawPose = null;
  72458. _this._specsVersion = "1.1";
  72459. _this._attached = false;
  72460. _this._descendants = [];
  72461. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72462. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72463. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72464. _this._standingMatrix = null;
  72465. // Represents device position and rotation in babylon space
  72466. _this.devicePosition = BABYLON.Vector3.Zero();
  72467. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72468. _this.deviceScaleFactor = 1;
  72469. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72470. _this._worldToDevice = BABYLON.Matrix.Identity();
  72471. _this.controllers = [];
  72472. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72473. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72474. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72475. _this._defaultHeight = 0;
  72476. _this.deviceDistanceToRoomGround = function () {
  72477. if (_this._standingMatrix) {
  72478. // Add standing matrix offset to get real offset from ground in room
  72479. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72480. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72481. }
  72482. else {
  72483. return _this._defaultHeight;
  72484. }
  72485. };
  72486. _this.useStandingMatrix = function (callback) {
  72487. if (callback === void 0) { callback = function (bool) { }; }
  72488. // Use standing matrix if availible
  72489. if (!navigator || !navigator.getVRDisplays) {
  72490. callback(false);
  72491. }
  72492. else {
  72493. navigator.getVRDisplays().then(function (displays) {
  72494. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72495. callback(false);
  72496. }
  72497. else {
  72498. _this._standingMatrix = new BABYLON.Matrix();
  72499. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72500. if (!_this.getScene().useRightHandedSystem) {
  72501. [2, 6, 8, 9, 14].forEach(function (num) {
  72502. if (_this._standingMatrix) {
  72503. _this._standingMatrix.m[num] *= -1;
  72504. }
  72505. });
  72506. }
  72507. callback(true);
  72508. }
  72509. });
  72510. }
  72511. };
  72512. _this._workingVector = BABYLON.Vector3.Zero();
  72513. _this._oneVector = BABYLON.Vector3.One();
  72514. _this._workingMatrix = BABYLON.Matrix.Identity();
  72515. _this._cache.position = BABYLON.Vector3.Zero();
  72516. if (webVROptions.defaultHeight) {
  72517. _this._defaultHeight = webVROptions.defaultHeight;
  72518. _this.position.y = _this._defaultHeight;
  72519. }
  72520. _this.minZ = 0.1;
  72521. //legacy support - the compensation boolean was removed.
  72522. if (arguments.length === 5) {
  72523. _this.webVROptions = arguments[4];
  72524. }
  72525. // default webVR options
  72526. if (_this.webVROptions.trackPosition == undefined) {
  72527. _this.webVROptions.trackPosition = true;
  72528. }
  72529. if (_this.webVROptions.controllerMeshes == undefined) {
  72530. _this.webVROptions.controllerMeshes = true;
  72531. }
  72532. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72533. _this.webVROptions.defaultLightingOnControllers = true;
  72534. }
  72535. _this.rotationQuaternion = new BABYLON.Quaternion();
  72536. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72537. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72538. }
  72539. //enable VR
  72540. var engine = _this.getEngine();
  72541. _this._onVREnabled = function (success) { if (success) {
  72542. _this.initControllers();
  72543. } };
  72544. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72545. engine.initWebVR().add(function (event) {
  72546. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72547. return;
  72548. }
  72549. _this._vrDevice = event.vrDisplay;
  72550. //reset the rig parameters.
  72551. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72552. if (_this._attached) {
  72553. _this.getEngine().enableVR();
  72554. }
  72555. });
  72556. if (typeof (VRFrameData) !== "undefined")
  72557. _this._frameData = new VRFrameData();
  72558. /**
  72559. * The idea behind the following lines:
  72560. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72561. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72562. * the second will not show it correctly.
  72563. *
  72564. * To solve this - each object that has the camera as parent will be added to a protected array.
  72565. * When the rig camera renders, it will take this array and set all of those to be its children.
  72566. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72567. * Amazing!
  72568. */
  72569. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72570. if (camera.parent === _this && _this.rigParenting) {
  72571. _this._descendants = _this.getDescendants(true, function (n) {
  72572. // don't take the cameras or the controllers!
  72573. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72574. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72575. return !isController && !isRigCamera;
  72576. });
  72577. _this._descendants.forEach(function (node) {
  72578. node.parent = camera;
  72579. });
  72580. }
  72581. });
  72582. scene.onAfterCameraRenderObservable.add(function (camera) {
  72583. if (camera.parent === _this && _this.rigParenting) {
  72584. _this._descendants.forEach(function (node) {
  72585. node.parent = _this;
  72586. });
  72587. }
  72588. });
  72589. return _this;
  72590. }
  72591. WebVRFreeCamera.prototype.dispose = function () {
  72592. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72593. _super.prototype.dispose.call(this);
  72594. };
  72595. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72596. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72597. var gp = _a[_i];
  72598. if (gp.hand === name) {
  72599. return gp;
  72600. }
  72601. }
  72602. return null;
  72603. };
  72604. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72605. get: function () {
  72606. if (!this._leftController) {
  72607. this._leftController = this.getControllerByName("left");
  72608. }
  72609. return this._leftController;
  72610. },
  72611. enumerable: true,
  72612. configurable: true
  72613. });
  72614. ;
  72615. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72616. get: function () {
  72617. if (!this._rightController) {
  72618. this._rightController = this.getControllerByName("right");
  72619. }
  72620. return this._rightController;
  72621. },
  72622. enumerable: true,
  72623. configurable: true
  72624. });
  72625. ;
  72626. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72627. if (length === void 0) { length = 100; }
  72628. if (this.leftCamera) {
  72629. // Use left eye to avoid computation to compute center on every call
  72630. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72631. }
  72632. else {
  72633. return _super.prototype.getForwardRay.call(this, length);
  72634. }
  72635. };
  72636. WebVRFreeCamera.prototype._checkInputs = function () {
  72637. if (this._vrDevice && this._vrDevice.isPresenting) {
  72638. this._vrDevice.getFrameData(this._frameData);
  72639. this.updateFromDevice(this._frameData.pose);
  72640. }
  72641. _super.prototype._checkInputs.call(this);
  72642. };
  72643. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72644. if (poseData && poseData.orientation) {
  72645. this.rawPose = poseData;
  72646. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72647. if (this.getScene().useRightHandedSystem) {
  72648. this._deviceRoomRotationQuaternion.z *= -1;
  72649. this._deviceRoomRotationQuaternion.w *= -1;
  72650. }
  72651. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72652. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72653. if (this.getScene().useRightHandedSystem) {
  72654. this._deviceRoomPosition.z *= -1;
  72655. }
  72656. }
  72657. }
  72658. };
  72659. /**
  72660. * WebVR's attach control will start broadcasting frames to the device.
  72661. * Note that in certain browsers (chrome for example) this function must be called
  72662. * within a user-interaction callback. Example:
  72663. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72664. *
  72665. * @param {HTMLElement} element
  72666. * @param {boolean} [noPreventDefault]
  72667. *
  72668. * @memberOf WebVRFreeCamera
  72669. */
  72670. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72671. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72672. this._attached = true;
  72673. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72674. if (this._vrDevice) {
  72675. this.getEngine().enableVR();
  72676. }
  72677. };
  72678. WebVRFreeCamera.prototype.detachControl = function (element) {
  72679. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72680. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72681. _super.prototype.detachControl.call(this, element);
  72682. this._attached = false;
  72683. this.getEngine().disableVR();
  72684. };
  72685. WebVRFreeCamera.prototype.getClassName = function () {
  72686. return "WebVRFreeCamera";
  72687. };
  72688. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72689. //uses the vrDisplay's "resetPose()".
  72690. //pitch and roll won't be affected.
  72691. this._vrDevice.resetPose();
  72692. };
  72693. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72694. var camLeft = this._rigCameras[0];
  72695. var camRight = this._rigCameras[1];
  72696. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72697. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72698. camLeft.position.copyFrom(this._deviceRoomPosition);
  72699. camRight.position.copyFrom(this._deviceRoomPosition);
  72700. };
  72701. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72702. var _this = this;
  72703. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72704. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72705. if (!this.updateCacheCalled) {
  72706. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72707. this.updateCacheCalled = true;
  72708. this.update();
  72709. }
  72710. // Set working vector to the device position in room space rotated by the new rotation
  72711. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72712. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72713. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72714. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72715. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72716. // Add translation from anchor position
  72717. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72718. this._workingVector.addInPlace(this.position);
  72719. this._workingVector.subtractInPlace(this._cache.position);
  72720. this._deviceToWorld.setTranslation(this._workingVector);
  72721. // Set an inverted matrix to be used when updating the camera
  72722. this._deviceToWorld.invertToRef(this._worldToDevice);
  72723. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72724. this.controllers.forEach(function (controller) {
  72725. controller._deviceToWorld = _this._deviceToWorld;
  72726. controller.update();
  72727. });
  72728. }
  72729. if (!ignoreParentClass) {
  72730. _super.prototype._updateCache.call(this);
  72731. }
  72732. this.updateCacheCalled = false;
  72733. };
  72734. WebVRFreeCamera.prototype.update = function () {
  72735. // Get current device position in babylon world
  72736. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72737. // Get current device rotation in babylon world
  72738. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72739. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72740. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72741. _super.prototype.update.call(this);
  72742. };
  72743. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72744. return BABYLON.Matrix.Identity();
  72745. };
  72746. /**
  72747. * This function is called by the two RIG cameras.
  72748. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72749. */
  72750. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72751. var _this = this;
  72752. //WebVR 1.1
  72753. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72754. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72755. if (!this.getScene().useRightHandedSystem) {
  72756. [2, 6, 8, 9, 14].forEach(function (num) {
  72757. _this._webvrViewMatrix.m[num] *= -1;
  72758. });
  72759. }
  72760. // update the camera rotation matrix
  72761. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72762. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72763. // Computing target and final matrix
  72764. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72765. var parentCamera = this._cameraRigParams["parentCamera"];
  72766. // should the view matrix be updated with scale and position offset?
  72767. if (parentCamera.deviceScaleFactor !== 1) {
  72768. this._webvrViewMatrix.invert();
  72769. // scale the position, if set
  72770. if (parentCamera.deviceScaleFactor) {
  72771. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72772. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72773. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72774. }
  72775. this._webvrViewMatrix.invert();
  72776. }
  72777. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72778. return this._webvrViewMatrix;
  72779. };
  72780. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72781. var _this = this;
  72782. var parentCamera = this.parent;
  72783. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72784. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72785. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72786. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72787. //babylon compatible matrix
  72788. if (!this.getScene().useRightHandedSystem) {
  72789. [8, 9, 10, 11].forEach(function (num) {
  72790. _this._projectionMatrix.m[num] *= -1;
  72791. });
  72792. }
  72793. return this._projectionMatrix;
  72794. };
  72795. WebVRFreeCamera.prototype.initControllers = function () {
  72796. var _this = this;
  72797. this.controllers = [];
  72798. var manager = this.getScene().gamepadManager;
  72799. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72800. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72801. var webVrController = gamepad;
  72802. if (webVrController.defaultModel) {
  72803. webVrController.defaultModel.setEnabled(false);
  72804. }
  72805. if (webVrController.hand === "right") {
  72806. _this._rightController = null;
  72807. }
  72808. if (webVrController.hand === "left") {
  72809. _this._rightController = null;
  72810. }
  72811. var controllerIndex = _this.controllers.indexOf(webVrController);
  72812. if (controllerIndex !== -1) {
  72813. _this.controllers.splice(controllerIndex, 1);
  72814. }
  72815. }
  72816. });
  72817. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72818. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72819. var webVrController_1 = gamepad;
  72820. webVrController_1._deviceToWorld = _this._deviceToWorld;
  72821. if (_this.webVROptions.controllerMeshes) {
  72822. if (webVrController_1.defaultModel) {
  72823. webVrController_1.defaultModel.setEnabled(true);
  72824. }
  72825. else {
  72826. // Load the meshes
  72827. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  72828. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  72829. if (_this.webVROptions.defaultLightingOnControllers) {
  72830. if (!_this._lightOnControllers) {
  72831. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  72832. }
  72833. var activateLightOnSubMeshes_1 = function (mesh, light) {
  72834. var children = mesh.getChildren();
  72835. if (children.length !== 0) {
  72836. children.forEach(function (mesh) {
  72837. light.includedOnlyMeshes.push(mesh);
  72838. activateLightOnSubMeshes_1(mesh, light);
  72839. });
  72840. }
  72841. };
  72842. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  72843. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  72844. }
  72845. });
  72846. }
  72847. }
  72848. webVrController_1.attachToPoseControlledCamera(_this);
  72849. // since this is async - sanity check. Is the controller already stored?
  72850. if (_this.controllers.indexOf(webVrController_1) === -1) {
  72851. //add to the controllers array
  72852. _this.controllers.push(webVrController_1);
  72853. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  72854. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  72855. // So we're overriding setting left & right manually to be sure
  72856. var firstViveWandDetected = false;
  72857. for (var i = 0; i < _this.controllers.length; i++) {
  72858. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72859. if (!firstViveWandDetected) {
  72860. firstViveWandDetected = true;
  72861. _this.controllers[i].hand = "left";
  72862. }
  72863. else {
  72864. _this.controllers[i].hand = "right";
  72865. }
  72866. }
  72867. }
  72868. //did we find enough controllers? Great! let the developer know.
  72869. if (_this.controllers.length >= 2) {
  72870. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  72871. }
  72872. }
  72873. }
  72874. });
  72875. };
  72876. return WebVRFreeCamera;
  72877. }(BABYLON.FreeCamera));
  72878. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  72879. })(BABYLON || (BABYLON = {}));
  72880. //# sourceMappingURL=babylon.webVRCamera.js.map
  72881. var BABYLON;
  72882. (function (BABYLON) {
  72883. // We're mainly based on the logic defined into the FreeCamera code
  72884. var DeviceOrientationCamera = /** @class */ (function (_super) {
  72885. __extends(DeviceOrientationCamera, _super);
  72886. function DeviceOrientationCamera(name, position, scene) {
  72887. var _this = _super.call(this, name, position, scene) || this;
  72888. _this._quaternionCache = new BABYLON.Quaternion();
  72889. _this.inputs.addDeviceOrientation();
  72890. return _this;
  72891. }
  72892. DeviceOrientationCamera.prototype.getClassName = function () {
  72893. return "DeviceOrientationCamera";
  72894. };
  72895. DeviceOrientationCamera.prototype._checkInputs = function () {
  72896. _super.prototype._checkInputs.call(this);
  72897. this._quaternionCache.copyFrom(this.rotationQuaternion);
  72898. if (this._initialQuaternion) {
  72899. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72900. }
  72901. };
  72902. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  72903. var _this = this;
  72904. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  72905. //can only work if this camera has a rotation quaternion already.
  72906. if (!this.rotationQuaternion)
  72907. return;
  72908. if (!this._initialQuaternion) {
  72909. this._initialQuaternion = new BABYLON.Quaternion();
  72910. }
  72911. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  72912. ['x', 'y', 'z'].forEach(function (axisName) {
  72913. if (!axis[axisName]) {
  72914. _this._initialQuaternion[axisName] = 0;
  72915. }
  72916. else {
  72917. _this._initialQuaternion[axisName] *= -1;
  72918. }
  72919. });
  72920. this._initialQuaternion.normalize();
  72921. //force rotation update
  72922. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72923. };
  72924. return DeviceOrientationCamera;
  72925. }(BABYLON.FreeCamera));
  72926. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  72927. })(BABYLON || (BABYLON = {}));
  72928. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  72929. var BABYLON;
  72930. (function (BABYLON) {
  72931. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  72932. __extends(VRDeviceOrientationFreeCamera, _super);
  72933. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72934. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72935. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72936. var _this = _super.call(this, name, position, scene) || this;
  72937. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72938. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72939. return _this;
  72940. }
  72941. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  72942. return "VRDeviceOrientationFreeCamera";
  72943. };
  72944. return VRDeviceOrientationFreeCamera;
  72945. }(BABYLON.DeviceOrientationCamera));
  72946. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  72947. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  72948. __extends(VRDeviceOrientationGamepadCamera, _super);
  72949. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72950. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72951. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72952. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  72953. _this.inputs.addGamepad();
  72954. return _this;
  72955. }
  72956. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  72957. return "VRDeviceOrientationGamepadCamera";
  72958. };
  72959. return VRDeviceOrientationGamepadCamera;
  72960. }(VRDeviceOrientationFreeCamera));
  72961. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  72962. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  72963. __extends(VRDeviceOrientationArcRotateCamera, _super);
  72964. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  72965. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72966. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72967. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72968. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72969. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72970. _this.inputs.addVRDeviceOrientation();
  72971. return _this;
  72972. }
  72973. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  72974. return "VRDeviceOrientationArcRotateCamera";
  72975. };
  72976. return VRDeviceOrientationArcRotateCamera;
  72977. }(BABYLON.ArcRotateCamera));
  72978. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  72979. })(BABYLON || (BABYLON = {}));
  72980. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  72981. var BABYLON;
  72982. (function (BABYLON) {
  72983. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  72984. __extends(AnaglyphFreeCamera, _super);
  72985. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  72986. var _this = _super.call(this, name, position, scene) || this;
  72987. _this.interaxialDistance = interaxialDistance;
  72988. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72989. return _this;
  72990. }
  72991. AnaglyphFreeCamera.prototype.getClassName = function () {
  72992. return "AnaglyphFreeCamera";
  72993. };
  72994. return AnaglyphFreeCamera;
  72995. }(BABYLON.FreeCamera));
  72996. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  72997. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  72998. __extends(AnaglyphArcRotateCamera, _super);
  72999. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  73000. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73001. _this.interaxialDistance = interaxialDistance;
  73002. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73003. return _this;
  73004. }
  73005. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  73006. return "AnaglyphArcRotateCamera";
  73007. };
  73008. return AnaglyphArcRotateCamera;
  73009. }(BABYLON.ArcRotateCamera));
  73010. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  73011. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  73012. __extends(AnaglyphGamepadCamera, _super);
  73013. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  73014. var _this = _super.call(this, name, position, scene) || this;
  73015. _this.interaxialDistance = interaxialDistance;
  73016. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73017. return _this;
  73018. }
  73019. AnaglyphGamepadCamera.prototype.getClassName = function () {
  73020. return "AnaglyphGamepadCamera";
  73021. };
  73022. return AnaglyphGamepadCamera;
  73023. }(BABYLON.GamepadCamera));
  73024. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  73025. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  73026. __extends(AnaglyphUniversalCamera, _super);
  73027. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  73028. var _this = _super.call(this, name, position, scene) || this;
  73029. _this.interaxialDistance = interaxialDistance;
  73030. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  73031. return _this;
  73032. }
  73033. AnaglyphUniversalCamera.prototype.getClassName = function () {
  73034. return "AnaglyphUniversalCamera";
  73035. };
  73036. return AnaglyphUniversalCamera;
  73037. }(BABYLON.UniversalCamera));
  73038. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  73039. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  73040. __extends(StereoscopicFreeCamera, _super);
  73041. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73042. var _this = _super.call(this, name, position, scene) || this;
  73043. _this.interaxialDistance = interaxialDistance;
  73044. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73045. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73046. return _this;
  73047. }
  73048. StereoscopicFreeCamera.prototype.getClassName = function () {
  73049. return "StereoscopicFreeCamera";
  73050. };
  73051. return StereoscopicFreeCamera;
  73052. }(BABYLON.FreeCamera));
  73053. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  73054. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  73055. __extends(StereoscopicArcRotateCamera, _super);
  73056. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  73057. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  73058. _this.interaxialDistance = interaxialDistance;
  73059. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73060. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73061. return _this;
  73062. }
  73063. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  73064. return "StereoscopicArcRotateCamera";
  73065. };
  73066. return StereoscopicArcRotateCamera;
  73067. }(BABYLON.ArcRotateCamera));
  73068. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  73069. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  73070. __extends(StereoscopicGamepadCamera, _super);
  73071. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73072. var _this = _super.call(this, name, position, scene) || this;
  73073. _this.interaxialDistance = interaxialDistance;
  73074. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73075. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73076. return _this;
  73077. }
  73078. StereoscopicGamepadCamera.prototype.getClassName = function () {
  73079. return "StereoscopicGamepadCamera";
  73080. };
  73081. return StereoscopicGamepadCamera;
  73082. }(BABYLON.GamepadCamera));
  73083. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  73084. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  73085. __extends(StereoscopicUniversalCamera, _super);
  73086. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  73087. var _this = _super.call(this, name, position, scene) || this;
  73088. _this.interaxialDistance = interaxialDistance;
  73089. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  73090. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  73091. return _this;
  73092. }
  73093. StereoscopicUniversalCamera.prototype.getClassName = function () {
  73094. return "StereoscopicUniversalCamera";
  73095. };
  73096. return StereoscopicUniversalCamera;
  73097. }(BABYLON.UniversalCamera));
  73098. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  73099. })(BABYLON || (BABYLON = {}));
  73100. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  73101. var BABYLON;
  73102. (function (BABYLON) {
  73103. var VRExperienceHelper = /** @class */ (function () {
  73104. function VRExperienceHelper(scene, webVROptions) {
  73105. if (webVROptions === void 0) { webVROptions = {}; }
  73106. var _this = this;
  73107. this.webVROptions = webVROptions;
  73108. // Can the system support WebVR, even if a headset isn't plugged in?
  73109. this._webVRsupported = false;
  73110. // If WebVR is supported, is a headset plugged in and are we ready to present?
  73111. this._webVRready = false;
  73112. // Are we waiting for the requestPresent callback to complete?
  73113. this._webVRrequesting = false;
  73114. // Are we presenting to the headset right now?
  73115. this._webVRpresenting = false;
  73116. // Are we presenting in the fullscreen fallback?
  73117. this._fullscreenVRpresenting = false;
  73118. /**
  73119. * Observable raised when entering VR.
  73120. */
  73121. this.onEnteringVRObservable = new BABYLON.Observable();
  73122. /**
  73123. * Observable raised when exiting VR.
  73124. */
  73125. this.onExitingVRObservable = new BABYLON.Observable();
  73126. /**
  73127. * Observable raised when controller mesh is loaded.
  73128. */
  73129. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  73130. this._useCustomVRButton = false;
  73131. this._teleportationRequested = false;
  73132. this._teleportationEnabledOnLeftController = false;
  73133. this._teleportationEnabledOnRightController = false;
  73134. this._interactionsEnabledOnLeftController = false;
  73135. this._interactionsEnabledOnRightController = false;
  73136. this._leftControllerReady = false;
  73137. this._rightControllerReady = false;
  73138. this._floorMeshesCollection = [];
  73139. this._teleportationAllowed = false;
  73140. this._rotationAllowed = true;
  73141. this._teleportationRequestInitiated = false;
  73142. this._teleportationBackRequestInitiated = false;
  73143. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  73144. this._rotationRightAsked = false;
  73145. this._rotationLeftAsked = false;
  73146. this._isDefaultTeleportationTarget = true;
  73147. this._teleportationFillColor = "#444444";
  73148. this._teleportationBorderColor = "#FFFFFF";
  73149. this._rotationAngle = 0;
  73150. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  73151. this._padSensibilityUp = 0.65;
  73152. this._padSensibilityDown = 0.35;
  73153. /**
  73154. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  73155. */
  73156. this.onNewMeshSelected = new BABYLON.Observable();
  73157. /**
  73158. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  73159. */
  73160. this.onNewMeshPicked = new BABYLON.Observable();
  73161. /**
  73162. * Observable raised before camera teleportation
  73163. */
  73164. this.onBeforeCameraTeleport = new BABYLON.Observable();
  73165. /**
  73166. * Observable raised after camera teleportation
  73167. */
  73168. this.onAfterCameraTeleport = new BABYLON.Observable();
  73169. /**
  73170. * Observable raised when current selected mesh gets unselected
  73171. */
  73172. this.onSelectedMeshUnselected = new BABYLON.Observable();
  73173. /**
  73174. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  73175. */
  73176. this.teleportationEnabled = true;
  73177. this._pointerDownOnMeshAsked = false;
  73178. this._isActionableMesh = false;
  73179. this._teleportationInitialized = false;
  73180. this._interactionsEnabled = false;
  73181. this._interactionsRequested = false;
  73182. this._displayGaze = true;
  73183. this._displayLaserPointer = true;
  73184. this._dpadPressed = true;
  73185. this._onResize = function () {
  73186. _this.moveButtonToBottomRight();
  73187. if (_this._fullscreenVRpresenting && _this._webVRready) {
  73188. _this.exitVR();
  73189. }
  73190. };
  73191. this._onFullscreenChange = function () {
  73192. if (document.fullscreen !== undefined) {
  73193. _this._fullscreenVRpresenting = document.fullscreen;
  73194. }
  73195. else if (document.mozFullScreen !== undefined) {
  73196. _this._fullscreenVRpresenting = document.mozFullScreen;
  73197. }
  73198. else if (document.webkitIsFullScreen !== undefined) {
  73199. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  73200. }
  73201. else if (document.msIsFullScreen !== undefined) {
  73202. _this._fullscreenVRpresenting = document.msIsFullScreen;
  73203. }
  73204. if (!_this._fullscreenVRpresenting && _this._canvas) {
  73205. _this.exitVR();
  73206. if (!_this._useCustomVRButton) {
  73207. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  73208. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  73209. }
  73210. }
  73211. };
  73212. this.beforeRender = function () {
  73213. _this._castRayAndSelectObject();
  73214. };
  73215. this._onNewGamepadConnected = function (gamepad) {
  73216. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  73217. if (gamepad.leftStick) {
  73218. gamepad.onleftstickchanged(function (stickValues) {
  73219. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  73220. // Listening to classic/xbox gamepad only if no VR controller is active
  73221. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  73222. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  73223. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  73224. _this._checkTeleportWithRay(stickValues);
  73225. _this._checkTeleportBackwards(stickValues);
  73226. }
  73227. }
  73228. });
  73229. }
  73230. if (gamepad.rightStick) {
  73231. gamepad.onrightstickchanged(function (stickValues) {
  73232. if (_this._teleportationInitialized) {
  73233. _this._checkRotate(stickValues);
  73234. }
  73235. });
  73236. }
  73237. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  73238. gamepad.onbuttondown(function (buttonPressed) {
  73239. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73240. _this._selectionPointerDown();
  73241. }
  73242. });
  73243. gamepad.onbuttonup(function (buttonPressed) {
  73244. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  73245. _this._selectionPointerUp();
  73246. }
  73247. });
  73248. }
  73249. }
  73250. else {
  73251. var webVRController = gamepad;
  73252. _this._tryEnableInteractionOnController(webVRController);
  73253. }
  73254. };
  73255. // 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
  73256. this._tryEnableInteractionOnController = function (webVRController) {
  73257. if (webVRController.hand === "left") {
  73258. _this._leftControllerReady = true;
  73259. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  73260. _this._enableInteractionOnController(webVRController);
  73261. }
  73262. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  73263. _this._enableTeleportationOnController(webVRController);
  73264. }
  73265. }
  73266. if (webVRController.hand === "right") {
  73267. _this._rightControllerReady = true;
  73268. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  73269. _this._enableInteractionOnController(webVRController);
  73270. }
  73271. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  73272. _this._enableTeleportationOnController(webVRController);
  73273. }
  73274. }
  73275. };
  73276. this._onNewGamepadDisconnected = function (gamepad) {
  73277. if (gamepad instanceof BABYLON.WebVRController) {
  73278. if (gamepad.hand === "left") {
  73279. _this._interactionsEnabledOnLeftController = false;
  73280. _this._teleportationEnabledOnLeftController = false;
  73281. _this._leftControllerReady = false;
  73282. if (_this._leftLaserPointer) {
  73283. _this._leftLaserPointer.dispose();
  73284. }
  73285. }
  73286. if (gamepad.hand === "right") {
  73287. _this._interactionsEnabledOnRightController = false;
  73288. _this._teleportationEnabledOnRightController = false;
  73289. _this._rightControllerReady = false;
  73290. if (_this._rightLaserPointer) {
  73291. _this._rightLaserPointer.dispose();
  73292. }
  73293. }
  73294. }
  73295. };
  73296. this._workingVector = BABYLON.Vector3.Zero();
  73297. this._workingQuaternion = BABYLON.Quaternion.Identity();
  73298. this._workingMatrix = BABYLON.Matrix.Identity();
  73299. this._scene = scene;
  73300. this._canvas = scene.getEngine().getRenderingCanvas();
  73301. // Parse options
  73302. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  73303. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  73304. }
  73305. if (webVROptions.createDeviceOrientationCamera === undefined) {
  73306. webVROptions.createDeviceOrientationCamera = true;
  73307. }
  73308. if (webVROptions.defaultHeight === undefined) {
  73309. webVROptions.defaultHeight = 1.7;
  73310. }
  73311. if (webVROptions.useCustomVRButton) {
  73312. this._useCustomVRButton = true;
  73313. if (webVROptions.customVRButton) {
  73314. this._btnVR = webVROptions.customVRButton;
  73315. }
  73316. }
  73317. if (webVROptions.rayLength) {
  73318. this._rayLength = webVROptions.rayLength;
  73319. }
  73320. this._defaultHeight = webVROptions.defaultHeight;
  73321. // Set position
  73322. if (this._scene.activeCamera) {
  73323. this._position = this._scene.activeCamera.position.clone();
  73324. }
  73325. else {
  73326. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  73327. }
  73328. // Set non-vr camera
  73329. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  73330. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  73331. // Copy data from existing camera
  73332. if (this._scene.activeCamera) {
  73333. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  73334. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  73335. // Set rotation from previous camera
  73336. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  73337. var targetCamera = this._scene.activeCamera;
  73338. if (targetCamera.rotationQuaternion) {
  73339. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  73340. }
  73341. else {
  73342. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  73343. }
  73344. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  73345. }
  73346. }
  73347. this._scene.activeCamera = this._deviceOrientationCamera;
  73348. if (this._canvas) {
  73349. this._scene.activeCamera.attachControl(this._canvas);
  73350. }
  73351. }
  73352. else {
  73353. this._existingCamera = this._scene.activeCamera;
  73354. }
  73355. // Create VR cameras
  73356. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73357. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  73358. }
  73359. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  73360. this._webVRCamera.useStandingMatrix();
  73361. // Create default button
  73362. if (!this._useCustomVRButton) {
  73363. this._btnVR = document.createElement("BUTTON");
  73364. this._btnVR.className = "babylonVRicon";
  73365. this._btnVR.id = "babylonVRiconbtn";
  73366. this._btnVR.title = "Click to switch to VR";
  73367. 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) }";
  73368. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  73369. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  73370. // css += ".babylonVRicon.vrdisplaysupported { }";
  73371. // css += ".babylonVRicon.vrdisplayready { }";
  73372. // css += ".babylonVRicon.vrdisplayrequesting { }";
  73373. var style = document.createElement('style');
  73374. style.appendChild(document.createTextNode(css));
  73375. document.getElementsByTagName('head')[0].appendChild(style);
  73376. this.moveButtonToBottomRight();
  73377. }
  73378. // VR button click event
  73379. if (this._btnVR) {
  73380. this._btnVR.addEventListener("click", function () {
  73381. if (!_this.isInVRMode) {
  73382. _this.enterVR();
  73383. }
  73384. else {
  73385. _this.exitVR();
  73386. }
  73387. });
  73388. }
  73389. // Window events
  73390. window.addEventListener("resize", this._onResize);
  73391. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  73392. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  73393. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  73394. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  73395. // Display vr button when headset is connected
  73396. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  73397. this.displayVRButton();
  73398. }
  73399. else {
  73400. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  73401. if (e.vrDisplay) {
  73402. _this.displayVRButton();
  73403. }
  73404. });
  73405. }
  73406. // Exiting VR mode using 'ESC' key on desktop
  73407. this._onKeyDown = function (event) {
  73408. if (event.keyCode === 27 && _this.isInVRMode) {
  73409. _this.exitVR();
  73410. }
  73411. };
  73412. document.addEventListener("keydown", this._onKeyDown);
  73413. // Exiting VR mode double tapping the touch screen
  73414. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  73415. if (_this.isInVRMode) {
  73416. _this.exitVR();
  73417. if (_this._fullscreenVRpresenting) {
  73418. _this._scene.getEngine().switchFullscreen(true);
  73419. }
  73420. }
  73421. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  73422. // Listen for WebVR display changes
  73423. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  73424. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  73425. this._onVRRequestPresentStart = function () {
  73426. _this._webVRrequesting = true;
  73427. _this.updateButtonVisibility();
  73428. };
  73429. this._onVRRequestPresentComplete = function (success) {
  73430. _this._webVRrequesting = false;
  73431. _this.updateButtonVisibility();
  73432. };
  73433. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  73434. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  73435. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  73436. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  73437. scene.onDisposeObservable.add(function () {
  73438. _this.dispose();
  73439. });
  73440. // Gamepad connection events
  73441. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73442. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73443. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73444. this.updateButtonVisibility();
  73445. //create easing functions
  73446. this._circleEase = new BABYLON.CircleEase();
  73447. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73448. }
  73449. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73450. /** Return this.onEnteringVRObservable
  73451. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73452. */
  73453. get: function () {
  73454. return this.onEnteringVRObservable;
  73455. },
  73456. enumerable: true,
  73457. configurable: true
  73458. });
  73459. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73460. /** Return this.onExitingVRObservable
  73461. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73462. */
  73463. get: function () {
  73464. return this.onExitingVRObservable;
  73465. },
  73466. enumerable: true,
  73467. configurable: true
  73468. });
  73469. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73470. /** Return this.onControllerMeshLoadedObservable
  73471. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73472. */
  73473. get: function () {
  73474. return this.onControllerMeshLoadedObservable;
  73475. },
  73476. enumerable: true,
  73477. configurable: true
  73478. });
  73479. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73480. get: function () {
  73481. return this._teleportationTarget;
  73482. },
  73483. set: function (value) {
  73484. if (value) {
  73485. value.name = "teleportationTarget";
  73486. this._isDefaultTeleportationTarget = false;
  73487. this._teleportationTarget = value;
  73488. }
  73489. },
  73490. enumerable: true,
  73491. configurable: true
  73492. });
  73493. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73494. get: function () {
  73495. return this._displayGaze;
  73496. },
  73497. set: function (value) {
  73498. this._displayGaze = value;
  73499. if (!value) {
  73500. this._gazeTracker.isVisible = false;
  73501. }
  73502. },
  73503. enumerable: true,
  73504. configurable: true
  73505. });
  73506. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73507. get: function () {
  73508. return this._displayLaserPointer;
  73509. },
  73510. set: function (value) {
  73511. this._displayLaserPointer = value;
  73512. if (!value) {
  73513. if (this._rightLaserPointer) {
  73514. this._rightLaserPointer.isVisible = false;
  73515. }
  73516. if (this._leftLaserPointer) {
  73517. this._leftLaserPointer.isVisible = false;
  73518. }
  73519. }
  73520. else {
  73521. if (this._rightLaserPointer) {
  73522. this._rightLaserPointer.isVisible = true;
  73523. }
  73524. else if (this._leftLaserPointer) {
  73525. this._leftLaserPointer.isVisible = true;
  73526. }
  73527. }
  73528. },
  73529. enumerable: true,
  73530. configurable: true
  73531. });
  73532. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73533. get: function () {
  73534. return this._deviceOrientationCamera;
  73535. },
  73536. enumerable: true,
  73537. configurable: true
  73538. });
  73539. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73540. // Based on the current WebVR support, returns the current VR camera used
  73541. get: function () {
  73542. if (this._webVRready) {
  73543. return this._webVRCamera;
  73544. }
  73545. else {
  73546. return this._scene.activeCamera;
  73547. }
  73548. },
  73549. enumerable: true,
  73550. configurable: true
  73551. });
  73552. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73553. get: function () {
  73554. return this._webVRCamera;
  73555. },
  73556. enumerable: true,
  73557. configurable: true
  73558. });
  73559. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73560. get: function () {
  73561. return this._vrDeviceOrientationCamera;
  73562. },
  73563. enumerable: true,
  73564. configurable: true
  73565. });
  73566. // Raised when one of the controller has loaded successfully its associated default mesh
  73567. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73568. this._tryEnableInteractionOnController(webVRController);
  73569. try {
  73570. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73571. }
  73572. catch (err) {
  73573. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73574. }
  73575. };
  73576. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73577. /**
  73578. * Gets a value indicating if we are currently in VR mode.
  73579. */
  73580. get: function () {
  73581. return this._webVRpresenting || this._fullscreenVRpresenting;
  73582. },
  73583. enumerable: true,
  73584. configurable: true
  73585. });
  73586. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73587. var vrDisplay = this._scene.getEngine().getVRDevice();
  73588. if (vrDisplay) {
  73589. var wasPresenting = this._webVRpresenting;
  73590. // A VR display is connected
  73591. this._webVRpresenting = vrDisplay.isPresenting;
  73592. if (wasPresenting && !this._webVRpresenting)
  73593. this.exitVR();
  73594. }
  73595. else {
  73596. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73597. }
  73598. this.updateButtonVisibility();
  73599. };
  73600. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73601. this._webVRsupported = eventArgs.vrSupported;
  73602. this._webVRready = !!eventArgs.vrDisplay;
  73603. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73604. this.updateButtonVisibility();
  73605. };
  73606. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73607. if (this._canvas && !this._useCustomVRButton) {
  73608. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73609. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73610. }
  73611. };
  73612. VRExperienceHelper.prototype.displayVRButton = function () {
  73613. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73614. document.body.appendChild(this._btnVR);
  73615. this._btnVRDisplayed = true;
  73616. }
  73617. };
  73618. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73619. if (!this._btnVR || this._useCustomVRButton) {
  73620. return;
  73621. }
  73622. this._btnVR.className = "babylonVRicon";
  73623. if (this.isInVRMode) {
  73624. this._btnVR.className += " vrdisplaypresenting";
  73625. }
  73626. else {
  73627. if (this._webVRready)
  73628. this._btnVR.className += " vrdisplayready";
  73629. if (this._webVRsupported)
  73630. this._btnVR.className += " vrdisplaysupported";
  73631. if (this._webVRrequesting)
  73632. this._btnVR.className += " vrdisplayrequesting";
  73633. }
  73634. };
  73635. /**
  73636. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73637. * Otherwise, will use the fullscreen API.
  73638. */
  73639. VRExperienceHelper.prototype.enterVR = function () {
  73640. if (this.onEnteringVRObservable) {
  73641. try {
  73642. this.onEnteringVRObservable.notifyObservers(this);
  73643. }
  73644. catch (err) {
  73645. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73646. }
  73647. }
  73648. if (this._scene.activeCamera) {
  73649. this._position = this._scene.activeCamera.position.clone();
  73650. // make sure that we return to the last active camera
  73651. this._existingCamera = this._scene.activeCamera;
  73652. }
  73653. if (this._webVRrequesting)
  73654. return;
  73655. // If WebVR is supported and a headset is connected
  73656. if (this._webVRready) {
  73657. if (!this._webVRpresenting) {
  73658. this._webVRCamera.position = this._position;
  73659. this._scene.activeCamera = this._webVRCamera;
  73660. }
  73661. }
  73662. else if (this._vrDeviceOrientationCamera) {
  73663. this._vrDeviceOrientationCamera.position = this._position;
  73664. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73665. this._scene.getEngine().switchFullscreen(true);
  73666. this.updateButtonVisibility();
  73667. }
  73668. if (this._scene.activeCamera && this._canvas) {
  73669. this._scene.activeCamera.attachControl(this._canvas);
  73670. }
  73671. if (this._interactionsEnabled) {
  73672. this._scene.registerBeforeRender(this.beforeRender);
  73673. }
  73674. };
  73675. /**
  73676. * Attempt to exit VR, or fullscreen.
  73677. */
  73678. VRExperienceHelper.prototype.exitVR = function () {
  73679. if (this.onExitingVRObservable) {
  73680. try {
  73681. this.onExitingVRObservable.notifyObservers(this);
  73682. }
  73683. catch (err) {
  73684. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73685. }
  73686. }
  73687. if (this._webVRpresenting) {
  73688. this._scene.getEngine().disableVR();
  73689. }
  73690. if (this._scene.activeCamera) {
  73691. this._position = this._scene.activeCamera.position.clone();
  73692. }
  73693. if (this._deviceOrientationCamera) {
  73694. this._deviceOrientationCamera.position = this._position;
  73695. this._scene.activeCamera = this._deviceOrientationCamera;
  73696. if (this._canvas) {
  73697. this._scene.activeCamera.attachControl(this._canvas);
  73698. }
  73699. }
  73700. else if (this._existingCamera) {
  73701. this._existingCamera.position = this._position;
  73702. this._scene.activeCamera = this._existingCamera;
  73703. }
  73704. this.updateButtonVisibility();
  73705. if (this._interactionsEnabled) {
  73706. this._scene.unregisterBeforeRender(this.beforeRender);
  73707. }
  73708. };
  73709. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73710. get: function () {
  73711. return this._position;
  73712. },
  73713. set: function (value) {
  73714. this._position = value;
  73715. if (this._scene.activeCamera) {
  73716. this._scene.activeCamera.position = value;
  73717. }
  73718. },
  73719. enumerable: true,
  73720. configurable: true
  73721. });
  73722. VRExperienceHelper.prototype.enableInteractions = function () {
  73723. var _this = this;
  73724. if (!this._interactionsEnabled) {
  73725. this._interactionsRequested = true;
  73726. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73727. this._enableInteractionOnController(this._webVRCamera.leftController);
  73728. }
  73729. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73730. this._enableInteractionOnController(this._webVRCamera.rightController);
  73731. }
  73732. this._createGazeTracker();
  73733. this.raySelectionPredicate = function (mesh) {
  73734. return mesh.isVisible;
  73735. };
  73736. this.meshSelectionPredicate = function (mesh) {
  73737. return true;
  73738. };
  73739. this._raySelectionPredicate = function (mesh) {
  73740. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  73741. && mesh.name.indexOf("teleportationTarget") === -1
  73742. && mesh.name.indexOf("torusTeleportation") === -1
  73743. && mesh.name.indexOf("laserPointer") === -1)) {
  73744. return _this.raySelectionPredicate(mesh);
  73745. }
  73746. return false;
  73747. };
  73748. this._interactionsEnabled = true;
  73749. }
  73750. };
  73751. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73752. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73753. if (this._floorMeshesCollection[i].id === mesh.id) {
  73754. return true;
  73755. }
  73756. }
  73757. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73758. return true;
  73759. }
  73760. return false;
  73761. };
  73762. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73763. if (!this._floorMeshesCollection) {
  73764. return;
  73765. }
  73766. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73767. return;
  73768. }
  73769. this._floorMeshesCollection.push(floorMesh);
  73770. };
  73771. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73772. if (!this._floorMeshesCollection) {
  73773. return;
  73774. }
  73775. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73776. if (meshIndex !== -1) {
  73777. this._floorMeshesCollection.splice(meshIndex, 1);
  73778. }
  73779. };
  73780. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73781. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73782. if (!this._teleportationInitialized) {
  73783. this._teleportationRequested = true;
  73784. this.enableInteractions();
  73785. if (vrTeleportationOptions.floorMeshName) {
  73786. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73787. }
  73788. if (vrTeleportationOptions.floorMeshes) {
  73789. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73790. }
  73791. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73792. this._enableTeleportationOnController(this._webVRCamera.leftController);
  73793. }
  73794. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73795. this._enableTeleportationOnController(this._webVRCamera.rightController);
  73796. }
  73797. // Creates an image processing post process for the vignette not relying
  73798. // on the main scene configuration for image processing to reduce setup and spaces
  73799. // (gamma/linear) conflicts.
  73800. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  73801. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  73802. imageProcessingConfiguration.vignetteEnabled = true;
  73803. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  73804. this._webVRCamera.detachPostProcess(this._postProcessMove);
  73805. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  73806. this._teleportationInitialized = true;
  73807. if (this._isDefaultTeleportationTarget) {
  73808. this._createTeleportationCircles();
  73809. }
  73810. }
  73811. };
  73812. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  73813. var _this = this;
  73814. var controllerMesh = webVRController.mesh;
  73815. if (controllerMesh) {
  73816. var makeNotPick = function (root) {
  73817. root.name += " laserPointer";
  73818. root.getChildMeshes().forEach(function (c) {
  73819. makeNotPick(c);
  73820. });
  73821. };
  73822. makeNotPick(controllerMesh);
  73823. var childMeshes = controllerMesh.getChildMeshes();
  73824. for (var i = 0; i < childMeshes.length; i++) {
  73825. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  73826. controllerMesh = childMeshes[i];
  73827. break;
  73828. }
  73829. }
  73830. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  73831. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  73832. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73833. laserPointerMaterial.alpha = 0.6;
  73834. laserPointer.material = laserPointerMaterial;
  73835. laserPointer.rotation.x = Math.PI / 2;
  73836. laserPointer.parent = controllerMesh;
  73837. laserPointer.position.z = -0.5;
  73838. laserPointer.isVisible = false;
  73839. if (webVRController.hand === "left") {
  73840. this._leftLaserPointer = laserPointer;
  73841. this._interactionsEnabledOnLeftController = true;
  73842. if (!this._rightLaserPointer) {
  73843. this._leftLaserPointer.isVisible = true;
  73844. }
  73845. }
  73846. else {
  73847. this._rightLaserPointer = laserPointer;
  73848. this._interactionsEnabledOnRightController = true;
  73849. if (!this._leftLaserPointer) {
  73850. this._rightLaserPointer.isVisible = true;
  73851. }
  73852. }
  73853. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  73854. // Enabling / disabling laserPointer
  73855. if (_this._displayLaserPointer && stateObject.value === 1) {
  73856. laserPointer.isVisible = !laserPointer.isVisible;
  73857. // Laser pointer can only be active on left or right, not both at the same time
  73858. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  73859. _this._rightLaserPointer.isVisible = false;
  73860. }
  73861. else if (_this._leftLaserPointer) {
  73862. _this._leftLaserPointer.isVisible = false;
  73863. }
  73864. }
  73865. });
  73866. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  73867. if (!_this._pointerDownOnMeshAsked) {
  73868. if (stateObject.value > _this._padSensibilityUp) {
  73869. _this._selectionPointerDown();
  73870. }
  73871. }
  73872. else if (stateObject.value < _this._padSensibilityDown) {
  73873. _this._selectionPointerUp();
  73874. }
  73875. });
  73876. }
  73877. };
  73878. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  73879. if (webVRController === void 0) { webVRController = null; }
  73880. if (!this._teleportationRequestInitiated) {
  73881. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  73882. if (webVRController) {
  73883. // If laser pointer wasn't enabled yet
  73884. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  73885. this._leftLaserPointer.isVisible = true;
  73886. if (this._rightLaserPointer) {
  73887. this._rightLaserPointer.isVisible = false;
  73888. }
  73889. }
  73890. else if (this._displayLaserPointer && this._rightLaserPointer) {
  73891. this._rightLaserPointer.isVisible = true;
  73892. if (this._leftLaserPointer) {
  73893. this._leftLaserPointer.isVisible = false;
  73894. }
  73895. }
  73896. }
  73897. this._teleportationRequestInitiated = true;
  73898. }
  73899. }
  73900. else {
  73901. // Listening to the proper controller values changes to confirm teleportation
  73902. if (webVRController == null
  73903. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  73904. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  73905. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  73906. if (this._teleportationAllowed) {
  73907. this._teleportationAllowed = false;
  73908. this._teleportCamera();
  73909. }
  73910. this._teleportationRequestInitiated = false;
  73911. }
  73912. }
  73913. }
  73914. };
  73915. VRExperienceHelper.prototype._selectionPointerDown = function () {
  73916. this._pointerDownOnMeshAsked = true;
  73917. if (this._currentMeshSelected && this._currentHit) {
  73918. this._scene.simulatePointerDown(this._currentHit);
  73919. }
  73920. };
  73921. VRExperienceHelper.prototype._selectionPointerUp = function () {
  73922. if (this._currentMeshSelected && this._currentHit) {
  73923. this._scene.simulatePointerUp(this._currentHit);
  73924. }
  73925. this._pointerDownOnMeshAsked = false;
  73926. };
  73927. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  73928. // Only rotate when user is not currently selecting a teleportation location
  73929. if (this._teleportationRequestInitiated) {
  73930. return;
  73931. }
  73932. if (!this._rotationLeftAsked) {
  73933. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  73934. this._rotationLeftAsked = true;
  73935. if (this._rotationAllowed) {
  73936. this._rotateCamera(false);
  73937. }
  73938. }
  73939. }
  73940. else {
  73941. if (stateObject.x > -this._padSensibilityDown) {
  73942. this._rotationLeftAsked = false;
  73943. }
  73944. }
  73945. if (!this._rotationRightAsked) {
  73946. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  73947. this._rotationRightAsked = true;
  73948. if (this._rotationAllowed) {
  73949. this._rotateCamera(true);
  73950. }
  73951. }
  73952. }
  73953. else {
  73954. if (stateObject.x < this._padSensibilityDown) {
  73955. this._rotationRightAsked = false;
  73956. }
  73957. }
  73958. };
  73959. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  73960. // Only teleport backwards when user is not currently selecting a teleportation location
  73961. if (this._teleportationRequestInitiated) {
  73962. return;
  73963. }
  73964. // Teleport backwards
  73965. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  73966. if (!this._teleportationBackRequestInitiated) {
  73967. if (!this.currentVRCamera) {
  73968. return;
  73969. }
  73970. // Get rotation and position of the current camera
  73971. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  73972. var position = this.currentVRCamera.position;
  73973. // If the camera has device position, use that instead
  73974. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  73975. rotation = this.currentVRCamera.deviceRotationQuaternion;
  73976. position = this.currentVRCamera.devicePosition;
  73977. }
  73978. // Get matrix with only the y rotation of the device rotation
  73979. rotation.toEulerAnglesToRef(this._workingVector);
  73980. this._workingVector.z = 0;
  73981. this._workingVector.x = 0;
  73982. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  73983. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  73984. // Rotate backwards ray by device rotation to cast at the ground behind the user
  73985. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  73986. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  73987. var ray = new BABYLON.Ray(position, this._workingVector);
  73988. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73989. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  73990. this._teleportCamera(hit.pickedPoint);
  73991. }
  73992. this._teleportationBackRequestInitiated = true;
  73993. }
  73994. }
  73995. else {
  73996. this._teleportationBackRequestInitiated = false;
  73997. }
  73998. };
  73999. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  74000. var _this = this;
  74001. var controllerMesh = webVRController.mesh;
  74002. if (controllerMesh) {
  74003. if (webVRController.hand === "left") {
  74004. if (!this._interactionsEnabledOnLeftController) {
  74005. this._enableInteractionOnController(webVRController);
  74006. }
  74007. this._teleportationEnabledOnLeftController = true;
  74008. }
  74009. else {
  74010. if (!this._interactionsEnabledOnRightController) {
  74011. this._enableInteractionOnController(webVRController);
  74012. }
  74013. this._teleportationEnabledOnRightController = true;
  74014. }
  74015. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  74016. this._dpadPressed = false;
  74017. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  74018. _this._dpadPressed = stateObject.pressed;
  74019. if (!_this._dpadPressed) {
  74020. _this._rotationLeftAsked = false;
  74021. _this._rotationRightAsked = false;
  74022. _this._teleportationBackRequestInitiated = false;
  74023. }
  74024. });
  74025. }
  74026. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  74027. if (_this.teleportationEnabled) {
  74028. _this._checkTeleportBackwards(stateObject);
  74029. _this._checkTeleportWithRay(stateObject, webVRController);
  74030. }
  74031. _this._checkRotate(stateObject);
  74032. });
  74033. }
  74034. };
  74035. // Gaze support used to point to teleport or to interact with an object
  74036. VRExperienceHelper.prototype._createGazeTracker = function () {
  74037. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  74038. this._gazeTracker.bakeCurrentTransformIntoVertices();
  74039. this._gazeTracker.isPickable = false;
  74040. this._gazeTracker.isVisible = false;
  74041. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  74042. targetMat.specularColor = BABYLON.Color3.Black();
  74043. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  74044. targetMat.backFaceCulling = false;
  74045. this._gazeTracker.material = targetMat;
  74046. };
  74047. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  74048. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  74049. this._teleportationTarget.isPickable = false;
  74050. var length = 512;
  74051. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  74052. dynamicTexture.hasAlpha = true;
  74053. var context = dynamicTexture.getContext();
  74054. var centerX = length / 2;
  74055. var centerY = length / 2;
  74056. var radius = 200;
  74057. context.beginPath();
  74058. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  74059. context.fillStyle = this._teleportationFillColor;
  74060. context.fill();
  74061. context.lineWidth = 10;
  74062. context.strokeStyle = this._teleportationBorderColor;
  74063. context.stroke();
  74064. context.closePath();
  74065. dynamicTexture.update();
  74066. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  74067. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  74068. this._teleportationTarget.material = teleportationCircleMaterial;
  74069. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  74070. torus.isPickable = false;
  74071. torus.parent = this._teleportationTarget;
  74072. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  74073. var keys = [];
  74074. keys.push({
  74075. frame: 0,
  74076. value: 0
  74077. });
  74078. keys.push({
  74079. frame: 30,
  74080. value: 0.4
  74081. });
  74082. keys.push({
  74083. frame: 60,
  74084. value: 0
  74085. });
  74086. animationInnerCircle.setKeys(keys);
  74087. var easingFunction = new BABYLON.SineEase();
  74088. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  74089. animationInnerCircle.setEasingFunction(easingFunction);
  74090. torus.animations = [];
  74091. torus.animations.push(animationInnerCircle);
  74092. this._scene.beginAnimation(torus, 0, 60, true);
  74093. this._hideTeleportationTarget();
  74094. };
  74095. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  74096. if (this._teleportationInitialized) {
  74097. this._teleportationTarget.isVisible = true;
  74098. if (this._isDefaultTeleportationTarget) {
  74099. this._teleportationTarget.getChildren()[0].isVisible = true;
  74100. }
  74101. }
  74102. };
  74103. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  74104. if (this._teleportationInitialized) {
  74105. this._teleportationTarget.isVisible = false;
  74106. if (this._isDefaultTeleportationTarget) {
  74107. this._teleportationTarget.getChildren()[0].isVisible = false;
  74108. }
  74109. }
  74110. };
  74111. VRExperienceHelper.prototype._rotateCamera = function (right) {
  74112. var _this = this;
  74113. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74114. return;
  74115. }
  74116. if (right) {
  74117. this._rotationAngle++;
  74118. }
  74119. else {
  74120. this._rotationAngle--;
  74121. }
  74122. this.currentVRCamera.animations = [];
  74123. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  74124. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74125. var animationRotationKeys = [];
  74126. animationRotationKeys.push({
  74127. frame: 0,
  74128. value: this.currentVRCamera.rotationQuaternion
  74129. });
  74130. animationRotationKeys.push({
  74131. frame: 6,
  74132. value: target
  74133. });
  74134. animationRotation.setKeys(animationRotationKeys);
  74135. animationRotation.setEasingFunction(this._circleEase);
  74136. this.currentVRCamera.animations.push(animationRotation);
  74137. this._postProcessMove.animations = [];
  74138. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74139. var vignetteWeightKeys = [];
  74140. vignetteWeightKeys.push({
  74141. frame: 0,
  74142. value: 0
  74143. });
  74144. vignetteWeightKeys.push({
  74145. frame: 3,
  74146. value: 4
  74147. });
  74148. vignetteWeightKeys.push({
  74149. frame: 6,
  74150. value: 0
  74151. });
  74152. animationPP.setKeys(vignetteWeightKeys);
  74153. animationPP.setEasingFunction(this._circleEase);
  74154. this._postProcessMove.animations.push(animationPP);
  74155. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74156. var vignetteStretchKeys = [];
  74157. vignetteStretchKeys.push({
  74158. frame: 0,
  74159. value: 0
  74160. });
  74161. vignetteStretchKeys.push({
  74162. frame: 3,
  74163. value: 10
  74164. });
  74165. vignetteStretchKeys.push({
  74166. frame: 6,
  74167. value: 0
  74168. });
  74169. animationPP2.setKeys(vignetteStretchKeys);
  74170. animationPP2.setEasingFunction(this._circleEase);
  74171. this._postProcessMove.animations.push(animationPP2);
  74172. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74173. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74174. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74175. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  74176. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74177. });
  74178. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  74179. };
  74180. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  74181. if (hit.pickedPoint) {
  74182. this._teleportationAllowed = true;
  74183. if (this._teleportationRequestInitiated) {
  74184. this._displayTeleportationTarget();
  74185. }
  74186. else {
  74187. this._hideTeleportationTarget();
  74188. }
  74189. this._haloCenter.copyFrom(hit.pickedPoint);
  74190. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  74191. var pickNormal = hit.getNormal(true, false);
  74192. if (pickNormal) {
  74193. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74194. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74195. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  74196. }
  74197. this._teleportationTarget.position.y += 0.1;
  74198. }
  74199. };
  74200. VRExperienceHelper.prototype._teleportCamera = function (location) {
  74201. var _this = this;
  74202. if (location === void 0) { location = null; }
  74203. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74204. return;
  74205. }
  74206. if (!location) {
  74207. location = this._haloCenter;
  74208. }
  74209. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  74210. // offset of the headset from the anchor.
  74211. if (this.webVRCamera.leftCamera) {
  74212. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  74213. this._workingVector.subtractInPlace(this.webVRCamera.position);
  74214. location.subtractToRef(this._workingVector, this._workingVector);
  74215. }
  74216. else {
  74217. this._workingVector.copyFrom(location);
  74218. }
  74219. // Add height to account for user's height offset
  74220. if (this.isInVRMode) {
  74221. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  74222. }
  74223. else {
  74224. this._workingVector.y += this._defaultHeight;
  74225. }
  74226. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  74227. // Create animation from the camera's position to the new location
  74228. this.currentVRCamera.animations = [];
  74229. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74230. var animationCameraTeleportationKeys = [{
  74231. frame: 0,
  74232. value: this.currentVRCamera.position
  74233. },
  74234. {
  74235. frame: 11,
  74236. value: this._workingVector
  74237. }
  74238. ];
  74239. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  74240. animationCameraTeleportation.setEasingFunction(this._circleEase);
  74241. this.currentVRCamera.animations.push(animationCameraTeleportation);
  74242. this._postProcessMove.animations = [];
  74243. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74244. var vignetteWeightKeys = [];
  74245. vignetteWeightKeys.push({
  74246. frame: 0,
  74247. value: 0
  74248. });
  74249. vignetteWeightKeys.push({
  74250. frame: 5,
  74251. value: 8
  74252. });
  74253. vignetteWeightKeys.push({
  74254. frame: 11,
  74255. value: 0
  74256. });
  74257. animationPP.setKeys(vignetteWeightKeys);
  74258. this._postProcessMove.animations.push(animationPP);
  74259. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  74260. var vignetteStretchKeys = [];
  74261. vignetteStretchKeys.push({
  74262. frame: 0,
  74263. value: 0
  74264. });
  74265. vignetteStretchKeys.push({
  74266. frame: 5,
  74267. value: 10
  74268. });
  74269. vignetteStretchKeys.push({
  74270. frame: 11,
  74271. value: 0
  74272. });
  74273. animationPP2.setKeys(vignetteStretchKeys);
  74274. this._postProcessMove.animations.push(animationPP2);
  74275. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  74276. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  74277. this._webVRCamera.attachPostProcess(this._postProcessMove);
  74278. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  74279. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  74280. });
  74281. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  74282. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  74283. });
  74284. };
  74285. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  74286. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  74287. return;
  74288. }
  74289. var ray;
  74290. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  74291. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  74292. }
  74293. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  74294. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  74295. }
  74296. else {
  74297. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  74298. }
  74299. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  74300. // Moving the gazeTracker on the mesh face targetted
  74301. if (hit && hit.pickedPoint) {
  74302. if (this._displayGaze) {
  74303. var multiplier = 1;
  74304. this._gazeTracker.isVisible = true;
  74305. if (this._isActionableMesh) {
  74306. multiplier = 3;
  74307. }
  74308. this._gazeTracker.scaling.x = hit.distance * multiplier;
  74309. this._gazeTracker.scaling.y = hit.distance * multiplier;
  74310. this._gazeTracker.scaling.z = hit.distance * multiplier;
  74311. var pickNormal = hit.getNormal();
  74312. // To avoid z-fighting
  74313. var deltaFighting = 0.002;
  74314. if (pickNormal) {
  74315. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  74316. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  74317. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  74318. }
  74319. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  74320. if (this._gazeTracker.position.x < 0) {
  74321. this._gazeTracker.position.x += deltaFighting;
  74322. }
  74323. else {
  74324. this._gazeTracker.position.x -= deltaFighting;
  74325. }
  74326. if (this._gazeTracker.position.y < 0) {
  74327. this._gazeTracker.position.y += deltaFighting;
  74328. }
  74329. else {
  74330. this._gazeTracker.position.y -= deltaFighting;
  74331. }
  74332. if (this._gazeTracker.position.z < 0) {
  74333. this._gazeTracker.position.z += deltaFighting;
  74334. }
  74335. else {
  74336. this._gazeTracker.position.z -= deltaFighting;
  74337. }
  74338. }
  74339. // Changing the size of the laser pointer based on the distance from the targetted point
  74340. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  74341. this._rightLaserPointer.scaling.y = hit.distance;
  74342. this._rightLaserPointer.position.z = -hit.distance / 2;
  74343. }
  74344. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  74345. this._leftLaserPointer.scaling.y = hit.distance;
  74346. this._leftLaserPointer.position.z = -hit.distance / 2;
  74347. }
  74348. }
  74349. else {
  74350. this._gazeTracker.isVisible = false;
  74351. }
  74352. if (hit && hit.pickedMesh) {
  74353. this._currentHit = hit;
  74354. if (this._pointerDownOnMeshAsked) {
  74355. this._scene.simulatePointerMove(this._currentHit);
  74356. }
  74357. // The object selected is the floor, we're in a teleportation scenario
  74358. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  74359. // Moving the teleportation area to this targetted point
  74360. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  74361. if (this._currentMeshSelected &&
  74362. !this._isTeleportationFloor(this._currentMeshSelected)) {
  74363. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74364. }
  74365. this._currentMeshSelected = null;
  74366. this._moveTeleportationSelectorTo(hit);
  74367. return;
  74368. }
  74369. // If not, we're in a selection scenario
  74370. this._hideTeleportationTarget();
  74371. this._teleportationAllowed = false;
  74372. if (hit.pickedMesh !== this._currentMeshSelected) {
  74373. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  74374. this.onNewMeshPicked.notifyObservers(hit);
  74375. this._currentMeshSelected = hit.pickedMesh;
  74376. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  74377. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  74378. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  74379. this._isActionableMesh = true;
  74380. }
  74381. else {
  74382. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74383. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74384. this._isActionableMesh = false;
  74385. }
  74386. try {
  74387. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  74388. }
  74389. catch (err) {
  74390. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  74391. }
  74392. }
  74393. else {
  74394. if (this._currentMeshSelected) {
  74395. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  74396. }
  74397. this._currentMeshSelected = null;
  74398. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74399. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74400. }
  74401. }
  74402. }
  74403. else {
  74404. this._currentHit = null;
  74405. this._currentMeshSelected = null;
  74406. this._teleportationAllowed = false;
  74407. this._hideTeleportationTarget();
  74408. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74409. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  74410. }
  74411. };
  74412. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  74413. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  74414. this._leftLaserPointer.material.emissiveColor = color;
  74415. }
  74416. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  74417. this._rightLaserPointer.material.emissiveColor = color;
  74418. }
  74419. };
  74420. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  74421. if (this._gazeTracker.material) {
  74422. this._gazeTracker.material.emissiveColor = color;
  74423. }
  74424. };
  74425. VRExperienceHelper.prototype.dispose = function () {
  74426. if (this.isInVRMode) {
  74427. this.exitVR();
  74428. }
  74429. if (this._passProcessMove) {
  74430. this._passProcessMove.dispose();
  74431. }
  74432. if (this._postProcessMove) {
  74433. this._postProcessMove.dispose();
  74434. }
  74435. if (this._webVRCamera) {
  74436. this._webVRCamera.dispose();
  74437. }
  74438. if (this._vrDeviceOrientationCamera) {
  74439. this._vrDeviceOrientationCamera.dispose();
  74440. }
  74441. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  74442. document.body.removeChild(this._btnVR);
  74443. }
  74444. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  74445. this._deviceOrientationCamera.dispose();
  74446. }
  74447. if (this._gazeTracker) {
  74448. this._gazeTracker.dispose();
  74449. }
  74450. if (this._teleportationTarget) {
  74451. this._teleportationTarget.dispose();
  74452. }
  74453. this._floorMeshesCollection = [];
  74454. document.removeEventListener("keydown", this._onKeyDown);
  74455. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74456. window.removeEventListener("resize", this._onResize);
  74457. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74458. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74459. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74460. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74461. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74462. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74463. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74464. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74465. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74466. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74467. this._scene.unregisterBeforeRender(this.beforeRender);
  74468. };
  74469. VRExperienceHelper.prototype.getClassName = function () {
  74470. return "VRExperienceHelper";
  74471. };
  74472. return VRExperienceHelper;
  74473. }());
  74474. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74475. })(BABYLON || (BABYLON = {}));
  74476. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74477. // Mainly based on these 2 articles :
  74478. // 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
  74479. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74480. var BABYLON;
  74481. (function (BABYLON) {
  74482. var JoystickAxis;
  74483. (function (JoystickAxis) {
  74484. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74485. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74486. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74487. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74488. var VirtualJoystick = /** @class */ (function () {
  74489. function VirtualJoystick(leftJoystick) {
  74490. var _this = this;
  74491. if (leftJoystick) {
  74492. this._leftJoystick = true;
  74493. }
  74494. else {
  74495. this._leftJoystick = false;
  74496. }
  74497. VirtualJoystick._globalJoystickIndex++;
  74498. // By default left & right arrow keys are moving the X
  74499. // and up & down keys are moving the Y
  74500. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74501. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74502. this.reverseLeftRight = false;
  74503. this.reverseUpDown = false;
  74504. // collections of pointers
  74505. this._touches = new BABYLON.StringDictionary();
  74506. this.deltaPosition = BABYLON.Vector3.Zero();
  74507. this._joystickSensibility = 25;
  74508. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74509. this._onResize = function (evt) {
  74510. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74511. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74512. if (VirtualJoystick.vjCanvas) {
  74513. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74514. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74515. }
  74516. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74517. };
  74518. // injecting a canvas element on top of the canvas 3D game
  74519. if (!VirtualJoystick.vjCanvas) {
  74520. window.addEventListener("resize", this._onResize, false);
  74521. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74522. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74523. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74524. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74525. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74526. VirtualJoystick.vjCanvas.style.width = "100%";
  74527. VirtualJoystick.vjCanvas.style.height = "100%";
  74528. VirtualJoystick.vjCanvas.style.position = "absolute";
  74529. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74530. VirtualJoystick.vjCanvas.style.top = "0px";
  74531. VirtualJoystick.vjCanvas.style.left = "0px";
  74532. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74533. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74534. // Support for jQuery PEP polyfill
  74535. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74536. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74537. if (!context) {
  74538. throw new Error("Unable to create canvas for virtual joystick");
  74539. }
  74540. VirtualJoystick.vjCanvasContext = context;
  74541. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74542. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74543. document.body.appendChild(VirtualJoystick.vjCanvas);
  74544. }
  74545. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74546. this.pressed = false;
  74547. // default joystick color
  74548. this._joystickColor = "cyan";
  74549. this._joystickPointerID = -1;
  74550. // current joystick position
  74551. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74552. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74553. // origin joystick position
  74554. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74555. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74556. this._onPointerDownHandlerRef = function (evt) {
  74557. _this._onPointerDown(evt);
  74558. };
  74559. this._onPointerMoveHandlerRef = function (evt) {
  74560. _this._onPointerMove(evt);
  74561. };
  74562. this._onPointerUpHandlerRef = function (evt) {
  74563. _this._onPointerUp(evt);
  74564. };
  74565. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74566. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74567. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74568. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74569. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74570. evt.preventDefault(); // Disables system menu
  74571. }, false);
  74572. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74573. }
  74574. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74575. this._joystickSensibility = newJoystickSensibility;
  74576. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74577. };
  74578. VirtualJoystick.prototype._onPointerDown = function (e) {
  74579. var positionOnScreenCondition;
  74580. e.preventDefault();
  74581. if (this._leftJoystick === true) {
  74582. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74583. }
  74584. else {
  74585. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74586. }
  74587. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74588. // First contact will be dedicated to the virtual joystick
  74589. this._joystickPointerID = e.pointerId;
  74590. this._joystickPointerStartPos.x = e.clientX;
  74591. this._joystickPointerStartPos.y = e.clientY;
  74592. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74593. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74594. this._deltaJoystickVector.x = 0;
  74595. this._deltaJoystickVector.y = 0;
  74596. this.pressed = true;
  74597. this._touches.add(e.pointerId.toString(), e);
  74598. }
  74599. else {
  74600. // You can only trigger the action buttons with a joystick declared
  74601. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74602. this._action();
  74603. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74604. }
  74605. }
  74606. };
  74607. VirtualJoystick.prototype._onPointerMove = function (e) {
  74608. // If the current pointer is the one associated to the joystick (first touch contact)
  74609. if (this._joystickPointerID == e.pointerId) {
  74610. this._joystickPointerPos.x = e.clientX;
  74611. this._joystickPointerPos.y = e.clientY;
  74612. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74613. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74614. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74615. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74616. switch (this._axisTargetedByLeftAndRight) {
  74617. case JoystickAxis.X:
  74618. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74619. break;
  74620. case JoystickAxis.Y:
  74621. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74622. break;
  74623. case JoystickAxis.Z:
  74624. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74625. break;
  74626. }
  74627. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74628. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74629. switch (this._axisTargetedByUpAndDown) {
  74630. case JoystickAxis.X:
  74631. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74632. break;
  74633. case JoystickAxis.Y:
  74634. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74635. break;
  74636. case JoystickAxis.Z:
  74637. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74638. break;
  74639. }
  74640. }
  74641. else {
  74642. var data = this._touches.get(e.pointerId.toString());
  74643. if (data) {
  74644. data.x = e.clientX;
  74645. data.y = e.clientY;
  74646. }
  74647. }
  74648. };
  74649. VirtualJoystick.prototype._onPointerUp = function (e) {
  74650. if (this._joystickPointerID == e.pointerId) {
  74651. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74652. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74653. this._joystickPointerID = -1;
  74654. this.pressed = false;
  74655. }
  74656. else {
  74657. var touch = this._touches.get(e.pointerId.toString());
  74658. if (touch) {
  74659. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74660. }
  74661. }
  74662. this._deltaJoystickVector.x = 0;
  74663. this._deltaJoystickVector.y = 0;
  74664. this._touches.remove(e.pointerId.toString());
  74665. };
  74666. /**
  74667. * Change the color of the virtual joystick
  74668. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74669. */
  74670. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74671. this._joystickColor = newColor;
  74672. };
  74673. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74674. this._action = action;
  74675. };
  74676. // Define which axis you'd like to control for left & right
  74677. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74678. switch (axis) {
  74679. case JoystickAxis.X:
  74680. case JoystickAxis.Y:
  74681. case JoystickAxis.Z:
  74682. this._axisTargetedByLeftAndRight = axis;
  74683. break;
  74684. default:
  74685. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74686. break;
  74687. }
  74688. };
  74689. // Define which axis you'd like to control for up & down
  74690. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74691. switch (axis) {
  74692. case JoystickAxis.X:
  74693. case JoystickAxis.Y:
  74694. case JoystickAxis.Z:
  74695. this._axisTargetedByUpAndDown = axis;
  74696. break;
  74697. default:
  74698. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74699. break;
  74700. }
  74701. };
  74702. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74703. var _this = this;
  74704. if (this.pressed) {
  74705. this._touches.forEach(function (key, touch) {
  74706. if (touch.pointerId === _this._joystickPointerID) {
  74707. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74708. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74709. VirtualJoystick.vjCanvasContext.beginPath();
  74710. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74711. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74712. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74713. VirtualJoystick.vjCanvasContext.stroke();
  74714. VirtualJoystick.vjCanvasContext.closePath();
  74715. VirtualJoystick.vjCanvasContext.beginPath();
  74716. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74717. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74718. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74719. VirtualJoystick.vjCanvasContext.stroke();
  74720. VirtualJoystick.vjCanvasContext.closePath();
  74721. VirtualJoystick.vjCanvasContext.beginPath();
  74722. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74723. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74724. VirtualJoystick.vjCanvasContext.stroke();
  74725. VirtualJoystick.vjCanvasContext.closePath();
  74726. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74727. }
  74728. else {
  74729. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74730. VirtualJoystick.vjCanvasContext.beginPath();
  74731. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74732. VirtualJoystick.vjCanvasContext.beginPath();
  74733. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74734. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74735. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74736. VirtualJoystick.vjCanvasContext.stroke();
  74737. VirtualJoystick.vjCanvasContext.closePath();
  74738. touch.prevX = touch.x;
  74739. touch.prevY = touch.y;
  74740. }
  74741. ;
  74742. });
  74743. }
  74744. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74745. };
  74746. VirtualJoystick.prototype.releaseCanvas = function () {
  74747. if (VirtualJoystick.vjCanvas) {
  74748. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74749. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74750. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74751. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74752. window.removeEventListener("resize", this._onResize);
  74753. document.body.removeChild(VirtualJoystick.vjCanvas);
  74754. VirtualJoystick.vjCanvas = null;
  74755. }
  74756. };
  74757. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74758. VirtualJoystick._globalJoystickIndex = 0;
  74759. return VirtualJoystick;
  74760. }());
  74761. BABYLON.VirtualJoystick = VirtualJoystick;
  74762. })(BABYLON || (BABYLON = {}));
  74763. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74764. var BABYLON;
  74765. (function (BABYLON) {
  74766. // We're mainly based on the logic defined into the FreeCamera code
  74767. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74768. __extends(VirtualJoysticksCamera, _super);
  74769. function VirtualJoysticksCamera(name, position, scene) {
  74770. var _this = _super.call(this, name, position, scene) || this;
  74771. _this.inputs.addVirtualJoystick();
  74772. return _this;
  74773. }
  74774. VirtualJoysticksCamera.prototype.getClassName = function () {
  74775. return "VirtualJoysticksCamera";
  74776. };
  74777. return VirtualJoysticksCamera;
  74778. }(BABYLON.FreeCamera));
  74779. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74780. })(BABYLON || (BABYLON = {}));
  74781. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74782. var BABYLON;
  74783. (function (BABYLON) {
  74784. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74785. function FreeCameraVirtualJoystickInput() {
  74786. }
  74787. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74788. return this._leftjoystick;
  74789. };
  74790. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74791. return this._rightjoystick;
  74792. };
  74793. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  74794. if (this._leftjoystick) {
  74795. var camera = this.camera;
  74796. var speed = camera._computeLocalCameraSpeed() * 50;
  74797. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  74798. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  74799. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  74800. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  74801. if (!this._leftjoystick.pressed) {
  74802. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  74803. }
  74804. if (!this._rightjoystick.pressed) {
  74805. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  74806. }
  74807. }
  74808. };
  74809. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  74810. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  74811. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  74812. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  74813. this._leftjoystick.setJoystickSensibility(0.15);
  74814. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  74815. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  74816. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  74817. this._rightjoystick.reverseUpDown = true;
  74818. this._rightjoystick.setJoystickSensibility(0.05);
  74819. this._rightjoystick.setJoystickColor("yellow");
  74820. };
  74821. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  74822. this._leftjoystick.releaseCanvas();
  74823. this._rightjoystick.releaseCanvas();
  74824. };
  74825. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  74826. return "FreeCameraVirtualJoystickInput";
  74827. };
  74828. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  74829. return "virtualJoystick";
  74830. };
  74831. return FreeCameraVirtualJoystickInput;
  74832. }());
  74833. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  74834. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  74835. })(BABYLON || (BABYLON = {}));
  74836. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  74837. var BABYLON;
  74838. (function (BABYLON) {
  74839. var SimplificationSettings = /** @class */ (function () {
  74840. function SimplificationSettings(quality, distance, optimizeMesh) {
  74841. this.quality = quality;
  74842. this.distance = distance;
  74843. this.optimizeMesh = optimizeMesh;
  74844. }
  74845. return SimplificationSettings;
  74846. }());
  74847. BABYLON.SimplificationSettings = SimplificationSettings;
  74848. var SimplificationQueue = /** @class */ (function () {
  74849. function SimplificationQueue() {
  74850. this.running = false;
  74851. this._simplificationArray = [];
  74852. }
  74853. SimplificationQueue.prototype.addTask = function (task) {
  74854. this._simplificationArray.push(task);
  74855. };
  74856. SimplificationQueue.prototype.executeNext = function () {
  74857. var task = this._simplificationArray.pop();
  74858. if (task) {
  74859. this.running = true;
  74860. this.runSimplification(task);
  74861. }
  74862. else {
  74863. this.running = false;
  74864. }
  74865. };
  74866. SimplificationQueue.prototype.runSimplification = function (task) {
  74867. var _this = this;
  74868. if (task.parallelProcessing) {
  74869. //parallel simplifier
  74870. task.settings.forEach(function (setting) {
  74871. var simplifier = _this.getSimplifier(task);
  74872. simplifier.simplify(setting, function (newMesh) {
  74873. task.mesh.addLODLevel(setting.distance, newMesh);
  74874. newMesh.isVisible = true;
  74875. //check if it is the last
  74876. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  74877. //all done, run the success callback.
  74878. task.successCallback();
  74879. }
  74880. _this.executeNext();
  74881. });
  74882. });
  74883. }
  74884. else {
  74885. //single simplifier.
  74886. var simplifier = this.getSimplifier(task);
  74887. var runDecimation = function (setting, callback) {
  74888. simplifier.simplify(setting, function (newMesh) {
  74889. task.mesh.addLODLevel(setting.distance, newMesh);
  74890. newMesh.isVisible = true;
  74891. //run the next quality level
  74892. callback();
  74893. });
  74894. };
  74895. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  74896. runDecimation(task.settings[loop.index], function () {
  74897. loop.executeNext();
  74898. });
  74899. }, function () {
  74900. //execution ended, run the success callback.
  74901. if (task.successCallback) {
  74902. task.successCallback();
  74903. }
  74904. _this.executeNext();
  74905. });
  74906. }
  74907. };
  74908. SimplificationQueue.prototype.getSimplifier = function (task) {
  74909. switch (task.simplificationType) {
  74910. case SimplificationType.QUADRATIC:
  74911. default:
  74912. return new QuadraticErrorSimplification(task.mesh);
  74913. }
  74914. };
  74915. return SimplificationQueue;
  74916. }());
  74917. BABYLON.SimplificationQueue = SimplificationQueue;
  74918. /**
  74919. * The implemented types of simplification.
  74920. * At the moment only Quadratic Error Decimation is implemented.
  74921. */
  74922. var SimplificationType;
  74923. (function (SimplificationType) {
  74924. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  74925. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  74926. var DecimationTriangle = /** @class */ (function () {
  74927. function DecimationTriangle(vertices) {
  74928. this.vertices = vertices;
  74929. this.error = new Array(4);
  74930. this.deleted = false;
  74931. this.isDirty = false;
  74932. this.deletePending = false;
  74933. this.borderFactor = 0;
  74934. }
  74935. return DecimationTriangle;
  74936. }());
  74937. BABYLON.DecimationTriangle = DecimationTriangle;
  74938. var DecimationVertex = /** @class */ (function () {
  74939. function DecimationVertex(position, id) {
  74940. this.position = position;
  74941. this.id = id;
  74942. this.isBorder = true;
  74943. this.q = new QuadraticMatrix();
  74944. this.triangleCount = 0;
  74945. this.triangleStart = 0;
  74946. this.originalOffsets = [];
  74947. }
  74948. DecimationVertex.prototype.updatePosition = function (newPosition) {
  74949. this.position.copyFrom(newPosition);
  74950. };
  74951. return DecimationVertex;
  74952. }());
  74953. BABYLON.DecimationVertex = DecimationVertex;
  74954. var QuadraticMatrix = /** @class */ (function () {
  74955. function QuadraticMatrix(data) {
  74956. this.data = new Array(10);
  74957. for (var i = 0; i < 10; ++i) {
  74958. if (data && data[i]) {
  74959. this.data[i] = data[i];
  74960. }
  74961. else {
  74962. this.data[i] = 0;
  74963. }
  74964. }
  74965. }
  74966. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  74967. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  74968. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  74969. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  74970. return det;
  74971. };
  74972. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  74973. for (var i = 0; i < 10; ++i) {
  74974. this.data[i] += matrix.data[i];
  74975. }
  74976. };
  74977. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  74978. for (var i = 0; i < 10; ++i) {
  74979. this.data[i] += data[i];
  74980. }
  74981. };
  74982. QuadraticMatrix.prototype.add = function (matrix) {
  74983. var m = new QuadraticMatrix();
  74984. for (var i = 0; i < 10; ++i) {
  74985. m.data[i] = this.data[i] + matrix.data[i];
  74986. }
  74987. return m;
  74988. };
  74989. QuadraticMatrix.FromData = function (a, b, c, d) {
  74990. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  74991. };
  74992. //returning an array to avoid garbage collection
  74993. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  74994. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  74995. };
  74996. return QuadraticMatrix;
  74997. }());
  74998. BABYLON.QuadraticMatrix = QuadraticMatrix;
  74999. var Reference = /** @class */ (function () {
  75000. function Reference(vertexId, triangleId) {
  75001. this.vertexId = vertexId;
  75002. this.triangleId = triangleId;
  75003. }
  75004. return Reference;
  75005. }());
  75006. BABYLON.Reference = Reference;
  75007. /**
  75008. * An implementation of the Quadratic Error simplification algorithm.
  75009. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  75010. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  75011. * @author RaananW
  75012. */
  75013. var QuadraticErrorSimplification = /** @class */ (function () {
  75014. function QuadraticErrorSimplification(_mesh) {
  75015. this._mesh = _mesh;
  75016. this.syncIterations = 5000;
  75017. this.aggressiveness = 7;
  75018. this.decimationIterations = 100;
  75019. this.boundingBoxEpsilon = BABYLON.Epsilon;
  75020. }
  75021. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  75022. var _this = this;
  75023. this.initDecimatedMesh();
  75024. //iterating through the submeshes array, one after the other.
  75025. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  75026. _this.initWithMesh(loop.index, function () {
  75027. _this.runDecimation(settings, loop.index, function () {
  75028. loop.executeNext();
  75029. });
  75030. }, settings.optimizeMesh);
  75031. }, function () {
  75032. setTimeout(function () {
  75033. successCallback(_this._reconstructedMesh);
  75034. }, 0);
  75035. });
  75036. };
  75037. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  75038. var _this = this;
  75039. var targetCount = ~~(this.triangles.length * settings.quality);
  75040. var deletedTriangles = 0;
  75041. var triangleCount = this.triangles.length;
  75042. var iterationFunction = function (iteration, callback) {
  75043. setTimeout(function () {
  75044. if (iteration % 5 === 0) {
  75045. _this.updateMesh(iteration === 0);
  75046. }
  75047. for (var i = 0; i < _this.triangles.length; ++i) {
  75048. _this.triangles[i].isDirty = false;
  75049. }
  75050. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  75051. var trianglesIterator = function (i) {
  75052. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  75053. var t = _this.triangles[tIdx];
  75054. if (!t)
  75055. return;
  75056. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  75057. return;
  75058. }
  75059. for (var j = 0; j < 3; ++j) {
  75060. if (t.error[j] < threshold) {
  75061. var deleted0 = [];
  75062. var deleted1 = [];
  75063. var v0 = t.vertices[j];
  75064. var v1 = t.vertices[(j + 1) % 3];
  75065. if (v0.isBorder || v1.isBorder)
  75066. continue;
  75067. var p = BABYLON.Vector3.Zero();
  75068. var n = BABYLON.Vector3.Zero();
  75069. var uv = BABYLON.Vector2.Zero();
  75070. var color = new BABYLON.Color4(0, 0, 0, 1);
  75071. _this.calculateError(v0, v1, p, n, uv, color);
  75072. var delTr = new Array();
  75073. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  75074. continue;
  75075. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  75076. continue;
  75077. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  75078. continue;
  75079. var uniqueArray = new Array();
  75080. delTr.forEach(function (deletedT) {
  75081. if (uniqueArray.indexOf(deletedT) === -1) {
  75082. deletedT.deletePending = true;
  75083. uniqueArray.push(deletedT);
  75084. }
  75085. });
  75086. if (uniqueArray.length % 2 !== 0) {
  75087. continue;
  75088. }
  75089. v0.q = v1.q.add(v0.q);
  75090. v0.updatePosition(p);
  75091. var tStart = _this.references.length;
  75092. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  75093. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  75094. var tCount = _this.references.length - tStart;
  75095. if (tCount <= v0.triangleCount) {
  75096. if (tCount) {
  75097. for (var c = 0; c < tCount; c++) {
  75098. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  75099. }
  75100. }
  75101. }
  75102. else {
  75103. v0.triangleStart = tStart;
  75104. }
  75105. v0.triangleCount = tCount;
  75106. break;
  75107. }
  75108. }
  75109. };
  75110. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  75111. }, 0);
  75112. };
  75113. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  75114. if (triangleCount - deletedTriangles <= targetCount)
  75115. loop.breakLoop();
  75116. else {
  75117. iterationFunction(loop.index, function () {
  75118. loop.executeNext();
  75119. });
  75120. }
  75121. }, function () {
  75122. setTimeout(function () {
  75123. //reconstruct this part of the mesh
  75124. _this.reconstructMesh(submeshIndex);
  75125. successCallback();
  75126. }, 0);
  75127. });
  75128. };
  75129. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  75130. var _this = this;
  75131. this.vertices = [];
  75132. this.triangles = [];
  75133. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75134. var indices = this._mesh.getIndices();
  75135. var submesh = this._mesh.subMeshes[submeshIndex];
  75136. var findInVertices = function (positionToSearch) {
  75137. if (optimizeMesh) {
  75138. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  75139. if (_this.vertices[ii].position.equals(positionToSearch)) {
  75140. return _this.vertices[ii];
  75141. }
  75142. }
  75143. }
  75144. return null;
  75145. };
  75146. var vertexReferences = [];
  75147. var vertexInit = function (i) {
  75148. if (!positionData) {
  75149. return;
  75150. }
  75151. var offset = i + submesh.verticesStart;
  75152. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  75153. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  75154. vertex.originalOffsets.push(offset);
  75155. if (vertex.id === _this.vertices.length) {
  75156. _this.vertices.push(vertex);
  75157. }
  75158. vertexReferences.push(vertex.id);
  75159. };
  75160. //var totalVertices = mesh.getTotalVertices();
  75161. var totalVertices = submesh.verticesCount;
  75162. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  75163. var indicesInit = function (i) {
  75164. if (!indices) {
  75165. return;
  75166. }
  75167. var offset = (submesh.indexStart / 3) + i;
  75168. var pos = (offset * 3);
  75169. var i0 = indices[pos + 0];
  75170. var i1 = indices[pos + 1];
  75171. var i2 = indices[pos + 2];
  75172. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  75173. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  75174. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  75175. var triangle = new DecimationTriangle([v0, v1, v2]);
  75176. triangle.originalOffset = pos;
  75177. _this.triangles.push(triangle);
  75178. };
  75179. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  75180. _this.init(callback);
  75181. });
  75182. });
  75183. };
  75184. QuadraticErrorSimplification.prototype.init = function (callback) {
  75185. var _this = this;
  75186. var triangleInit1 = function (i) {
  75187. var t = _this.triangles[i];
  75188. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  75189. for (var j = 0; j < 3; j++) {
  75190. 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))));
  75191. }
  75192. };
  75193. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  75194. var triangleInit2 = function (i) {
  75195. var t = _this.triangles[i];
  75196. for (var j = 0; j < 3; ++j) {
  75197. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  75198. }
  75199. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75200. };
  75201. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  75202. callback();
  75203. });
  75204. });
  75205. };
  75206. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  75207. var newTriangles = [];
  75208. var i;
  75209. for (i = 0; i < this.vertices.length; ++i) {
  75210. this.vertices[i].triangleCount = 0;
  75211. }
  75212. var t;
  75213. var j;
  75214. for (i = 0; i < this.triangles.length; ++i) {
  75215. if (!this.triangles[i].deleted) {
  75216. t = this.triangles[i];
  75217. for (j = 0; j < 3; ++j) {
  75218. t.vertices[j].triangleCount = 1;
  75219. }
  75220. newTriangles.push(t);
  75221. }
  75222. }
  75223. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  75224. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  75225. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  75226. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  75227. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  75228. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  75229. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  75230. var vertexCount = 0;
  75231. for (i = 0; i < this.vertices.length; ++i) {
  75232. var vertex = this.vertices[i];
  75233. vertex.id = vertexCount;
  75234. if (vertex.triangleCount) {
  75235. vertex.originalOffsets.forEach(function (originalOffset) {
  75236. if (!normalData) {
  75237. return;
  75238. }
  75239. newPositionData.push(vertex.position.x);
  75240. newPositionData.push(vertex.position.y);
  75241. newPositionData.push(vertex.position.z);
  75242. newNormalData.push(normalData[originalOffset * 3]);
  75243. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  75244. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  75245. if (uvs && uvs.length) {
  75246. newUVsData.push(uvs[(originalOffset * 2)]);
  75247. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  75248. }
  75249. else if (colorsData && colorsData.length) {
  75250. newColorsData.push(colorsData[(originalOffset * 4)]);
  75251. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  75252. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  75253. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  75254. }
  75255. ++vertexCount;
  75256. });
  75257. }
  75258. }
  75259. var startingIndex = this._reconstructedMesh.getTotalIndices();
  75260. var startingVertex = this._reconstructedMesh.getTotalVertices();
  75261. var submeshesArray = this._reconstructedMesh.subMeshes;
  75262. this._reconstructedMesh.subMeshes = [];
  75263. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  75264. var originalIndices = this._mesh.getIndices();
  75265. for (i = 0; i < newTriangles.length; ++i) {
  75266. t = newTriangles[i]; //now get the new referencing point for each vertex
  75267. [0, 1, 2].forEach(function (idx) {
  75268. var id = originalIndices[t.originalOffset + idx];
  75269. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  75270. if (offset < 0)
  75271. offset = 0;
  75272. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  75273. });
  75274. }
  75275. //overwriting the old vertex buffers and indices.
  75276. this._reconstructedMesh.setIndices(newIndicesArray);
  75277. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  75278. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  75279. if (newUVsData.length > 0)
  75280. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  75281. if (newColorsData.length > 0)
  75282. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  75283. //create submesh
  75284. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  75285. if (submeshIndex > 0) {
  75286. this._reconstructedMesh.subMeshes = [];
  75287. submeshesArray.forEach(function (submesh) {
  75288. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  75289. });
  75290. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  75291. }
  75292. };
  75293. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  75294. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  75295. this._reconstructedMesh.material = this._mesh.material;
  75296. this._reconstructedMesh.parent = this._mesh.parent;
  75297. this._reconstructedMesh.isVisible = false;
  75298. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  75299. };
  75300. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  75301. for (var i = 0; i < vertex1.triangleCount; ++i) {
  75302. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  75303. if (t.deleted)
  75304. continue;
  75305. var s = this.references[vertex1.triangleStart + i].vertexId;
  75306. var v1 = t.vertices[(s + 1) % 3];
  75307. var v2 = t.vertices[(s + 2) % 3];
  75308. if ((v1 === vertex2 || v2 === vertex2)) {
  75309. deletedArray[i] = true;
  75310. delTr.push(t);
  75311. continue;
  75312. }
  75313. var d1 = v1.position.subtract(point);
  75314. d1 = d1.normalize();
  75315. var d2 = v2.position.subtract(point);
  75316. d2 = d2.normalize();
  75317. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  75318. return true;
  75319. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  75320. deletedArray[i] = false;
  75321. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  75322. return true;
  75323. }
  75324. return false;
  75325. };
  75326. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  75327. var newDeleted = deletedTriangles;
  75328. for (var i = 0; i < vertex.triangleCount; ++i) {
  75329. var ref = this.references[vertex.triangleStart + i];
  75330. var t = this.triangles[ref.triangleId];
  75331. if (t.deleted)
  75332. continue;
  75333. if (deletedArray[i] && t.deletePending) {
  75334. t.deleted = true;
  75335. newDeleted++;
  75336. continue;
  75337. }
  75338. t.vertices[ref.vertexId] = origVertex;
  75339. t.isDirty = true;
  75340. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  75341. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  75342. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  75343. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  75344. this.references.push(ref);
  75345. }
  75346. return newDeleted;
  75347. };
  75348. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  75349. for (var i = 0; i < this.vertices.length; ++i) {
  75350. var vCount = [];
  75351. var vId = [];
  75352. var v = this.vertices[i];
  75353. var j;
  75354. for (j = 0; j < v.triangleCount; ++j) {
  75355. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  75356. for (var ii = 0; ii < 3; ii++) {
  75357. var ofs = 0;
  75358. var vv = triangle.vertices[ii];
  75359. while (ofs < vCount.length) {
  75360. if (vId[ofs] === vv.id)
  75361. break;
  75362. ++ofs;
  75363. }
  75364. if (ofs === vCount.length) {
  75365. vCount.push(1);
  75366. vId.push(vv.id);
  75367. }
  75368. else {
  75369. vCount[ofs]++;
  75370. }
  75371. }
  75372. }
  75373. for (j = 0; j < vCount.length; ++j) {
  75374. if (vCount[j] === 1) {
  75375. this.vertices[vId[j]].isBorder = true;
  75376. }
  75377. else {
  75378. this.vertices[vId[j]].isBorder = false;
  75379. }
  75380. }
  75381. }
  75382. };
  75383. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  75384. if (identifyBorders === void 0) { identifyBorders = false; }
  75385. var i;
  75386. if (!identifyBorders) {
  75387. var newTrianglesVector = [];
  75388. for (i = 0; i < this.triangles.length; ++i) {
  75389. if (!this.triangles[i].deleted) {
  75390. newTrianglesVector.push(this.triangles[i]);
  75391. }
  75392. }
  75393. this.triangles = newTrianglesVector;
  75394. }
  75395. for (i = 0; i < this.vertices.length; ++i) {
  75396. this.vertices[i].triangleCount = 0;
  75397. this.vertices[i].triangleStart = 0;
  75398. }
  75399. var t;
  75400. var j;
  75401. var v;
  75402. for (i = 0; i < this.triangles.length; ++i) {
  75403. t = this.triangles[i];
  75404. for (j = 0; j < 3; ++j) {
  75405. v = t.vertices[j];
  75406. v.triangleCount++;
  75407. }
  75408. }
  75409. var tStart = 0;
  75410. for (i = 0; i < this.vertices.length; ++i) {
  75411. this.vertices[i].triangleStart = tStart;
  75412. tStart += this.vertices[i].triangleCount;
  75413. this.vertices[i].triangleCount = 0;
  75414. }
  75415. var newReferences = new Array(this.triangles.length * 3);
  75416. for (i = 0; i < this.triangles.length; ++i) {
  75417. t = this.triangles[i];
  75418. for (j = 0; j < 3; ++j) {
  75419. v = t.vertices[j];
  75420. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  75421. v.triangleCount++;
  75422. }
  75423. }
  75424. this.references = newReferences;
  75425. if (identifyBorders) {
  75426. this.identifyBorder();
  75427. }
  75428. };
  75429. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  75430. var x = point.x;
  75431. var y = point.y;
  75432. var z = point.z;
  75433. 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
  75434. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  75435. };
  75436. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  75437. var q = vertex1.q.add(vertex2.q);
  75438. var border = vertex1.isBorder && vertex2.isBorder;
  75439. var error = 0;
  75440. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  75441. if (qDet !== 0 && !border) {
  75442. if (!pointResult) {
  75443. pointResult = BABYLON.Vector3.Zero();
  75444. }
  75445. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  75446. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  75447. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  75448. error = this.vertexError(q, pointResult);
  75449. }
  75450. else {
  75451. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75452. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75453. var error1 = this.vertexError(q, vertex1.position);
  75454. var error2 = this.vertexError(q, vertex2.position);
  75455. var error3 = this.vertexError(q, p3);
  75456. error = Math.min(error1, error2, error3);
  75457. if (error === error1) {
  75458. if (pointResult) {
  75459. pointResult.copyFrom(vertex1.position);
  75460. }
  75461. }
  75462. else if (error === error2) {
  75463. if (pointResult) {
  75464. pointResult.copyFrom(vertex2.position);
  75465. }
  75466. }
  75467. else {
  75468. if (pointResult) {
  75469. pointResult.copyFrom(p3);
  75470. }
  75471. }
  75472. }
  75473. return error;
  75474. };
  75475. return QuadraticErrorSimplification;
  75476. }());
  75477. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75478. })(BABYLON || (BABYLON = {}));
  75479. //# sourceMappingURL=babylon.meshSimplification.js.map
  75480. var BABYLON;
  75481. (function (BABYLON) {
  75482. var MeshLODLevel = /** @class */ (function () {
  75483. function MeshLODLevel(distance, mesh) {
  75484. this.distance = distance;
  75485. this.mesh = mesh;
  75486. }
  75487. return MeshLODLevel;
  75488. }());
  75489. BABYLON.MeshLODLevel = MeshLODLevel;
  75490. })(BABYLON || (BABYLON = {}));
  75491. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75492. var BABYLON;
  75493. (function (BABYLON) {
  75494. /**
  75495. * Defines the root class used to create scene optimization to use with SceneOptimizer
  75496. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75497. */
  75498. var SceneOptimization = /** @class */ (function () {
  75499. /**
  75500. * Creates the SceneOptimization object
  75501. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75502. * @param desc defines the description associated with the optimization
  75503. */
  75504. function SceneOptimization(priority) {
  75505. if (priority === void 0) { priority = 0; }
  75506. this.priority = priority;
  75507. }
  75508. /**
  75509. * Gets a string describing the action executed by the current optimization
  75510. */
  75511. SceneOptimization.prototype.getDescription = function () {
  75512. return "";
  75513. };
  75514. /**
  75515. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75516. * @param scene defines the current scene where to apply this optimization
  75517. * @returnstrue if everything that can be done was applied
  75518. */
  75519. SceneOptimization.prototype.apply = function (scene) {
  75520. return true;
  75521. };
  75522. ;
  75523. return SceneOptimization;
  75524. }());
  75525. BABYLON.SceneOptimization = SceneOptimization;
  75526. /**
  75527. * Defines an optimization used to reduce the size of render target textures
  75528. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75529. */
  75530. var TextureOptimization = /** @class */ (function (_super) {
  75531. __extends(TextureOptimization, _super);
  75532. /**
  75533. * Creates the TextureOptimization object
  75534. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75535. * @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
  75536. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  75537. */
  75538. function TextureOptimization(priority, maximumSize, step) {
  75539. if (priority === void 0) { priority = 0; }
  75540. if (maximumSize === void 0) { maximumSize = 1024; }
  75541. if (step === void 0) { step = 0.5; }
  75542. var _this = _super.call(this, priority) || this;
  75543. _this.priority = priority;
  75544. _this.maximumSize = maximumSize;
  75545. _this.step = step;
  75546. return _this;
  75547. }
  75548. /**
  75549. * Gets a string describing the action executed by the current optimization
  75550. */
  75551. TextureOptimization.prototype.getDescription = function () {
  75552. return "Reducing render target texture size to " + this.maximumSize;
  75553. };
  75554. /**
  75555. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75556. * @param scene defines the current scene where to apply this optimization
  75557. */
  75558. TextureOptimization.prototype.apply = function (scene) {
  75559. var allDone = true;
  75560. for (var index = 0; index < scene.textures.length; index++) {
  75561. var texture = scene.textures[index];
  75562. if (!texture.canRescale || texture.getContext) {
  75563. continue;
  75564. }
  75565. var currentSize = texture.getSize();
  75566. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75567. if (maxDimension > this.maximumSize) {
  75568. texture.scale(this.step);
  75569. allDone = false;
  75570. }
  75571. }
  75572. return allDone;
  75573. };
  75574. return TextureOptimization;
  75575. }(SceneOptimization));
  75576. BABYLON.TextureOptimization = TextureOptimization;
  75577. /**
  75578. * Defines an optimization used to increase or decrease the rendering resolution
  75579. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75580. */
  75581. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75582. __extends(HardwareScalingOptimization, _super);
  75583. /**
  75584. * Creates the HardwareScalingOptimization object
  75585. * @param priority priority defines the priority of this optimization (0 by default which means first in the list)
  75586. * @param maximumScale
  75587. * @param step
  75588. */
  75589. function HardwareScalingOptimization(priority, maximumScale, step) {
  75590. if (priority === void 0) { priority = 0; }
  75591. if (maximumScale === void 0) { maximumScale = 2; }
  75592. if (step === void 0) { step = 0.25; }
  75593. var _this = _super.call(this, priority) || this;
  75594. _this.priority = priority;
  75595. _this.maximumScale = maximumScale;
  75596. _this.step = step;
  75597. _this._currentScale = -1;
  75598. _this._directionOffset = 1;
  75599. return _this;
  75600. }
  75601. /**
  75602. * Gets a string describing the action executed by the current optimization
  75603. */
  75604. HardwareScalingOptimization.prototype.getDescription = function () {
  75605. return "Setting hardware scaling level to " + this._currentScale;
  75606. };
  75607. /**
  75608. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75609. * @param scene defines the current scene where to apply this optimization
  75610. */
  75611. HardwareScalingOptimization.prototype.apply = function (scene) {
  75612. if (this._currentScale === -1) {
  75613. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  75614. if (this._currentScale > this.maximumScale) {
  75615. this._directionOffset = -1;
  75616. }
  75617. }
  75618. this._currentScale += this._directionOffset * this.step;
  75619. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  75620. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  75621. };
  75622. ;
  75623. return HardwareScalingOptimization;
  75624. }(SceneOptimization));
  75625. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75626. /**
  75627. * Defines an optimization used to remove shadows
  75628. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75629. */
  75630. var ShadowsOptimization = /** @class */ (function (_super) {
  75631. __extends(ShadowsOptimization, _super);
  75632. function ShadowsOptimization() {
  75633. return _super !== null && _super.apply(this, arguments) || this;
  75634. }
  75635. /**
  75636. * Gets a string describing the action executed by the current optimization
  75637. */
  75638. ShadowsOptimization.prototype.getDescription = function () {
  75639. return "Turning shadows off";
  75640. };
  75641. /**
  75642. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75643. * @param scene defines the current scene where to apply this optimization
  75644. */
  75645. ShadowsOptimization.prototype.apply = function (scene) {
  75646. scene.shadowsEnabled = false;
  75647. return true;
  75648. };
  75649. ;
  75650. return ShadowsOptimization;
  75651. }(SceneOptimization));
  75652. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75653. /**
  75654. * Defines an optimization used to turn post-processes off
  75655. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75656. */
  75657. var PostProcessesOptimization = /** @class */ (function (_super) {
  75658. __extends(PostProcessesOptimization, _super);
  75659. function PostProcessesOptimization() {
  75660. return _super !== null && _super.apply(this, arguments) || this;
  75661. }
  75662. /**
  75663. * Gets a string describing the action executed by the current optimization
  75664. */
  75665. PostProcessesOptimization.prototype.getDescription = function () {
  75666. return "Turning post-processes off";
  75667. };
  75668. /**
  75669. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75670. * @param scene defines the current scene where to apply this optimization
  75671. */
  75672. PostProcessesOptimization.prototype.apply = function (scene) {
  75673. scene.postProcessesEnabled = false;
  75674. return true;
  75675. };
  75676. ;
  75677. return PostProcessesOptimization;
  75678. }(SceneOptimization));
  75679. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75680. /**
  75681. * Defines an optimization used to turn lens flares off
  75682. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75683. */
  75684. var LensFlaresOptimization = /** @class */ (function (_super) {
  75685. __extends(LensFlaresOptimization, _super);
  75686. function LensFlaresOptimization() {
  75687. return _super !== null && _super.apply(this, arguments) || this;
  75688. }
  75689. /**
  75690. * Gets a string describing the action executed by the current optimization
  75691. */
  75692. LensFlaresOptimization.prototype.getDescription = function () {
  75693. return "Turning lens flares off";
  75694. };
  75695. /**
  75696. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75697. * @param scene defines the current scene where to apply this optimization
  75698. */
  75699. LensFlaresOptimization.prototype.apply = function (scene) {
  75700. scene.lensFlaresEnabled = false;
  75701. return true;
  75702. };
  75703. ;
  75704. return LensFlaresOptimization;
  75705. }(SceneOptimization));
  75706. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75707. /**
  75708. * Defines an optimization based on user defined callback.
  75709. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75710. */
  75711. var CustomOptimization = /** @class */ (function (_super) {
  75712. __extends(CustomOptimization, _super);
  75713. function CustomOptimization() {
  75714. return _super !== null && _super.apply(this, arguments) || this;
  75715. }
  75716. /**
  75717. * Gets a string describing the action executed by the current optimization
  75718. */
  75719. CustomOptimization.prototype.getDescription = function () {
  75720. if (this.onGetDescription) {
  75721. return this.onGetDescription();
  75722. }
  75723. return "Running user defined callback";
  75724. };
  75725. /**
  75726. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75727. * @param scene defines the current scene where to apply this optimization
  75728. */
  75729. CustomOptimization.prototype.apply = function (scene) {
  75730. if (this.onApply) {
  75731. return this.onApply(scene);
  75732. }
  75733. return true;
  75734. };
  75735. ;
  75736. return CustomOptimization;
  75737. }(SceneOptimization));
  75738. BABYLON.CustomOptimization = CustomOptimization;
  75739. /**
  75740. * Defines an optimization used to turn particles off
  75741. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75742. */
  75743. var ParticlesOptimization = /** @class */ (function (_super) {
  75744. __extends(ParticlesOptimization, _super);
  75745. function ParticlesOptimization() {
  75746. return _super !== null && _super.apply(this, arguments) || this;
  75747. }
  75748. /**
  75749. * Gets a string describing the action executed by the current optimization
  75750. */
  75751. ParticlesOptimization.prototype.getDescription = function () {
  75752. return "Turning particles off";
  75753. };
  75754. /**
  75755. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75756. * @param scene defines the current scene where to apply this optimization
  75757. */
  75758. ParticlesOptimization.prototype.apply = function (scene) {
  75759. scene.particlesEnabled = false;
  75760. return true;
  75761. };
  75762. ;
  75763. return ParticlesOptimization;
  75764. }(SceneOptimization));
  75765. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75766. /**
  75767. * Defines an optimization used to turn render targets off
  75768. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75769. */
  75770. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75771. __extends(RenderTargetsOptimization, _super);
  75772. function RenderTargetsOptimization() {
  75773. return _super !== null && _super.apply(this, arguments) || this;
  75774. }
  75775. /**
  75776. * Gets a string describing the action executed by the current optimization
  75777. */
  75778. RenderTargetsOptimization.prototype.getDescription = function () {
  75779. return "Turning render targets off";
  75780. };
  75781. /**
  75782. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75783. * @param scene defines the current scene where to apply this optimization
  75784. */
  75785. RenderTargetsOptimization.prototype.apply = function (scene) {
  75786. scene.renderTargetsEnabled = false;
  75787. return true;
  75788. };
  75789. ;
  75790. return RenderTargetsOptimization;
  75791. }(SceneOptimization));
  75792. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  75793. /**
  75794. * Defines an optimization used to merge meshes with compatible materials
  75795. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75796. */
  75797. var MergeMeshesOptimization = /** @class */ (function (_super) {
  75798. __extends(MergeMeshesOptimization, _super);
  75799. function MergeMeshesOptimization() {
  75800. var _this = _super !== null && _super.apply(this, arguments) || this;
  75801. _this._canBeMerged = function (abstractMesh) {
  75802. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  75803. return false;
  75804. }
  75805. var mesh = abstractMesh;
  75806. if (!mesh.isVisible || !mesh.isEnabled()) {
  75807. return false;
  75808. }
  75809. if (mesh.instances.length > 0) {
  75810. return false;
  75811. }
  75812. if (mesh.skeleton || mesh.hasLODLevels) {
  75813. return false;
  75814. }
  75815. if (mesh.parent) {
  75816. return false;
  75817. }
  75818. return true;
  75819. };
  75820. return _this;
  75821. }
  75822. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  75823. /**
  75824. * Gets or sets a boolean which defines if optimization octree has to be updated
  75825. */
  75826. get: function () {
  75827. return MergeMeshesOptimization._UpdateSelectionTree;
  75828. },
  75829. /**
  75830. * Gets or sets a boolean which defines if optimization octree has to be updated
  75831. */
  75832. set: function (value) {
  75833. MergeMeshesOptimization._UpdateSelectionTree = value;
  75834. },
  75835. enumerable: true,
  75836. configurable: true
  75837. });
  75838. /**
  75839. * Gets a string describing the action executed by the current optimization
  75840. */
  75841. MergeMeshesOptimization.prototype.getDescription = function () {
  75842. return "Merging similar meshes together";
  75843. };
  75844. /**
  75845. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  75846. * @param scene defines the current scene where to apply this optimization
  75847. */
  75848. MergeMeshesOptimization.prototype.apply = function (scene, updateSelectionTree) {
  75849. var globalPool = scene.meshes.slice(0);
  75850. var globalLength = globalPool.length;
  75851. for (var index = 0; index < globalLength; index++) {
  75852. var currentPool = new Array();
  75853. var current = globalPool[index];
  75854. // Checks
  75855. if (!this._canBeMerged(current)) {
  75856. continue;
  75857. }
  75858. currentPool.push(current);
  75859. // Find compatible meshes
  75860. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  75861. var otherMesh = globalPool[subIndex];
  75862. if (!this._canBeMerged(otherMesh)) {
  75863. continue;
  75864. }
  75865. if (otherMesh.material !== current.material) {
  75866. continue;
  75867. }
  75868. if (otherMesh.checkCollisions !== current.checkCollisions) {
  75869. continue;
  75870. }
  75871. currentPool.push(otherMesh);
  75872. globalLength--;
  75873. globalPool.splice(subIndex, 1);
  75874. subIndex--;
  75875. }
  75876. if (currentPool.length < 2) {
  75877. continue;
  75878. }
  75879. // Merge meshes
  75880. BABYLON.Mesh.MergeMeshes(currentPool);
  75881. }
  75882. if (updateSelectionTree != undefined) {
  75883. if (updateSelectionTree) {
  75884. scene.createOrUpdateSelectionOctree();
  75885. }
  75886. }
  75887. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  75888. scene.createOrUpdateSelectionOctree();
  75889. }
  75890. return true;
  75891. };
  75892. ;
  75893. MergeMeshesOptimization._UpdateSelectionTree = false;
  75894. return MergeMeshesOptimization;
  75895. }(SceneOptimization));
  75896. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  75897. /**
  75898. * Defines a list of options used by SceneOptimizer
  75899. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  75900. */
  75901. var SceneOptimizerOptions = /** @class */ (function () {
  75902. /**
  75903. * Creates a new list of options used by SceneOptimizer
  75904. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  75905. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  75906. */
  75907. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  75908. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  75909. if (trackerDuration === void 0) { trackerDuration = 2000; }
  75910. this.targetFrameRate = targetFrameRate;
  75911. this.trackerDuration = trackerDuration;
  75912. /**
  75913. * Gets the list of optimizations to apply
  75914. */
  75915. this.optimizations = new Array();
  75916. }
  75917. /**
  75918. * Add a new optimization
  75919. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  75920. */
  75921. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  75922. this.optimizations.push(optimization);
  75923. return this;
  75924. };
  75925. /**
  75926. * Add a new custom optimization
  75927. * @param onApply defines the callback called to apply the custom optimization.
  75928. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  75929. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  75930. */
  75931. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  75932. if (priority === void 0) { priority = 0; }
  75933. var optimization = new CustomOptimization(priority);
  75934. optimization.onApply = onApply;
  75935. optimization.onGetDescription = onGetDescription;
  75936. this.optimizations.push(optimization);
  75937. return this;
  75938. };
  75939. /**
  75940. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  75941. * @param targetFrameRate defines the target frame rate (60 by default)
  75942. * @returns a SceneOptimizerOptions object
  75943. */
  75944. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  75945. var result = new SceneOptimizerOptions(targetFrameRate);
  75946. var priority = 0;
  75947. result.addOptimization(new MergeMeshesOptimization(priority));
  75948. result.addOptimization(new ShadowsOptimization(priority));
  75949. result.addOptimization(new LensFlaresOptimization(priority));
  75950. // Next priority
  75951. priority++;
  75952. result.addOptimization(new PostProcessesOptimization(priority));
  75953. result.addOptimization(new ParticlesOptimization(priority));
  75954. // Next priority
  75955. priority++;
  75956. result.addOptimization(new TextureOptimization(priority, 1024));
  75957. return result;
  75958. };
  75959. /**
  75960. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  75961. * @param targetFrameRate defines the target frame rate (60 by default)
  75962. * @returns a SceneOptimizerOptions object
  75963. */
  75964. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  75965. var result = new SceneOptimizerOptions(targetFrameRate);
  75966. var priority = 0;
  75967. result.addOptimization(new MergeMeshesOptimization(priority));
  75968. result.addOptimization(new ShadowsOptimization(priority));
  75969. result.addOptimization(new LensFlaresOptimization(priority));
  75970. // Next priority
  75971. priority++;
  75972. result.addOptimization(new PostProcessesOptimization(priority));
  75973. result.addOptimization(new ParticlesOptimization(priority));
  75974. // Next priority
  75975. priority++;
  75976. result.addOptimization(new TextureOptimization(priority, 512));
  75977. // Next priority
  75978. priority++;
  75979. result.addOptimization(new RenderTargetsOptimization(priority));
  75980. // Next priority
  75981. priority++;
  75982. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  75983. return result;
  75984. };
  75985. /**
  75986. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  75987. * @param targetFrameRate defines the target frame rate (60 by default)
  75988. * @returns a SceneOptimizerOptions object
  75989. */
  75990. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  75991. var result = new SceneOptimizerOptions(targetFrameRate);
  75992. var priority = 0;
  75993. result.addOptimization(new MergeMeshesOptimization(priority));
  75994. result.addOptimization(new ShadowsOptimization(priority));
  75995. result.addOptimization(new LensFlaresOptimization(priority));
  75996. // Next priority
  75997. priority++;
  75998. result.addOptimization(new PostProcessesOptimization(priority));
  75999. result.addOptimization(new ParticlesOptimization(priority));
  76000. // Next priority
  76001. priority++;
  76002. result.addOptimization(new TextureOptimization(priority, 256));
  76003. // Next priority
  76004. priority++;
  76005. result.addOptimization(new RenderTargetsOptimization(priority));
  76006. // Next priority
  76007. priority++;
  76008. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  76009. return result;
  76010. };
  76011. return SceneOptimizerOptions;
  76012. }());
  76013. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  76014. /**
  76015. * Class used to run optimizations in order to reach a target frame rate
  76016. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  76017. */
  76018. var SceneOptimizer = /** @class */ (function () {
  76019. /**
  76020. * Creates a new SceneOptimizer
  76021. * @param scene defines the scene to work on
  76022. * @param options defines the options to use with the SceneOptimizer
  76023. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  76024. */
  76025. function SceneOptimizer(scene, options, autoGeneratePriorities) {
  76026. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  76027. var _this = this;
  76028. this._isRunning = false;
  76029. this._currentPriorityLevel = 0;
  76030. this._targetFrameRate = 60;
  76031. this._trackerDuration = 2000;
  76032. this._currentFrameRate = 0;
  76033. /**
  76034. * Defines an observable called when the optimizer reaches the target frame rate
  76035. */
  76036. this.onSuccessObservable = new BABYLON.Observable();
  76037. /**
  76038. * Defines an observable called when the optimizer enables an optimization
  76039. */
  76040. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  76041. /**
  76042. * Defines an observable called when the optimizer is not able to reach the target frame rate
  76043. */
  76044. this.onFailureObservable = new BABYLON.Observable();
  76045. if (!options) {
  76046. this._options = new SceneOptimizerOptions();
  76047. }
  76048. else {
  76049. this._options = options;
  76050. }
  76051. if (this._options.targetFrameRate) {
  76052. this._targetFrameRate = this._options.targetFrameRate;
  76053. }
  76054. if (this._options.trackerDuration) {
  76055. this._trackerDuration = this._options.trackerDuration;
  76056. }
  76057. if (autoGeneratePriorities) {
  76058. var priority = 0;
  76059. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  76060. var optim = _a[_i];
  76061. optim.priority = priority++;
  76062. }
  76063. }
  76064. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76065. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  76066. _this._sceneDisposeObserver = null;
  76067. _this.dispose();
  76068. });
  76069. }
  76070. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  76071. /**
  76072. * Gets the current priority level (0 at start)
  76073. */
  76074. get: function () {
  76075. return this._currentPriorityLevel;
  76076. },
  76077. enumerable: true,
  76078. configurable: true
  76079. });
  76080. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  76081. /**
  76082. * Gets the current frame rate checked by the SceneOptimizer
  76083. */
  76084. get: function () {
  76085. return this._currentFrameRate;
  76086. },
  76087. enumerable: true,
  76088. configurable: true
  76089. });
  76090. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  76091. /**
  76092. * Gets or sets the current target frame rate (60 by default)
  76093. */
  76094. get: function () {
  76095. return this._targetFrameRate;
  76096. },
  76097. /**
  76098. * Gets or sets the current target frame rate (60 by default)
  76099. */
  76100. set: function (value) {
  76101. this._targetFrameRate = value;
  76102. },
  76103. enumerable: true,
  76104. configurable: true
  76105. });
  76106. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  76107. /**
  76108. * Gets or sets the current interval between two checks (every 2000ms by default)
  76109. */
  76110. get: function () {
  76111. return this._trackerDuration;
  76112. },
  76113. /**
  76114. * Gets or sets the current interval between two checks (every 2000ms by default)
  76115. */
  76116. set: function (value) {
  76117. this._trackerDuration = value;
  76118. },
  76119. enumerable: true,
  76120. configurable: true
  76121. });
  76122. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  76123. /**
  76124. * Gets the list of active optimizations
  76125. */
  76126. get: function () {
  76127. return this._options.optimizations;
  76128. },
  76129. enumerable: true,
  76130. configurable: true
  76131. });
  76132. /**
  76133. * Stops the current optimizer
  76134. */
  76135. SceneOptimizer.prototype.stop = function () {
  76136. this._isRunning = false;
  76137. };
  76138. SceneOptimizer.prototype.reset = function () {
  76139. this._currentPriorityLevel = 0;
  76140. };
  76141. SceneOptimizer.prototype.start = function () {
  76142. var _this = this;
  76143. if (this._isRunning) {
  76144. return;
  76145. }
  76146. this._isRunning = true;
  76147. // Let's wait for the scene to be ready before running our check
  76148. this._scene.executeWhenReady(function () {
  76149. setTimeout(function () {
  76150. _this._checkCurrentState();
  76151. }, _this._trackerDuration);
  76152. });
  76153. };
  76154. SceneOptimizer.prototype._checkCurrentState = function () {
  76155. var _this = this;
  76156. if (!this._isRunning) {
  76157. return;
  76158. }
  76159. var scene = this._scene;
  76160. var options = this._options;
  76161. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  76162. if (this._currentFrameRate >= this._targetFrameRate) {
  76163. this._isRunning = false;
  76164. this.onSuccessObservable.notifyObservers(this);
  76165. return;
  76166. }
  76167. // Apply current level of optimizations
  76168. var allDone = true;
  76169. var noOptimizationApplied = true;
  76170. for (var index = 0; index < options.optimizations.length; index++) {
  76171. var optimization = options.optimizations[index];
  76172. if (optimization.priority === this._currentPriorityLevel) {
  76173. noOptimizationApplied = false;
  76174. allDone = allDone && optimization.apply(scene);
  76175. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  76176. }
  76177. }
  76178. // If no optimization was applied, this is a failure :(
  76179. if (noOptimizationApplied) {
  76180. this._isRunning = false;
  76181. this.onFailureObservable.notifyObservers(this);
  76182. return;
  76183. }
  76184. // If all optimizations were done, move to next level
  76185. if (allDone) {
  76186. this._currentPriorityLevel++;
  76187. }
  76188. // Let's the system running for a specific amount of time before checking FPS
  76189. scene.executeWhenReady(function () {
  76190. setTimeout(function () {
  76191. _this._checkCurrentState();
  76192. }, _this._trackerDuration);
  76193. });
  76194. };
  76195. /**
  76196. * Release all resources
  76197. */
  76198. SceneOptimizer.prototype.dispose = function () {
  76199. this.stop();
  76200. this.onSuccessObservable.clear();
  76201. this.onFailureObservable.clear();
  76202. this.onNewOptimizationAppliedObservable.clear();
  76203. if (this._sceneDisposeObserver) {
  76204. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  76205. }
  76206. };
  76207. /**
  76208. * Helper function to create a SceneOptimizer with one single line of code
  76209. * @param scene defines the scene to work on
  76210. * @param options defines the options to use with the SceneOptimizer
  76211. * @param onSuccess defines a callback to call on success
  76212. * @param onFailure defines a callback to call on failure
  76213. */
  76214. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  76215. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  76216. if (onSuccess) {
  76217. optimizer.onSuccessObservable.add(function () {
  76218. onSuccess();
  76219. });
  76220. }
  76221. if (onFailure) {
  76222. optimizer.onFailureObservable.add(function () {
  76223. onFailure();
  76224. });
  76225. }
  76226. optimizer.start();
  76227. return optimizer;
  76228. };
  76229. return SceneOptimizer;
  76230. }());
  76231. BABYLON.SceneOptimizer = SceneOptimizer;
  76232. })(BABYLON || (BABYLON = {}));
  76233. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  76234. var BABYLON;
  76235. (function (BABYLON) {
  76236. var OutlineRenderer = /** @class */ (function () {
  76237. function OutlineRenderer(scene) {
  76238. this.zOffset = 1;
  76239. this._scene = scene;
  76240. }
  76241. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  76242. var _this = this;
  76243. if (useOverlay === void 0) { useOverlay = false; }
  76244. var scene = this._scene;
  76245. var engine = this._scene.getEngine();
  76246. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76247. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  76248. return;
  76249. }
  76250. var mesh = subMesh.getRenderingMesh();
  76251. var material = subMesh.getMaterial();
  76252. if (!material || !scene.activeCamera) {
  76253. return;
  76254. }
  76255. engine.enableEffect(this._effect);
  76256. // Logarithmic depth
  76257. if (material.useLogarithmicDepth) {
  76258. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  76259. }
  76260. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  76261. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  76262. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76263. // Bones
  76264. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76265. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76266. }
  76267. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  76268. // Alpha test
  76269. if (material && material.needAlphaTesting()) {
  76270. var alphaTexture = material.getAlphaTestTexture();
  76271. if (alphaTexture) {
  76272. this._effect.setTexture("diffuseSampler", alphaTexture);
  76273. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76274. }
  76275. }
  76276. engine.setZOffset(-this.zOffset);
  76277. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  76278. engine.setZOffset(0);
  76279. };
  76280. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  76281. var defines = [];
  76282. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76283. var mesh = subMesh.getMesh();
  76284. var material = subMesh.getMaterial();
  76285. if (material) {
  76286. // Alpha test
  76287. if (material.needAlphaTesting()) {
  76288. defines.push("#define ALPHATEST");
  76289. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76290. attribs.push(BABYLON.VertexBuffer.UVKind);
  76291. defines.push("#define UV1");
  76292. }
  76293. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76294. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76295. defines.push("#define UV2");
  76296. }
  76297. }
  76298. //Logarithmic depth
  76299. if (material.useLogarithmicDepth) {
  76300. defines.push("#define LOGARITHMICDEPTH");
  76301. }
  76302. }
  76303. // Bones
  76304. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76305. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76306. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76307. if (mesh.numBoneInfluencers > 4) {
  76308. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76309. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76310. }
  76311. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76312. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76313. }
  76314. else {
  76315. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76316. }
  76317. // Instances
  76318. if (useInstances) {
  76319. defines.push("#define INSTANCES");
  76320. attribs.push("world0");
  76321. attribs.push("world1");
  76322. attribs.push("world2");
  76323. attribs.push("world3");
  76324. }
  76325. // Get correct effect
  76326. var join = defines.join("\n");
  76327. if (this._cachedDefines !== join) {
  76328. this._cachedDefines = join;
  76329. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  76330. }
  76331. return this._effect.isReady();
  76332. };
  76333. return OutlineRenderer;
  76334. }());
  76335. BABYLON.OutlineRenderer = OutlineRenderer;
  76336. })(BABYLON || (BABYLON = {}));
  76337. //# sourceMappingURL=babylon.outlineRenderer.js.map
  76338. var BABYLON;
  76339. (function (BABYLON) {
  76340. var FaceAdjacencies = /** @class */ (function () {
  76341. function FaceAdjacencies() {
  76342. this.edges = new Array();
  76343. this.edgesConnectedCount = 0;
  76344. }
  76345. return FaceAdjacencies;
  76346. }());
  76347. var EdgesRenderer = /** @class */ (function () {
  76348. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  76349. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  76350. if (epsilon === void 0) { epsilon = 0.95; }
  76351. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  76352. this.edgesWidthScalerForOrthographic = 1000.0;
  76353. this.edgesWidthScalerForPerspective = 50.0;
  76354. this._linesPositions = new Array();
  76355. this._linesNormals = new Array();
  76356. this._linesIndices = new Array();
  76357. this._buffers = {};
  76358. this._checkVerticesInsteadOfIndices = false;
  76359. this._source = source;
  76360. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  76361. this._epsilon = epsilon;
  76362. this._prepareRessources();
  76363. this._generateEdgesLines();
  76364. }
  76365. EdgesRenderer.prototype._prepareRessources = function () {
  76366. if (this._lineShader) {
  76367. return;
  76368. }
  76369. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  76370. attributes: ["position", "normal"],
  76371. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  76372. });
  76373. this._lineShader.disableDepthWrite = true;
  76374. this._lineShader.backFaceCulling = false;
  76375. };
  76376. EdgesRenderer.prototype._rebuild = function () {
  76377. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76378. if (buffer) {
  76379. buffer._rebuild();
  76380. }
  76381. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76382. if (buffer) {
  76383. buffer._rebuild();
  76384. }
  76385. var scene = this._source.getScene();
  76386. var engine = scene.getEngine();
  76387. this._ib = engine.createIndexBuffer(this._linesIndices);
  76388. };
  76389. EdgesRenderer.prototype.dispose = function () {
  76390. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  76391. if (buffer) {
  76392. buffer.dispose();
  76393. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  76394. }
  76395. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  76396. if (buffer) {
  76397. buffer.dispose();
  76398. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  76399. }
  76400. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  76401. this._lineShader.dispose();
  76402. };
  76403. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  76404. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  76405. return 0;
  76406. }
  76407. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  76408. return 1;
  76409. }
  76410. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  76411. return 2;
  76412. }
  76413. return -1;
  76414. };
  76415. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  76416. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  76417. return 0;
  76418. }
  76419. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  76420. return 1;
  76421. }
  76422. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  76423. return 2;
  76424. }
  76425. return -1;
  76426. };
  76427. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  76428. var needToCreateLine;
  76429. if (edge === undefined) {
  76430. needToCreateLine = true;
  76431. }
  76432. else {
  76433. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  76434. needToCreateLine = dotProduct < this._epsilon;
  76435. }
  76436. if (needToCreateLine) {
  76437. var offset = this._linesPositions.length / 3;
  76438. var normal = p0.subtract(p1);
  76439. normal.normalize();
  76440. // Positions
  76441. this._linesPositions.push(p0.x);
  76442. this._linesPositions.push(p0.y);
  76443. this._linesPositions.push(p0.z);
  76444. this._linesPositions.push(p0.x);
  76445. this._linesPositions.push(p0.y);
  76446. this._linesPositions.push(p0.z);
  76447. this._linesPositions.push(p1.x);
  76448. this._linesPositions.push(p1.y);
  76449. this._linesPositions.push(p1.z);
  76450. this._linesPositions.push(p1.x);
  76451. this._linesPositions.push(p1.y);
  76452. this._linesPositions.push(p1.z);
  76453. // Normals
  76454. this._linesNormals.push(p1.x);
  76455. this._linesNormals.push(p1.y);
  76456. this._linesNormals.push(p1.z);
  76457. this._linesNormals.push(-1);
  76458. this._linesNormals.push(p1.x);
  76459. this._linesNormals.push(p1.y);
  76460. this._linesNormals.push(p1.z);
  76461. this._linesNormals.push(1);
  76462. this._linesNormals.push(p0.x);
  76463. this._linesNormals.push(p0.y);
  76464. this._linesNormals.push(p0.z);
  76465. this._linesNormals.push(-1);
  76466. this._linesNormals.push(p0.x);
  76467. this._linesNormals.push(p0.y);
  76468. this._linesNormals.push(p0.z);
  76469. this._linesNormals.push(1);
  76470. // Indices
  76471. this._linesIndices.push(offset);
  76472. this._linesIndices.push(offset + 1);
  76473. this._linesIndices.push(offset + 2);
  76474. this._linesIndices.push(offset);
  76475. this._linesIndices.push(offset + 2);
  76476. this._linesIndices.push(offset + 3);
  76477. }
  76478. };
  76479. EdgesRenderer.prototype._generateEdgesLines = function () {
  76480. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  76481. var indices = this._source.getIndices();
  76482. if (!indices || !positions) {
  76483. return;
  76484. }
  76485. // First let's find adjacencies
  76486. var adjacencies = new Array();
  76487. var faceNormals = new Array();
  76488. var index;
  76489. var faceAdjacencies;
  76490. // Prepare faces
  76491. for (index = 0; index < indices.length; index += 3) {
  76492. faceAdjacencies = new FaceAdjacencies();
  76493. var p0Index = indices[index];
  76494. var p1Index = indices[index + 1];
  76495. var p2Index = indices[index + 2];
  76496. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  76497. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  76498. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  76499. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  76500. faceNormal.normalize();
  76501. faceNormals.push(faceNormal);
  76502. adjacencies.push(faceAdjacencies);
  76503. }
  76504. // Scan
  76505. for (index = 0; index < adjacencies.length; index++) {
  76506. faceAdjacencies = adjacencies[index];
  76507. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  76508. var otherFaceAdjacencies = adjacencies[otherIndex];
  76509. if (faceAdjacencies.edgesConnectedCount === 3) {
  76510. break;
  76511. }
  76512. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  76513. continue;
  76514. }
  76515. var otherP0 = indices[otherIndex * 3];
  76516. var otherP1 = indices[otherIndex * 3 + 1];
  76517. var otherP2 = indices[otherIndex * 3 + 2];
  76518. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  76519. var otherEdgeIndex = 0;
  76520. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  76521. continue;
  76522. }
  76523. switch (edgeIndex) {
  76524. case 0:
  76525. if (this._checkVerticesInsteadOfIndices) {
  76526. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76527. }
  76528. else {
  76529. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  76530. }
  76531. break;
  76532. case 1:
  76533. if (this._checkVerticesInsteadOfIndices) {
  76534. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76535. }
  76536. else {
  76537. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  76538. }
  76539. break;
  76540. case 2:
  76541. if (this._checkVerticesInsteadOfIndices) {
  76542. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  76543. }
  76544. else {
  76545. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  76546. }
  76547. break;
  76548. }
  76549. if (otherEdgeIndex === -1) {
  76550. continue;
  76551. }
  76552. faceAdjacencies.edges[edgeIndex] = otherIndex;
  76553. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  76554. faceAdjacencies.edgesConnectedCount++;
  76555. otherFaceAdjacencies.edgesConnectedCount++;
  76556. if (faceAdjacencies.edgesConnectedCount === 3) {
  76557. break;
  76558. }
  76559. }
  76560. }
  76561. }
  76562. // Create lines
  76563. for (index = 0; index < adjacencies.length; index++) {
  76564. // 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
  76565. var current = adjacencies[index];
  76566. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  76567. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  76568. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  76569. }
  76570. // Merge into a single mesh
  76571. var engine = this._source.getScene().getEngine();
  76572. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  76573. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  76574. this._ib = engine.createIndexBuffer(this._linesIndices);
  76575. this._indicesCount = this._linesIndices.length;
  76576. };
  76577. EdgesRenderer.prototype.render = function () {
  76578. var scene = this._source.getScene();
  76579. if (!this._lineShader.isReady() || !scene.activeCamera) {
  76580. return;
  76581. }
  76582. var engine = scene.getEngine();
  76583. this._lineShader._preBind();
  76584. // VBOs
  76585. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  76586. scene.resetCachedMaterial();
  76587. this._lineShader.setColor4("color", this._source.edgesColor);
  76588. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  76589. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  76590. }
  76591. else {
  76592. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  76593. }
  76594. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  76595. this._lineShader.bind(this._source.getWorldMatrix());
  76596. // Draw order
  76597. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  76598. this._lineShader.unbind();
  76599. engine.setDepthWrite(true);
  76600. };
  76601. return EdgesRenderer;
  76602. }());
  76603. BABYLON.EdgesRenderer = EdgesRenderer;
  76604. })(BABYLON || (BABYLON = {}));
  76605. //# sourceMappingURL=babylon.edgesRenderer.js.map
  76606. var BABYLON;
  76607. (function (BABYLON) {
  76608. /**
  76609. * Special Glow Blur post process only blurring the alpha channel
  76610. * It enforces keeping the most luminous color in the color channel.
  76611. */
  76612. var GlowBlurPostProcess = /** @class */ (function (_super) {
  76613. __extends(GlowBlurPostProcess, _super);
  76614. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  76615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76616. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  76617. _this.direction = direction;
  76618. _this.kernel = kernel;
  76619. _this.onApplyObservable.add(function (effect) {
  76620. effect.setFloat2("screenSize", _this.width, _this.height);
  76621. effect.setVector2("direction", _this.direction);
  76622. effect.setFloat("blurWidth", _this.kernel);
  76623. });
  76624. return _this;
  76625. }
  76626. return GlowBlurPostProcess;
  76627. }(BABYLON.PostProcess));
  76628. /**
  76629. * The highlight layer Helps adding a glow effect around a mesh.
  76630. *
  76631. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  76632. * glowy meshes to your scene.
  76633. *
  76634. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  76635. */
  76636. var HighlightLayer = /** @class */ (function () {
  76637. /**
  76638. * Instantiates a new highlight Layer and references it to the scene..
  76639. * @param name The name of the layer
  76640. * @param scene The scene to use the layer in
  76641. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  76642. */
  76643. function HighlightLayer(name, scene, options) {
  76644. this.name = name;
  76645. this._vertexBuffers = {};
  76646. this._mainTextureDesiredSize = { width: 0, height: 0 };
  76647. this._meshes = {};
  76648. this._maxSize = 0;
  76649. this._shouldRender = false;
  76650. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  76651. this._excludedMeshes = {};
  76652. /**
  76653. * Specifies whether or not the inner glow is ACTIVE in the layer.
  76654. */
  76655. this.innerGlow = true;
  76656. /**
  76657. * Specifies whether or not the outer glow is ACTIVE in the layer.
  76658. */
  76659. this.outerGlow = true;
  76660. /**
  76661. * Specifies wether the highlight layer is enabled or not.
  76662. */
  76663. this.isEnabled = true;
  76664. /**
  76665. * An event triggered when the highlight layer has been disposed.
  76666. * @type {BABYLON.Observable}
  76667. */
  76668. this.onDisposeObservable = new BABYLON.Observable();
  76669. /**
  76670. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  76671. * @type {BABYLON.Observable}
  76672. */
  76673. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  76674. /**
  76675. * An event triggered when the highlight layer is being blurred.
  76676. * @type {BABYLON.Observable}
  76677. */
  76678. this.onBeforeBlurObservable = new BABYLON.Observable();
  76679. /**
  76680. * An event triggered when the highlight layer has been blurred.
  76681. * @type {BABYLON.Observable}
  76682. */
  76683. this.onAfterBlurObservable = new BABYLON.Observable();
  76684. /**
  76685. * An event triggered when the glowing blurred texture is being merged in the scene.
  76686. * @type {BABYLON.Observable}
  76687. */
  76688. this.onBeforeComposeObservable = new BABYLON.Observable();
  76689. /**
  76690. * An event triggered when the glowing blurred texture has been merged in the scene.
  76691. * @type {BABYLON.Observable}
  76692. */
  76693. this.onAfterComposeObservable = new BABYLON.Observable();
  76694. /**
  76695. * An event triggered when the highlight layer changes its size.
  76696. * @type {BABYLON.Observable}
  76697. */
  76698. this.onSizeChangedObservable = new BABYLON.Observable();
  76699. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76700. var engine = scene.getEngine();
  76701. this._engine = engine;
  76702. this._maxSize = this._engine.getCaps().maxTextureSize;
  76703. this._scene.highlightLayers.push(this);
  76704. // Warn on stencil.
  76705. if (!this._engine.isStencilEnable) {
  76706. 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 }");
  76707. }
  76708. // Adapt options
  76709. this._options = options || {
  76710. mainTextureRatio: 0.5,
  76711. blurTextureSizeRatio: 0.5,
  76712. blurHorizontalSize: 1.0,
  76713. blurVerticalSize: 1.0,
  76714. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  76715. camera: null
  76716. };
  76717. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  76718. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  76719. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  76720. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  76721. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  76722. // VBO
  76723. var vertices = [];
  76724. vertices.push(1, 1);
  76725. vertices.push(-1, 1);
  76726. vertices.push(-1, -1);
  76727. vertices.push(1, -1);
  76728. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76729. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  76730. this._createIndexBuffer();
  76731. // Effect
  76732. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  76733. // Render target
  76734. this.setMainTextureSize();
  76735. // Create Textures and post processes
  76736. this.createTextureAndPostProcesses();
  76737. }
  76738. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  76739. /**
  76740. * Gets the horizontal size of the blur.
  76741. */
  76742. get: function () {
  76743. return this._horizontalBlurPostprocess.kernel;
  76744. },
  76745. /**
  76746. * Specifies the horizontal size of the blur.
  76747. */
  76748. set: function (value) {
  76749. this._horizontalBlurPostprocess.kernel = value;
  76750. },
  76751. enumerable: true,
  76752. configurable: true
  76753. });
  76754. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  76755. /**
  76756. * Gets the vertical size of the blur.
  76757. */
  76758. get: function () {
  76759. return this._verticalBlurPostprocess.kernel;
  76760. },
  76761. /**
  76762. * Specifies the vertical size of the blur.
  76763. */
  76764. set: function (value) {
  76765. this._verticalBlurPostprocess.kernel = value;
  76766. },
  76767. enumerable: true,
  76768. configurable: true
  76769. });
  76770. Object.defineProperty(HighlightLayer.prototype, "camera", {
  76771. /**
  76772. * Gets the camera attached to the layer.
  76773. */
  76774. get: function () {
  76775. return this._options.camera;
  76776. },
  76777. enumerable: true,
  76778. configurable: true
  76779. });
  76780. HighlightLayer.prototype._createIndexBuffer = function () {
  76781. var engine = this._scene.getEngine();
  76782. // Indices
  76783. var indices = [];
  76784. indices.push(0);
  76785. indices.push(1);
  76786. indices.push(2);
  76787. indices.push(0);
  76788. indices.push(2);
  76789. indices.push(3);
  76790. this._indexBuffer = engine.createIndexBuffer(indices);
  76791. };
  76792. HighlightLayer.prototype._rebuild = function () {
  76793. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76794. if (vb) {
  76795. vb._rebuild();
  76796. }
  76797. this._createIndexBuffer();
  76798. };
  76799. /**
  76800. * Creates the render target textures and post processes used in the highlight layer.
  76801. */
  76802. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  76803. var _this = this;
  76804. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  76805. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  76806. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  76807. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  76808. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  76809. width: this._mainTextureDesiredSize.width,
  76810. height: this._mainTextureDesiredSize.height
  76811. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76812. this._mainTexture.activeCamera = this._options.camera;
  76813. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76814. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76815. this._mainTexture.anisotropicFilteringLevel = 1;
  76816. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  76817. this._mainTexture.renderParticles = false;
  76818. this._mainTexture.renderList = null;
  76819. this._mainTexture.ignoreCameraViewport = true;
  76820. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  76821. width: blurTextureWidth,
  76822. height: blurTextureHeight
  76823. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76824. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76825. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76826. this._blurTexture.anisotropicFilteringLevel = 16;
  76827. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76828. this._blurTexture.renderParticles = false;
  76829. this._blurTexture.ignoreCameraViewport = true;
  76830. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76831. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  76832. effect.setTexture("textureSampler", _this._mainTexture);
  76833. });
  76834. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  76835. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76836. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76837. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76838. });
  76839. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76840. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76841. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76842. });
  76843. }
  76844. else {
  76845. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76846. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  76847. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76848. });
  76849. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  76850. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  76851. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  76852. });
  76853. }
  76854. this._mainTexture.onAfterUnbindObservable.add(function () {
  76855. _this.onBeforeBlurObservable.notifyObservers(_this);
  76856. var internalTexture = _this._blurTexture.getInternalTexture();
  76857. if (internalTexture) {
  76858. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  76859. }
  76860. _this.onAfterBlurObservable.notifyObservers(_this);
  76861. });
  76862. // Custom render function
  76863. var renderSubMesh = function (subMesh) {
  76864. if (!_this._meshes) {
  76865. return;
  76866. }
  76867. var material = subMesh.getMaterial();
  76868. var mesh = subMesh.getRenderingMesh();
  76869. var scene = _this._scene;
  76870. var engine = scene.getEngine();
  76871. if (!material) {
  76872. return;
  76873. }
  76874. // Do not block in blend mode.
  76875. if (material.needAlphaBlendingForMesh(mesh)) {
  76876. return;
  76877. }
  76878. // Culling
  76879. engine.setState(material.backFaceCulling);
  76880. // Managing instances
  76881. var batch = mesh._getInstancesRenderList(subMesh._id);
  76882. if (batch.mustReturn) {
  76883. return;
  76884. }
  76885. // Excluded Mesh
  76886. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  76887. return;
  76888. }
  76889. ;
  76890. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76891. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  76892. var emissiveTexture = null;
  76893. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76894. emissiveTexture = material.emissiveTexture;
  76895. }
  76896. if (_this._isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  76897. engine.enableEffect(_this._glowMapGenerationEffect);
  76898. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  76899. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  76900. if (highlightLayerMesh) {
  76901. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  76902. }
  76903. else {
  76904. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  76905. }
  76906. // Alpha test
  76907. if (material && material.needAlphaTesting()) {
  76908. var alphaTexture = material.getAlphaTestTexture();
  76909. if (alphaTexture) {
  76910. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  76911. var textureMatrix = alphaTexture.getTextureMatrix();
  76912. if (textureMatrix) {
  76913. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  76914. }
  76915. }
  76916. }
  76917. // Glow emissive only
  76918. if (emissiveTexture) {
  76919. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  76920. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  76921. }
  76922. // Bones
  76923. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76924. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76925. }
  76926. // Draw
  76927. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  76928. }
  76929. else {
  76930. // Need to reset refresh rate of the shadowMap
  76931. _this._mainTexture.resetRefreshCounter();
  76932. }
  76933. };
  76934. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76935. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  76936. var index;
  76937. var engine = _this._scene.getEngine();
  76938. if (depthOnlySubMeshes.length) {
  76939. engine.setColorWrite(false);
  76940. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76941. renderSubMesh(depthOnlySubMeshes.data[index]);
  76942. }
  76943. engine.setColorWrite(true);
  76944. }
  76945. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76946. renderSubMesh(opaqueSubMeshes.data[index]);
  76947. }
  76948. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76949. renderSubMesh(alphaTestSubMeshes.data[index]);
  76950. }
  76951. for (index = 0; index < transparentSubMeshes.length; index++) {
  76952. renderSubMesh(transparentSubMeshes.data[index]);
  76953. }
  76954. };
  76955. this._mainTexture.onClearObservable.add(function (engine) {
  76956. engine.clear(HighlightLayer.neutralColor, true, true, true);
  76957. });
  76958. };
  76959. /**
  76960. * Checks for the readiness of the element composing the layer.
  76961. * @param subMesh the mesh to check for
  76962. * @param useInstances specify wether or not to use instances to render the mesh
  76963. * @param emissiveTexture the associated emissive texture used to generate the glow
  76964. * @return true if ready otherwise, false
  76965. */
  76966. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  76967. var material = subMesh.getMaterial();
  76968. var mesh = subMesh.getRenderingMesh();
  76969. if (!material || !mesh || !this._meshes) {
  76970. return false;
  76971. }
  76972. var emissiveTexture = null;
  76973. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  76974. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76975. emissiveTexture = material.emissiveTexture;
  76976. }
  76977. return this._isReady(subMesh, useInstances, emissiveTexture);
  76978. };
  76979. /**
  76980. * Checks for the readiness of the element composing the layer.
  76981. * @param subMesh the mesh to check for
  76982. * @param useInstances specify wether or not to use instances to render the mesh
  76983. * @param emissiveTexture the associated emissive texture used to generate the glow
  76984. * @return true if ready otherwise, false
  76985. */
  76986. HighlightLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  76987. var material = subMesh.getMaterial();
  76988. if (!material) {
  76989. return false;
  76990. }
  76991. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  76992. return false;
  76993. }
  76994. var defines = [];
  76995. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76996. var mesh = subMesh.getMesh();
  76997. var uv1 = false;
  76998. var uv2 = false;
  76999. // Alpha test
  77000. if (material && material.needAlphaTesting()) {
  77001. var alphaTexture = material.getAlphaTestTexture();
  77002. if (alphaTexture) {
  77003. defines.push("#define ALPHATEST");
  77004. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77005. alphaTexture.coordinatesIndex === 1) {
  77006. defines.push("#define DIFFUSEUV2");
  77007. uv2 = true;
  77008. }
  77009. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77010. defines.push("#define DIFFUSEUV1");
  77011. uv1 = true;
  77012. }
  77013. }
  77014. }
  77015. // Emissive
  77016. if (emissiveTexture) {
  77017. defines.push("#define EMISSIVE");
  77018. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  77019. emissiveTexture.coordinatesIndex === 1) {
  77020. defines.push("#define EMISSIVEUV2");
  77021. uv2 = true;
  77022. }
  77023. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  77024. defines.push("#define EMISSIVEUV1");
  77025. uv1 = true;
  77026. }
  77027. }
  77028. if (uv1) {
  77029. attribs.push(BABYLON.VertexBuffer.UVKind);
  77030. defines.push("#define UV1");
  77031. }
  77032. if (uv2) {
  77033. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  77034. defines.push("#define UV2");
  77035. }
  77036. // Bones
  77037. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  77038. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  77039. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  77040. if (mesh.numBoneInfluencers > 4) {
  77041. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  77042. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  77043. }
  77044. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77045. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  77046. }
  77047. else {
  77048. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77049. }
  77050. // Instances
  77051. if (useInstances) {
  77052. defines.push("#define INSTANCES");
  77053. attribs.push("world0");
  77054. attribs.push("world1");
  77055. attribs.push("world2");
  77056. attribs.push("world3");
  77057. }
  77058. // Get correct effect
  77059. var join = defines.join("\n");
  77060. if (this._cachedDefines !== join) {
  77061. this._cachedDefines = join;
  77062. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  77063. }
  77064. return this._glowMapGenerationEffect.isReady();
  77065. };
  77066. /**
  77067. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  77068. */
  77069. HighlightLayer.prototype.render = function () {
  77070. var currentEffect = this._glowMapMergeEffect;
  77071. // Check
  77072. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  77073. return;
  77074. var engine = this._scene.getEngine();
  77075. this.onBeforeComposeObservable.notifyObservers(this);
  77076. // Render
  77077. engine.enableEffect(currentEffect);
  77078. engine.setState(false);
  77079. // Cache
  77080. var previousStencilBuffer = engine.getStencilBuffer();
  77081. var previousStencilFunction = engine.getStencilFunction();
  77082. var previousStencilMask = engine.getStencilMask();
  77083. var previousStencilOperationPass = engine.getStencilOperationPass();
  77084. var previousStencilOperationFail = engine.getStencilOperationFail();
  77085. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  77086. var previousAlphaMode = engine.getAlphaMode();
  77087. // Texture
  77088. currentEffect.setTexture("textureSampler", this._blurTexture);
  77089. // VBOs
  77090. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  77091. // Stencil operations
  77092. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  77093. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  77094. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  77095. // Draw order
  77096. engine.setAlphaMode(this._options.alphaBlendingMode);
  77097. engine.setStencilMask(0x00);
  77098. engine.setStencilBuffer(true);
  77099. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  77100. if (this.outerGlow) {
  77101. currentEffect.setFloat("offset", 0);
  77102. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  77103. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77104. }
  77105. if (this.innerGlow) {
  77106. currentEffect.setFloat("offset", 1);
  77107. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  77108. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77109. }
  77110. // Restore Cache
  77111. engine.setStencilFunction(previousStencilFunction);
  77112. engine.setStencilMask(previousStencilMask);
  77113. engine.setAlphaMode(previousAlphaMode);
  77114. engine.setStencilBuffer(previousStencilBuffer);
  77115. engine.setStencilOperationPass(previousStencilOperationPass);
  77116. engine.setStencilOperationFail(previousStencilOperationFail);
  77117. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  77118. engine._stencilState.reset();
  77119. this.onAfterComposeObservable.notifyObservers(this);
  77120. // Handle size changes.
  77121. var size = this._mainTexture.getSize();
  77122. this.setMainTextureSize();
  77123. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  77124. // Recreate RTT and post processes on size change.
  77125. this.onSizeChangedObservable.notifyObservers(this);
  77126. this.disposeTextureAndPostProcesses();
  77127. this.createTextureAndPostProcesses();
  77128. }
  77129. };
  77130. /**
  77131. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  77132. * @param mesh The mesh to exclude from the highlight layer
  77133. */
  77134. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  77135. if (!this._excludedMeshes) {
  77136. return;
  77137. }
  77138. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77139. if (!meshExcluded) {
  77140. this._excludedMeshes[mesh.uniqueId] = {
  77141. mesh: mesh,
  77142. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  77143. mesh.getEngine().setStencilBuffer(false);
  77144. }),
  77145. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  77146. mesh.getEngine().setStencilBuffer(true);
  77147. }),
  77148. };
  77149. }
  77150. };
  77151. /**
  77152. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  77153. * @param mesh The mesh to highlight
  77154. */
  77155. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  77156. if (!this._excludedMeshes) {
  77157. return;
  77158. }
  77159. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  77160. if (meshExcluded) {
  77161. if (meshExcluded.beforeRender) {
  77162. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  77163. }
  77164. if (meshExcluded.afterRender) {
  77165. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  77166. }
  77167. }
  77168. this._excludedMeshes[mesh.uniqueId] = null;
  77169. };
  77170. /**
  77171. * Determine if a given mesh will be highlighted by the current HighlightLayer
  77172. * @param mesh mesh to test
  77173. * @returns true if the mesh will be highlighted by the current HighlightLayer
  77174. */
  77175. HighlightLayer.prototype.hasMesh = function (mesh) {
  77176. if (!this._meshes) {
  77177. return false;
  77178. }
  77179. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  77180. };
  77181. /**
  77182. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  77183. * @param mesh The mesh to highlight
  77184. * @param color The color of the highlight
  77185. * @param glowEmissiveOnly Extract the glow from the emissive texture
  77186. */
  77187. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  77188. var _this = this;
  77189. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  77190. if (!this._meshes) {
  77191. return;
  77192. }
  77193. var meshHighlight = this._meshes[mesh.uniqueId];
  77194. if (meshHighlight) {
  77195. meshHighlight.color = color;
  77196. }
  77197. else {
  77198. this._meshes[mesh.uniqueId] = {
  77199. mesh: mesh,
  77200. color: color,
  77201. // Lambda required for capture due to Observable this context
  77202. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  77203. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  77204. _this.defaultStencilReference(mesh);
  77205. }
  77206. else {
  77207. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  77208. }
  77209. }),
  77210. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  77211. glowEmissiveOnly: glowEmissiveOnly
  77212. };
  77213. }
  77214. this._shouldRender = true;
  77215. };
  77216. /**
  77217. * Remove a mesh from the highlight layer in order to make it stop glowing.
  77218. * @param mesh The mesh to highlight
  77219. */
  77220. HighlightLayer.prototype.removeMesh = function (mesh) {
  77221. if (!this._meshes) {
  77222. return;
  77223. }
  77224. var meshHighlight = this._meshes[mesh.uniqueId];
  77225. if (meshHighlight) {
  77226. if (meshHighlight.observerHighlight) {
  77227. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77228. }
  77229. if (meshHighlight.observerDefault) {
  77230. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77231. }
  77232. delete this._meshes[mesh.uniqueId];
  77233. }
  77234. this._shouldRender = false;
  77235. for (var meshHighlightToCheck in this._meshes) {
  77236. if (this._meshes[meshHighlightToCheck]) {
  77237. this._shouldRender = true;
  77238. break;
  77239. }
  77240. }
  77241. };
  77242. /**
  77243. * Returns true if the layer contains information to display, otherwise false.
  77244. */
  77245. HighlightLayer.prototype.shouldRender = function () {
  77246. return this.isEnabled && this._shouldRender;
  77247. };
  77248. /**
  77249. * Sets the main texture desired size which is the closest power of two
  77250. * of the engine canvas size.
  77251. */
  77252. HighlightLayer.prototype.setMainTextureSize = function () {
  77253. if (this._options.mainTextureFixedSize) {
  77254. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  77255. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  77256. }
  77257. else {
  77258. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  77259. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  77260. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  77261. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  77262. }
  77263. };
  77264. /**
  77265. * Force the stencil to the normal expected value for none glowing parts
  77266. */
  77267. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  77268. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  77269. };
  77270. /**
  77271. * Dispose only the render target textures and post process.
  77272. */
  77273. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  77274. this._blurTexture.dispose();
  77275. this._mainTexture.dispose();
  77276. this._downSamplePostprocess.dispose();
  77277. this._horizontalBlurPostprocess.dispose();
  77278. this._verticalBlurPostprocess.dispose();
  77279. };
  77280. /**
  77281. * Dispose the highlight layer and free resources.
  77282. */
  77283. HighlightLayer.prototype.dispose = function () {
  77284. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77285. if (vertexBuffer) {
  77286. vertexBuffer.dispose();
  77287. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77288. }
  77289. if (this._indexBuffer) {
  77290. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77291. this._indexBuffer = null;
  77292. }
  77293. // Clean textures and post processes
  77294. this.disposeTextureAndPostProcesses();
  77295. if (this._meshes) {
  77296. // Clean mesh references
  77297. for (var id in this._meshes) {
  77298. var meshHighlight = this._meshes[id];
  77299. if (meshHighlight && meshHighlight.mesh) {
  77300. if (meshHighlight.observerHighlight) {
  77301. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  77302. }
  77303. if (meshHighlight.observerDefault) {
  77304. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  77305. }
  77306. }
  77307. }
  77308. this._meshes = null;
  77309. }
  77310. if (this._excludedMeshes) {
  77311. for (var id in this._excludedMeshes) {
  77312. var meshHighlight = this._excludedMeshes[id];
  77313. if (meshHighlight) {
  77314. if (meshHighlight.beforeRender) {
  77315. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  77316. }
  77317. if (meshHighlight.afterRender) {
  77318. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  77319. }
  77320. }
  77321. }
  77322. this._excludedMeshes = null;
  77323. }
  77324. // Remove from scene
  77325. var index = this._scene.highlightLayers.indexOf(this, 0);
  77326. if (index > -1) {
  77327. this._scene.highlightLayers.splice(index, 1);
  77328. }
  77329. // Callback
  77330. this.onDisposeObservable.notifyObservers(this);
  77331. this.onDisposeObservable.clear();
  77332. this.onBeforeRenderMainTextureObservable.clear();
  77333. this.onBeforeBlurObservable.clear();
  77334. this.onBeforeComposeObservable.clear();
  77335. this.onAfterComposeObservable.clear();
  77336. this.onSizeChangedObservable.clear();
  77337. };
  77338. /**
  77339. * The neutral color used during the preparation of the glow effect.
  77340. * This is black by default as the blend operation is a blend operation.
  77341. */
  77342. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  77343. /**
  77344. * Stencil value used for glowing meshes.
  77345. */
  77346. HighlightLayer.glowingMeshStencilReference = 0x02;
  77347. /**
  77348. * Stencil value used for the other meshes in the scene.
  77349. */
  77350. HighlightLayer.normalMeshStencilReference = 0x01;
  77351. return HighlightLayer;
  77352. }());
  77353. BABYLON.HighlightLayer = HighlightLayer;
  77354. })(BABYLON || (BABYLON = {}));
  77355. //# sourceMappingURL=babylon.highlightlayer.js.map
  77356. var BABYLON;
  77357. (function (BABYLON) {
  77358. /**
  77359. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  77360. */
  77361. var AssetTaskState;
  77362. (function (AssetTaskState) {
  77363. /**
  77364. * Initialization
  77365. */
  77366. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  77367. /**
  77368. * Running
  77369. */
  77370. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  77371. /**
  77372. * Done
  77373. */
  77374. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  77375. /**
  77376. * Error
  77377. */
  77378. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  77379. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  77380. /**
  77381. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  77382. */
  77383. var AbstractAssetTask = /** @class */ (function () {
  77384. /**
  77385. * Creates a new {BABYLON.AssetsManager}
  77386. * @param name defines the name of the task
  77387. */
  77388. function AbstractAssetTask(
  77389. /**
  77390. * Task name
  77391. */ name) {
  77392. this.name = name;
  77393. this._isCompleted = false;
  77394. this._taskState = AssetTaskState.INIT;
  77395. }
  77396. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  77397. /**
  77398. * Get if the task is completed
  77399. */
  77400. get: function () {
  77401. return this._isCompleted;
  77402. },
  77403. enumerable: true,
  77404. configurable: true
  77405. });
  77406. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  77407. /**
  77408. * Gets the current state of the task
  77409. */
  77410. get: function () {
  77411. return this._taskState;
  77412. },
  77413. enumerable: true,
  77414. configurable: true
  77415. });
  77416. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  77417. /**
  77418. * Gets the current error object (if task is in error)
  77419. */
  77420. get: function () {
  77421. return this._errorObject;
  77422. },
  77423. enumerable: true,
  77424. configurable: true
  77425. });
  77426. /**
  77427. * Internal only
  77428. * @ignore
  77429. */
  77430. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  77431. if (this._errorObject) {
  77432. return;
  77433. }
  77434. this._errorObject = {
  77435. message: message,
  77436. exception: exception
  77437. };
  77438. };
  77439. /**
  77440. * Execute the current task
  77441. * @param scene defines the scene where you want your assets to be loaded
  77442. * @param onSuccess is a callback called when the task is successfully executed
  77443. * @param onError is a callback called if an error occurs
  77444. */
  77445. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77446. var _this = this;
  77447. this._taskState = AssetTaskState.RUNNING;
  77448. this.runTask(scene, function () {
  77449. _this.onDoneCallback(onSuccess, onError);
  77450. }, function (msg, exception) {
  77451. _this.onErrorCallback(onError, msg, exception);
  77452. });
  77453. };
  77454. /**
  77455. * Execute the current task
  77456. * @param scene defines the scene where you want your assets to be loaded
  77457. * @param onSuccess is a callback called when the task is successfully executed
  77458. * @param onError is a callback called if an error occurs
  77459. */
  77460. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77461. throw new Error("runTask is not implemented");
  77462. };
  77463. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  77464. this._taskState = AssetTaskState.ERROR;
  77465. this._errorObject = {
  77466. message: message,
  77467. exception: exception
  77468. };
  77469. if (this.onError) {
  77470. this.onError(this, message, exception);
  77471. }
  77472. onError();
  77473. };
  77474. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  77475. try {
  77476. this._taskState = AssetTaskState.DONE;
  77477. this._isCompleted = true;
  77478. if (this.onSuccess) {
  77479. this.onSuccess(this);
  77480. }
  77481. onSuccess();
  77482. }
  77483. catch (e) {
  77484. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  77485. }
  77486. };
  77487. return AbstractAssetTask;
  77488. }());
  77489. BABYLON.AbstractAssetTask = AbstractAssetTask;
  77490. /**
  77491. * Class used to share progress information about assets loading
  77492. */
  77493. var AssetsProgressEvent = /** @class */ (function () {
  77494. /**
  77495. * Creates a {BABYLON.AssetsProgressEvent}
  77496. * @param remainingCount defines the number of remaining tasks to process
  77497. * @param totalCount defines the total number of tasks
  77498. * @param task defines the task that was just processed
  77499. */
  77500. function AssetsProgressEvent(remainingCount, totalCount, task) {
  77501. this.remainingCount = remainingCount;
  77502. this.totalCount = totalCount;
  77503. this.task = task;
  77504. }
  77505. return AssetsProgressEvent;
  77506. }());
  77507. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  77508. /**
  77509. * Define a task used by {BABYLON.AssetsManager} to load meshes
  77510. */
  77511. var MeshAssetTask = /** @class */ (function (_super) {
  77512. __extends(MeshAssetTask, _super);
  77513. /**
  77514. * Creates a new {BABYLON.MeshAssetTask}
  77515. * @param name defines the name of the task
  77516. * @param meshesNames defines the list of mesh's names you want to load
  77517. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  77518. * @param sceneFilename defines the filename of the scene to load from
  77519. */
  77520. function MeshAssetTask(
  77521. /**
  77522. * Defines the name of the task
  77523. */
  77524. name,
  77525. /**
  77526. * Defines the list of mesh's names you want to load
  77527. */
  77528. meshesNames,
  77529. /**
  77530. * Defines the root url to use as a base to load your meshes and associated resources
  77531. */
  77532. rootUrl,
  77533. /**
  77534. * Defines the filename of the scene to load from
  77535. */
  77536. sceneFilename) {
  77537. var _this = _super.call(this, name) || this;
  77538. _this.name = name;
  77539. _this.meshesNames = meshesNames;
  77540. _this.rootUrl = rootUrl;
  77541. _this.sceneFilename = sceneFilename;
  77542. return _this;
  77543. }
  77544. /**
  77545. * Execute the current task
  77546. * @param scene defines the scene where you want your assets to be loaded
  77547. * @param onSuccess is a callback called when the task is successfully executed
  77548. * @param onError is a callback called if an error occurs
  77549. */
  77550. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77551. var _this = this;
  77552. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  77553. _this.loadedMeshes = meshes;
  77554. _this.loadedParticleSystems = particleSystems;
  77555. _this.loadedSkeletons = skeletons;
  77556. onSuccess();
  77557. }, null, function (scene, message, exception) {
  77558. onError(message, exception);
  77559. });
  77560. };
  77561. return MeshAssetTask;
  77562. }(AbstractAssetTask));
  77563. BABYLON.MeshAssetTask = MeshAssetTask;
  77564. /**
  77565. * Define a task used by {BABYLON.AssetsManager} to load text content
  77566. */
  77567. var TextFileAssetTask = /** @class */ (function (_super) {
  77568. __extends(TextFileAssetTask, _super);
  77569. /**
  77570. * Creates a new TextFileAssetTask object
  77571. * @param name defines the name of the task
  77572. * @param url defines the location of the file to load
  77573. */
  77574. function TextFileAssetTask(
  77575. /**
  77576. * Defines the name of the task
  77577. */
  77578. name,
  77579. /**
  77580. * Defines the location of the file to load
  77581. */
  77582. url) {
  77583. var _this = _super.call(this, name) || this;
  77584. _this.name = name;
  77585. _this.url = url;
  77586. return _this;
  77587. }
  77588. /**
  77589. * Execute the current task
  77590. * @param scene defines the scene where you want your assets to be loaded
  77591. * @param onSuccess is a callback called when the task is successfully executed
  77592. * @param onError is a callback called if an error occurs
  77593. */
  77594. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77595. var _this = this;
  77596. scene._loadFile(this.url, function (data) {
  77597. _this.text = data;
  77598. onSuccess();
  77599. }, undefined, false, true, function (request, exception) {
  77600. if (request) {
  77601. onError(request.status + " " + request.statusText, exception);
  77602. }
  77603. });
  77604. };
  77605. return TextFileAssetTask;
  77606. }(AbstractAssetTask));
  77607. BABYLON.TextFileAssetTask = TextFileAssetTask;
  77608. /**
  77609. * Define a task used by {BABYLON.AssetsManager} to load binary data
  77610. */
  77611. var BinaryFileAssetTask = /** @class */ (function (_super) {
  77612. __extends(BinaryFileAssetTask, _super);
  77613. /**
  77614. * Creates a new BinaryFileAssetTask object
  77615. * @param name defines the name of the new task
  77616. * @param url defines the location of the file to load
  77617. */
  77618. function BinaryFileAssetTask(
  77619. /**
  77620. * Defines the name of the task
  77621. */
  77622. name,
  77623. /**
  77624. * Defines the location of the file to load
  77625. */
  77626. url) {
  77627. var _this = _super.call(this, name) || this;
  77628. _this.name = name;
  77629. _this.url = url;
  77630. return _this;
  77631. }
  77632. /**
  77633. * Execute the current task
  77634. * @param scene defines the scene where you want your assets to be loaded
  77635. * @param onSuccess is a callback called when the task is successfully executed
  77636. * @param onError is a callback called if an error occurs
  77637. */
  77638. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77639. var _this = this;
  77640. scene._loadFile(this.url, function (data) {
  77641. _this.data = data;
  77642. onSuccess();
  77643. }, undefined, true, true, function (request, exception) {
  77644. if (request) {
  77645. onError(request.status + " " + request.statusText, exception);
  77646. }
  77647. });
  77648. };
  77649. return BinaryFileAssetTask;
  77650. }(AbstractAssetTask));
  77651. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  77652. /**
  77653. * Define a task used by {BABYLON.AssetsManager} to load images
  77654. */
  77655. var ImageAssetTask = /** @class */ (function (_super) {
  77656. __extends(ImageAssetTask, _super);
  77657. /**
  77658. * Creates a new ImageAssetTask
  77659. * @param name defines the name of the task
  77660. * @param url defines the location of the image to load
  77661. */
  77662. function ImageAssetTask(
  77663. /**
  77664. * Defines the name of the task
  77665. */
  77666. name,
  77667. /**
  77668. * Defines the location of the image to load
  77669. */
  77670. url) {
  77671. var _this = _super.call(this, name) || this;
  77672. _this.name = name;
  77673. _this.url = url;
  77674. return _this;
  77675. }
  77676. /**
  77677. * Execute the current task
  77678. * @param scene defines the scene where you want your assets to be loaded
  77679. * @param onSuccess is a callback called when the task is successfully executed
  77680. * @param onError is a callback called if an error occurs
  77681. */
  77682. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77683. var _this = this;
  77684. var img = new Image();
  77685. BABYLON.Tools.SetCorsBehavior(this.url, img);
  77686. img.onload = function () {
  77687. _this.image = img;
  77688. onSuccess();
  77689. };
  77690. img.onerror = function (err) {
  77691. onError("Error loading image", err);
  77692. };
  77693. img.src = this.url;
  77694. };
  77695. return ImageAssetTask;
  77696. }(AbstractAssetTask));
  77697. BABYLON.ImageAssetTask = ImageAssetTask;
  77698. /**
  77699. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  77700. */
  77701. var TextureAssetTask = /** @class */ (function (_super) {
  77702. __extends(TextureAssetTask, _super);
  77703. /**
  77704. * Creates a new TextureAssetTask object
  77705. * @param name defines the name of the task
  77706. * @param url defines the location of the file to load
  77707. * @param noMipmap defines if mipmap should not be generated (default is false)
  77708. * @param invertY defines if texture must be inverted on Y axis (default is false)
  77709. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77710. */
  77711. function TextureAssetTask(
  77712. /**
  77713. * Defines the name of the task
  77714. */
  77715. name,
  77716. /**
  77717. * Defines the location of the file to load
  77718. */
  77719. url,
  77720. /**
  77721. * Defines if mipmap should not be generated (default is false)
  77722. */
  77723. noMipmap,
  77724. /**
  77725. * Defines if texture must be inverted on Y axis (default is false)
  77726. */
  77727. invertY,
  77728. /**
  77729. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  77730. */
  77731. samplingMode) {
  77732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77733. var _this = _super.call(this, name) || this;
  77734. _this.name = name;
  77735. _this.url = url;
  77736. _this.noMipmap = noMipmap;
  77737. _this.invertY = invertY;
  77738. _this.samplingMode = samplingMode;
  77739. return _this;
  77740. }
  77741. /**
  77742. * Execute the current task
  77743. * @param scene defines the scene where you want your assets to be loaded
  77744. * @param onSuccess is a callback called when the task is successfully executed
  77745. * @param onError is a callback called if an error occurs
  77746. */
  77747. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77748. var onload = function () {
  77749. onSuccess();
  77750. };
  77751. var onerror = function (message, exception) {
  77752. onError(message, exception);
  77753. };
  77754. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  77755. };
  77756. return TextureAssetTask;
  77757. }(AbstractAssetTask));
  77758. BABYLON.TextureAssetTask = TextureAssetTask;
  77759. /**
  77760. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  77761. */
  77762. var CubeTextureAssetTask = /** @class */ (function (_super) {
  77763. __extends(CubeTextureAssetTask, _super);
  77764. /**
  77765. * Creates a new CubeTextureAssetTask
  77766. * @param name defines the name of the task
  77767. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77768. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77769. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77770. * @param files defines the explicit list of files (undefined by default)
  77771. */
  77772. function CubeTextureAssetTask(
  77773. /**
  77774. * Defines the name of the task
  77775. */
  77776. name,
  77777. /**
  77778. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  77779. */
  77780. url,
  77781. /**
  77782. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  77783. */
  77784. extensions,
  77785. /**
  77786. * Defines if mipmaps should not be generated (default is false)
  77787. */
  77788. noMipmap,
  77789. /**
  77790. * Defines the explicit list of files (undefined by default)
  77791. */
  77792. files) {
  77793. var _this = _super.call(this, name) || this;
  77794. _this.name = name;
  77795. _this.url = url;
  77796. _this.extensions = extensions;
  77797. _this.noMipmap = noMipmap;
  77798. _this.files = files;
  77799. return _this;
  77800. }
  77801. /**
  77802. * Execute the current task
  77803. * @param scene defines the scene where you want your assets to be loaded
  77804. * @param onSuccess is a callback called when the task is successfully executed
  77805. * @param onError is a callback called if an error occurs
  77806. */
  77807. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  77808. var onload = function () {
  77809. onSuccess();
  77810. };
  77811. var onerror = function (message, exception) {
  77812. onError(message, exception);
  77813. };
  77814. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  77815. };
  77816. return CubeTextureAssetTask;
  77817. }(AbstractAssetTask));
  77818. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  77819. /**
  77820. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  77821. */
  77822. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  77823. __extends(HDRCubeTextureAssetTask, _super);
  77824. /**
  77825. * Creates a new HDRCubeTextureAssetTask object
  77826. * @param name defines the name of the task
  77827. * @param url defines the location of the file to load
  77828. * @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.
  77829. * @param noMipmap defines if mipmaps should not be generated (default is false)
  77830. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  77831. * @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)
  77832. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  77833. */
  77834. function HDRCubeTextureAssetTask(
  77835. /**
  77836. * Defines the name of the task
  77837. */
  77838. name,
  77839. /**
  77840. * Defines the location of the file to load
  77841. */
  77842. url,
  77843. /**
  77844. * 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.
  77845. */
  77846. size,
  77847. /**
  77848. * Defines if mipmaps should not be generated (default is false)
  77849. */
  77850. noMipmap,
  77851. /**
  77852. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  77853. */
  77854. generateHarmonics,
  77855. /**
  77856. * 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)
  77857. */
  77858. useInGammaSpace,
  77859. /**
  77860. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  77861. */
  77862. usePMREMGenerator) {
  77863. if (noMipmap === void 0) { noMipmap = false; }
  77864. if (generateHarmonics === void 0) { generateHarmonics = true; }
  77865. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  77866. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  77867. var _this = _super.call(this, name) || this;
  77868. _this.name = name;
  77869. _this.url = url;
  77870. _this.size = size;
  77871. _this.noMipmap = noMipmap;
  77872. _this.generateHarmonics = generateHarmonics;
  77873. _this.useInGammaSpace = useInGammaSpace;
  77874. _this.usePMREMGenerator = usePMREMGenerator;
  77875. return _this;
  77876. }
  77877. /**
  77878. * Execute the current task
  77879. * @param scene defines the scene where you want your assets to be loaded
  77880. * @param onSuccess is a callback called when the task is successfully executed
  77881. * @param onError is a callback called if an error occurs
  77882. */
  77883. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  77884. var onload = function () {
  77885. onSuccess();
  77886. };
  77887. var onerror = function (message, exception) {
  77888. onError(message, exception);
  77889. };
  77890. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  77891. };
  77892. return HDRCubeTextureAssetTask;
  77893. }(AbstractAssetTask));
  77894. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  77895. /**
  77896. * This class can be used to easily import assets into a scene
  77897. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  77898. */
  77899. var AssetsManager = /** @class */ (function () {
  77900. /**
  77901. * Creates a new AssetsManager
  77902. * @param scene defines the scene to work on
  77903. */
  77904. function AssetsManager(scene) {
  77905. this._isLoading = false;
  77906. this._tasks = new Array();
  77907. this._waitingTasksCount = 0;
  77908. this._totalTasksCount = 0;
  77909. /**
  77910. * Observable called when all tasks are processed
  77911. */
  77912. this.onTaskSuccessObservable = new BABYLON.Observable();
  77913. /**
  77914. * Observable called when a task had an error
  77915. */
  77916. this.onTaskErrorObservable = new BABYLON.Observable();
  77917. /**
  77918. * Observable called when a task is successful
  77919. */
  77920. this.onTasksDoneObservable = new BABYLON.Observable();
  77921. /**
  77922. * Observable called when a task is done (whatever the result is)
  77923. */
  77924. this.onProgressObservable = new BABYLON.Observable();
  77925. /**
  77926. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  77927. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  77928. */
  77929. this.useDefaultLoadingScreen = true;
  77930. this._scene = scene;
  77931. }
  77932. /**
  77933. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  77934. * @param taskName defines the name of the new task
  77935. * @param meshesNames defines the name of meshes to load
  77936. * @param rootUrl defines the root url to use to locate files
  77937. * @param sceneFilename defines the filename of the scene file
  77938. * @returns a new {BABYLON.MeshAssetTask} object
  77939. */
  77940. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  77941. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  77942. this._tasks.push(task);
  77943. return task;
  77944. };
  77945. /**
  77946. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  77947. * @param taskName defines the name of the new task
  77948. * @param url defines the url of the file to load
  77949. * @returns a new {BABYLON.TextFileAssetTask} object
  77950. */
  77951. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  77952. var task = new TextFileAssetTask(taskName, url);
  77953. this._tasks.push(task);
  77954. return task;
  77955. };
  77956. /**
  77957. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  77958. * @param taskName defines the name of the new task
  77959. * @param url defines the url of the file to load
  77960. * @returns a new {BABYLON.BinaryFileAssetTask} object
  77961. */
  77962. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  77963. var task = new BinaryFileAssetTask(taskName, url);
  77964. this._tasks.push(task);
  77965. return task;
  77966. };
  77967. /**
  77968. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  77969. * @param taskName defines the name of the new task
  77970. * @param url defines the url of the file to load
  77971. * @returns a new {BABYLON.ImageAssetTask} object
  77972. */
  77973. AssetsManager.prototype.addImageTask = function (taskName, url) {
  77974. var task = new ImageAssetTask(taskName, url);
  77975. this._tasks.push(task);
  77976. return task;
  77977. };
  77978. /**
  77979. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  77980. * @param taskName defines the name of the new task
  77981. * @param url defines the url of the file to load
  77982. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  77983. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  77984. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  77985. * @returns a new {BABYLON.TextureAssetTask} object
  77986. */
  77987. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  77988. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  77989. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  77990. this._tasks.push(task);
  77991. return task;
  77992. };
  77993. /**
  77994. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  77995. * @param taskName defines the name of the new task
  77996. * @param url defines the url of the file to load
  77997. * @param extensions defines the extension to use to load the cube map (can be null)
  77998. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  77999. * @param files defines the list of files to load (can be null)
  78000. * @returns a new {BABYLON.CubeTextureAssetTask} object
  78001. */
  78002. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  78003. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  78004. this._tasks.push(task);
  78005. return task;
  78006. };
  78007. /**
  78008. *
  78009. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  78010. * @param taskName defines the name of the new task
  78011. * @param url defines the url of the file to load
  78012. * @param size defines the size you want for the cubemap (can be null)
  78013. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  78014. * @param generateHarmonics defines if you want to automatically generate (true by default)
  78015. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  78016. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  78017. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  78018. */
  78019. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  78020. if (noMipmap === void 0) { noMipmap = false; }
  78021. if (generateHarmonics === void 0) { generateHarmonics = true; }
  78022. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  78023. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  78024. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  78025. this._tasks.push(task);
  78026. return task;
  78027. };
  78028. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  78029. var _this = this;
  78030. this._waitingTasksCount--;
  78031. try {
  78032. if (task.taskState === AssetTaskState.DONE) {
  78033. // Let's remove successfull tasks
  78034. BABYLON.Tools.SetImmediate(function () {
  78035. var index = _this._tasks.indexOf(task);
  78036. if (index > -1) {
  78037. _this._tasks.splice(index, 1);
  78038. }
  78039. });
  78040. }
  78041. if (this.onProgress) {
  78042. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  78043. }
  78044. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  78045. }
  78046. catch (e) {
  78047. BABYLON.Tools.Error("Error running progress callbacks.");
  78048. console.log(e);
  78049. }
  78050. if (this._waitingTasksCount === 0) {
  78051. try {
  78052. if (this.onFinish) {
  78053. this.onFinish(this._tasks);
  78054. }
  78055. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78056. }
  78057. catch (e) {
  78058. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  78059. console.log(e);
  78060. }
  78061. this._isLoading = false;
  78062. this._scene.getEngine().hideLoadingUI();
  78063. }
  78064. };
  78065. AssetsManager.prototype._runTask = function (task) {
  78066. var _this = this;
  78067. var done = function () {
  78068. try {
  78069. if (_this.onTaskSuccess) {
  78070. _this.onTaskSuccess(task);
  78071. }
  78072. _this.onTaskSuccessObservable.notifyObservers(task);
  78073. _this._decreaseWaitingTasksCount(task);
  78074. }
  78075. catch (e) {
  78076. error("Error executing task success callbacks", e);
  78077. }
  78078. };
  78079. var error = function (message, exception) {
  78080. task._setErrorObject(message, exception);
  78081. if (_this.onTaskError) {
  78082. _this.onTaskError(task);
  78083. }
  78084. _this.onTaskErrorObservable.notifyObservers(task);
  78085. _this._decreaseWaitingTasksCount(task);
  78086. };
  78087. task.run(this._scene, done, error);
  78088. };
  78089. /**
  78090. * Reset the {BABYLON.AssetsManager} and remove all tasks
  78091. * @return the current instance of the {BABYLON.AssetsManager}
  78092. */
  78093. AssetsManager.prototype.reset = function () {
  78094. this._isLoading = false;
  78095. this._tasks = new Array();
  78096. return this;
  78097. };
  78098. /**
  78099. * Start the loading process
  78100. * @return the current instance of the {BABYLON.AssetsManager}
  78101. */
  78102. AssetsManager.prototype.load = function () {
  78103. if (this._isLoading) {
  78104. return this;
  78105. }
  78106. this._isLoading = true;
  78107. this._waitingTasksCount = this._tasks.length;
  78108. this._totalTasksCount = this._tasks.length;
  78109. if (this._waitingTasksCount === 0) {
  78110. if (this.onFinish) {
  78111. this.onFinish(this._tasks);
  78112. }
  78113. this.onTasksDoneObservable.notifyObservers(this._tasks);
  78114. return this;
  78115. }
  78116. if (this.useDefaultLoadingScreen) {
  78117. this._scene.getEngine().displayLoadingUI();
  78118. }
  78119. for (var index = 0; index < this._tasks.length; index++) {
  78120. var task = this._tasks[index];
  78121. this._runTask(task);
  78122. }
  78123. return this;
  78124. };
  78125. return AssetsManager;
  78126. }());
  78127. BABYLON.AssetsManager = AssetsManager;
  78128. })(BABYLON || (BABYLON = {}));
  78129. //# sourceMappingURL=babylon.assetsManager.js.map
  78130. var BABYLON;
  78131. (function (BABYLON) {
  78132. var serializedGeometries = [];
  78133. var serializeGeometry = function (geometry, serializationGeometries) {
  78134. if (serializedGeometries[geometry.id]) {
  78135. return;
  78136. }
  78137. if (geometry.doNotSerialize) {
  78138. return;
  78139. }
  78140. if (geometry instanceof BABYLON.BoxGeometry) {
  78141. serializationGeometries.boxes.push(geometry.serialize());
  78142. }
  78143. else if (geometry instanceof BABYLON.SphereGeometry) {
  78144. serializationGeometries.spheres.push(geometry.serialize());
  78145. }
  78146. else if (geometry instanceof BABYLON.CylinderGeometry) {
  78147. serializationGeometries.cylinders.push(geometry.serialize());
  78148. }
  78149. else if (geometry instanceof BABYLON.TorusGeometry) {
  78150. serializationGeometries.toruses.push(geometry.serialize());
  78151. }
  78152. else if (geometry instanceof BABYLON.GroundGeometry) {
  78153. serializationGeometries.grounds.push(geometry.serialize());
  78154. }
  78155. else if (geometry instanceof BABYLON.Plane) {
  78156. serializationGeometries.planes.push(geometry.serialize());
  78157. }
  78158. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  78159. serializationGeometries.torusKnots.push(geometry.serialize());
  78160. }
  78161. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  78162. throw new Error("Unknown primitive type");
  78163. }
  78164. else {
  78165. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  78166. }
  78167. serializedGeometries[geometry.id] = true;
  78168. };
  78169. var serializeMesh = function (mesh, serializationScene) {
  78170. var serializationObject = {};
  78171. // Geometry
  78172. var geometry = mesh._geometry;
  78173. if (geometry) {
  78174. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  78175. // 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
  78176. serializeGeometry(geometry, serializationScene.geometries);
  78177. }
  78178. }
  78179. // Custom
  78180. if (mesh.serialize) {
  78181. mesh.serialize(serializationObject);
  78182. }
  78183. return serializationObject;
  78184. };
  78185. var finalizeSingleMesh = function (mesh, serializationObject) {
  78186. //only works if the mesh is already loaded
  78187. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78188. //serialize material
  78189. if (mesh.material) {
  78190. if (mesh.material instanceof BABYLON.StandardMaterial) {
  78191. serializationObject.materials = serializationObject.materials || [];
  78192. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78193. serializationObject.materials.push(mesh.material.serialize());
  78194. }
  78195. }
  78196. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  78197. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  78198. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  78199. serializationObject.multiMaterials.push(mesh.material.serialize());
  78200. }
  78201. }
  78202. }
  78203. //serialize geometry
  78204. var geometry = mesh._geometry;
  78205. if (geometry) {
  78206. if (!serializationObject.geometries) {
  78207. serializationObject.geometries = {};
  78208. serializationObject.geometries.boxes = [];
  78209. serializationObject.geometries.spheres = [];
  78210. serializationObject.geometries.cylinders = [];
  78211. serializationObject.geometries.toruses = [];
  78212. serializationObject.geometries.grounds = [];
  78213. serializationObject.geometries.planes = [];
  78214. serializationObject.geometries.torusKnots = [];
  78215. serializationObject.geometries.vertexData = [];
  78216. }
  78217. serializeGeometry(geometry, serializationObject.geometries);
  78218. }
  78219. // Skeletons
  78220. if (mesh.skeleton) {
  78221. serializationObject.skeletons = serializationObject.skeletons || [];
  78222. serializationObject.skeletons.push(mesh.skeleton.serialize());
  78223. }
  78224. //serialize the actual mesh
  78225. serializationObject.meshes = serializationObject.meshes || [];
  78226. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78227. }
  78228. };
  78229. var SceneSerializer = /** @class */ (function () {
  78230. function SceneSerializer() {
  78231. }
  78232. SceneSerializer.ClearCache = function () {
  78233. serializedGeometries = [];
  78234. };
  78235. SceneSerializer.Serialize = function (scene) {
  78236. var serializationObject = {};
  78237. SceneSerializer.ClearCache();
  78238. // Scene
  78239. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  78240. serializationObject.autoClear = scene.autoClear;
  78241. serializationObject.clearColor = scene.clearColor.asArray();
  78242. serializationObject.ambientColor = scene.ambientColor.asArray();
  78243. serializationObject.gravity = scene.gravity.asArray();
  78244. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  78245. serializationObject.workerCollisions = scene.workerCollisions;
  78246. // Fog
  78247. if (scene.fogMode && scene.fogMode !== 0) {
  78248. serializationObject.fogMode = scene.fogMode;
  78249. serializationObject.fogColor = scene.fogColor.asArray();
  78250. serializationObject.fogStart = scene.fogStart;
  78251. serializationObject.fogEnd = scene.fogEnd;
  78252. serializationObject.fogDensity = scene.fogDensity;
  78253. }
  78254. //Physics
  78255. if (scene.isPhysicsEnabled()) {
  78256. var physicEngine = scene.getPhysicsEngine();
  78257. if (physicEngine) {
  78258. serializationObject.physicsEnabled = true;
  78259. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  78260. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  78261. }
  78262. }
  78263. // Metadata
  78264. if (scene.metadata) {
  78265. serializationObject.metadata = scene.metadata;
  78266. }
  78267. // Morph targets
  78268. serializationObject.morphTargetManagers = [];
  78269. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  78270. var abstractMesh = _a[_i];
  78271. var manager = abstractMesh.morphTargetManager;
  78272. if (manager) {
  78273. serializationObject.morphTargetManagers.push(manager.serialize());
  78274. }
  78275. }
  78276. // Lights
  78277. serializationObject.lights = [];
  78278. var index;
  78279. var light;
  78280. for (index = 0; index < scene.lights.length; index++) {
  78281. light = scene.lights[index];
  78282. if (!light.doNotSerialize) {
  78283. serializationObject.lights.push(light.serialize());
  78284. }
  78285. }
  78286. // Cameras
  78287. serializationObject.cameras = [];
  78288. for (index = 0; index < scene.cameras.length; index++) {
  78289. var camera = scene.cameras[index];
  78290. if (!camera.doNotSerialize) {
  78291. serializationObject.cameras.push(camera.serialize());
  78292. }
  78293. }
  78294. if (scene.activeCamera) {
  78295. serializationObject.activeCameraID = scene.activeCamera.id;
  78296. }
  78297. // Animations
  78298. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  78299. // Materials
  78300. serializationObject.materials = [];
  78301. serializationObject.multiMaterials = [];
  78302. var material;
  78303. for (index = 0; index < scene.materials.length; index++) {
  78304. material = scene.materials[index];
  78305. if (!material.doNotSerialize) {
  78306. serializationObject.materials.push(material.serialize());
  78307. }
  78308. }
  78309. // MultiMaterials
  78310. serializationObject.multiMaterials = [];
  78311. for (index = 0; index < scene.multiMaterials.length; index++) {
  78312. var multiMaterial = scene.multiMaterials[index];
  78313. serializationObject.multiMaterials.push(multiMaterial.serialize());
  78314. }
  78315. // Environment texture
  78316. if (scene.environmentTexture) {
  78317. serializationObject.environmentTexture = scene.environmentTexture.name;
  78318. }
  78319. // Skeletons
  78320. serializationObject.skeletons = [];
  78321. for (index = 0; index < scene.skeletons.length; index++) {
  78322. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  78323. }
  78324. // Transform nodes
  78325. serializationObject.transformNodes = [];
  78326. for (index = 0; index < scene.transformNodes.length; index++) {
  78327. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  78328. }
  78329. // Geometries
  78330. serializationObject.geometries = {};
  78331. serializationObject.geometries.boxes = [];
  78332. serializationObject.geometries.spheres = [];
  78333. serializationObject.geometries.cylinders = [];
  78334. serializationObject.geometries.toruses = [];
  78335. serializationObject.geometries.grounds = [];
  78336. serializationObject.geometries.planes = [];
  78337. serializationObject.geometries.torusKnots = [];
  78338. serializationObject.geometries.vertexData = [];
  78339. serializedGeometries = [];
  78340. var geometries = scene.getGeometries();
  78341. for (index = 0; index < geometries.length; index++) {
  78342. var geometry = geometries[index];
  78343. if (geometry.isReady()) {
  78344. serializeGeometry(geometry, serializationObject.geometries);
  78345. }
  78346. }
  78347. // Meshes
  78348. serializationObject.meshes = [];
  78349. for (index = 0; index < scene.meshes.length; index++) {
  78350. var abstractMesh = scene.meshes[index];
  78351. if (abstractMesh instanceof BABYLON.Mesh) {
  78352. var mesh = abstractMesh;
  78353. if (!mesh.doNotSerialize) {
  78354. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  78355. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  78356. }
  78357. }
  78358. }
  78359. }
  78360. // Particles Systems
  78361. serializationObject.particleSystems = [];
  78362. for (index = 0; index < scene.particleSystems.length; index++) {
  78363. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  78364. }
  78365. // Lens flares
  78366. serializationObject.lensFlareSystems = [];
  78367. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  78368. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  78369. }
  78370. // Shadows
  78371. serializationObject.shadowGenerators = [];
  78372. for (index = 0; index < scene.lights.length; index++) {
  78373. light = scene.lights[index];
  78374. var shadowGenerator = light.getShadowGenerator();
  78375. if (shadowGenerator) {
  78376. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  78377. }
  78378. }
  78379. // Action Manager
  78380. if (scene.actionManager) {
  78381. serializationObject.actions = scene.actionManager.serialize("scene");
  78382. }
  78383. // Audio
  78384. serializationObject.sounds = [];
  78385. for (index = 0; index < scene.soundTracks.length; index++) {
  78386. var soundtrack = scene.soundTracks[index];
  78387. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  78388. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  78389. }
  78390. }
  78391. return serializationObject;
  78392. };
  78393. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  78394. if (withParents === void 0) { withParents = false; }
  78395. if (withChildren === void 0) { withChildren = false; }
  78396. var serializationObject = {};
  78397. SceneSerializer.ClearCache();
  78398. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  78399. if (withParents || withChildren) {
  78400. //deliberate for loop! not for each, appended should be processed as well.
  78401. for (var i = 0; i < toSerialize.length; ++i) {
  78402. if (withChildren) {
  78403. toSerialize[i].getDescendants().forEach(function (node) {
  78404. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  78405. toSerialize.push(node);
  78406. }
  78407. });
  78408. }
  78409. //make sure the array doesn't contain the object already
  78410. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  78411. toSerialize.push(toSerialize[i].parent);
  78412. }
  78413. }
  78414. }
  78415. toSerialize.forEach(function (mesh) {
  78416. finalizeSingleMesh(mesh, serializationObject);
  78417. });
  78418. return serializationObject;
  78419. };
  78420. return SceneSerializer;
  78421. }());
  78422. BABYLON.SceneSerializer = SceneSerializer;
  78423. })(BABYLON || (BABYLON = {}));
  78424. //# sourceMappingURL=babylon.sceneSerializer.js.map
  78425. var BABYLON;
  78426. (function (BABYLON) {
  78427. var ReflectionProbe = /** @class */ (function () {
  78428. function ReflectionProbe(name, size, scene, generateMipMaps) {
  78429. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78430. var _this = this;
  78431. this.name = name;
  78432. this._viewMatrix = BABYLON.Matrix.Identity();
  78433. this._target = BABYLON.Vector3.Zero();
  78434. this._add = BABYLON.Vector3.Zero();
  78435. this.invertYAxis = false;
  78436. this.position = BABYLON.Vector3.Zero();
  78437. this._scene = scene;
  78438. this._scene.reflectionProbes.push(this);
  78439. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  78440. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  78441. switch (faceIndex) {
  78442. case 0:
  78443. _this._add.copyFromFloats(1, 0, 0);
  78444. break;
  78445. case 1:
  78446. _this._add.copyFromFloats(-1, 0, 0);
  78447. break;
  78448. case 2:
  78449. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  78450. break;
  78451. case 3:
  78452. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  78453. break;
  78454. case 4:
  78455. _this._add.copyFromFloats(0, 0, 1);
  78456. break;
  78457. case 5:
  78458. _this._add.copyFromFloats(0, 0, -1);
  78459. break;
  78460. }
  78461. if (_this._attachedMesh) {
  78462. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  78463. }
  78464. _this.position.addToRef(_this._add, _this._target);
  78465. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  78466. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  78467. scene._forcedViewPosition = _this.position;
  78468. });
  78469. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  78470. scene._forcedViewPosition = null;
  78471. scene.updateTransformMatrix(true);
  78472. });
  78473. if (scene.activeCamera) {
  78474. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  78475. }
  78476. }
  78477. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  78478. get: function () {
  78479. return this._renderTargetTexture.samples;
  78480. },
  78481. set: function (value) {
  78482. this._renderTargetTexture.samples = value;
  78483. },
  78484. enumerable: true,
  78485. configurable: true
  78486. });
  78487. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  78488. get: function () {
  78489. return this._renderTargetTexture.refreshRate;
  78490. },
  78491. set: function (value) {
  78492. this._renderTargetTexture.refreshRate = value;
  78493. },
  78494. enumerable: true,
  78495. configurable: true
  78496. });
  78497. ReflectionProbe.prototype.getScene = function () {
  78498. return this._scene;
  78499. };
  78500. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  78501. get: function () {
  78502. return this._renderTargetTexture;
  78503. },
  78504. enumerable: true,
  78505. configurable: true
  78506. });
  78507. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  78508. get: function () {
  78509. return this._renderTargetTexture.renderList;
  78510. },
  78511. enumerable: true,
  78512. configurable: true
  78513. });
  78514. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  78515. this._attachedMesh = mesh;
  78516. };
  78517. /**
  78518. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  78519. *
  78520. * @param renderingGroupId The rendering group id corresponding to its index
  78521. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  78522. */
  78523. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  78524. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  78525. };
  78526. ReflectionProbe.prototype.dispose = function () {
  78527. var index = this._scene.reflectionProbes.indexOf(this);
  78528. if (index !== -1) {
  78529. // Remove from the scene if found
  78530. this._scene.reflectionProbes.splice(index, 1);
  78531. }
  78532. if (this._renderTargetTexture) {
  78533. this._renderTargetTexture.dispose();
  78534. this._renderTargetTexture = null;
  78535. }
  78536. };
  78537. return ReflectionProbe;
  78538. }());
  78539. BABYLON.ReflectionProbe = ReflectionProbe;
  78540. })(BABYLON || (BABYLON = {}));
  78541. //# sourceMappingURL=babylon.reflectionProbe.js.map
  78542. var BABYLON;
  78543. (function (BABYLON) {
  78544. var Layer = /** @class */ (function () {
  78545. function Layer(name, imgUrl, scene, isBackground, color) {
  78546. this.name = name;
  78547. this.scale = new BABYLON.Vector2(1, 1);
  78548. this.offset = new BABYLON.Vector2(0, 0);
  78549. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  78550. this.layerMask = 0x0FFFFFFF;
  78551. this._vertexBuffers = {};
  78552. // Events
  78553. /**
  78554. * An event triggered when the layer is disposed.
  78555. * @type {BABYLON.Observable}
  78556. */
  78557. this.onDisposeObservable = new BABYLON.Observable();
  78558. /**
  78559. * An event triggered before rendering the scene
  78560. * @type {BABYLON.Observable}
  78561. */
  78562. this.onBeforeRenderObservable = new BABYLON.Observable();
  78563. /**
  78564. * An event triggered after rendering the scene
  78565. * @type {BABYLON.Observable}
  78566. */
  78567. this.onAfterRenderObservable = new BABYLON.Observable();
  78568. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  78569. this.isBackground = isBackground === undefined ? true : isBackground;
  78570. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  78571. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  78572. this._scene.layers.push(this);
  78573. var engine = this._scene.getEngine();
  78574. // VBO
  78575. var vertices = [];
  78576. vertices.push(1, 1);
  78577. vertices.push(-1, 1);
  78578. vertices.push(-1, -1);
  78579. vertices.push(1, -1);
  78580. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  78581. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  78582. this._createIndexBuffer();
  78583. // Effects
  78584. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  78585. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  78586. }
  78587. Object.defineProperty(Layer.prototype, "onDispose", {
  78588. set: function (callback) {
  78589. if (this._onDisposeObserver) {
  78590. this.onDisposeObservable.remove(this._onDisposeObserver);
  78591. }
  78592. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  78593. },
  78594. enumerable: true,
  78595. configurable: true
  78596. });
  78597. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  78598. set: function (callback) {
  78599. if (this._onBeforeRenderObserver) {
  78600. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  78601. }
  78602. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  78603. },
  78604. enumerable: true,
  78605. configurable: true
  78606. });
  78607. Object.defineProperty(Layer.prototype, "onAfterRender", {
  78608. set: function (callback) {
  78609. if (this._onAfterRenderObserver) {
  78610. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  78611. }
  78612. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  78613. },
  78614. enumerable: true,
  78615. configurable: true
  78616. });
  78617. Layer.prototype._createIndexBuffer = function () {
  78618. var engine = this._scene.getEngine();
  78619. // Indices
  78620. var indices = [];
  78621. indices.push(0);
  78622. indices.push(1);
  78623. indices.push(2);
  78624. indices.push(0);
  78625. indices.push(2);
  78626. indices.push(3);
  78627. this._indexBuffer = engine.createIndexBuffer(indices);
  78628. };
  78629. Layer.prototype._rebuild = function () {
  78630. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78631. if (vb) {
  78632. vb._rebuild();
  78633. }
  78634. this._createIndexBuffer();
  78635. };
  78636. Layer.prototype.render = function () {
  78637. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  78638. // Check
  78639. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  78640. return;
  78641. var engine = this._scene.getEngine();
  78642. this.onBeforeRenderObservable.notifyObservers(this);
  78643. // Render
  78644. engine.enableEffect(currentEffect);
  78645. engine.setState(false);
  78646. // Texture
  78647. currentEffect.setTexture("textureSampler", this.texture);
  78648. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  78649. // Color
  78650. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  78651. // Scale / offset
  78652. currentEffect.setVector2("offset", this.offset);
  78653. currentEffect.setVector2("scale", this.scale);
  78654. // VBOs
  78655. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  78656. // Draw order
  78657. if (!this.alphaTest) {
  78658. engine.setAlphaMode(this.alphaBlendingMode);
  78659. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78660. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78661. }
  78662. else {
  78663. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  78664. }
  78665. this.onAfterRenderObservable.notifyObservers(this);
  78666. };
  78667. Layer.prototype.dispose = function () {
  78668. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78669. if (vertexBuffer) {
  78670. vertexBuffer.dispose();
  78671. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78672. }
  78673. if (this._indexBuffer) {
  78674. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78675. this._indexBuffer = null;
  78676. }
  78677. if (this.texture) {
  78678. this.texture.dispose();
  78679. this.texture = null;
  78680. }
  78681. // Remove from scene
  78682. var index = this._scene.layers.indexOf(this);
  78683. this._scene.layers.splice(index, 1);
  78684. // Callback
  78685. this.onDisposeObservable.notifyObservers(this);
  78686. this.onDisposeObservable.clear();
  78687. this.onAfterRenderObservable.clear();
  78688. this.onBeforeRenderObservable.clear();
  78689. };
  78690. return Layer;
  78691. }());
  78692. BABYLON.Layer = Layer;
  78693. })(BABYLON || (BABYLON = {}));
  78694. //# sourceMappingURL=babylon.layer.js.map
  78695. var BABYLON;
  78696. (function (BABYLON) {
  78697. var TextureTools = /** @class */ (function () {
  78698. function TextureTools() {
  78699. }
  78700. /**
  78701. * Uses the GPU to create a copy texture rescaled at a given size
  78702. * @param texture Texture to copy from
  78703. * @param width Desired width
  78704. * @param height Desired height
  78705. * @return Generated texture
  78706. */
  78707. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  78708. if (useBilinearMode === void 0) { useBilinearMode = true; }
  78709. var scene = texture.getScene();
  78710. var engine = scene.getEngine();
  78711. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  78712. rtt.wrapU = texture.wrapU;
  78713. rtt.wrapV = texture.wrapV;
  78714. rtt.uOffset = texture.uOffset;
  78715. rtt.vOffset = texture.vOffset;
  78716. rtt.uScale = texture.uScale;
  78717. rtt.vScale = texture.vScale;
  78718. rtt.uAng = texture.uAng;
  78719. rtt.vAng = texture.vAng;
  78720. rtt.wAng = texture.wAng;
  78721. rtt.coordinatesIndex = texture.coordinatesIndex;
  78722. rtt.level = texture.level;
  78723. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  78724. rtt._texture.isReady = false;
  78725. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78726. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78727. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78728. passPostProcess.getEffect().executeWhenCompiled(function () {
  78729. passPostProcess.onApply = function (effect) {
  78730. effect.setTexture("textureSampler", texture);
  78731. };
  78732. var internalTexture = rtt.getInternalTexture();
  78733. if (internalTexture) {
  78734. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  78735. engine.unBindFramebuffer(internalTexture);
  78736. rtt.disposeFramebufferObjects();
  78737. passPostProcess.dispose();
  78738. internalTexture.isReady = true;
  78739. }
  78740. });
  78741. return rtt;
  78742. };
  78743. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  78744. if (!scene._environmentBRDFTexture) {
  78745. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  78746. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78747. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78748. scene._environmentBRDFTexture = texture;
  78749. }
  78750. return scene._environmentBRDFTexture;
  78751. };
  78752. 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=";
  78753. return TextureTools;
  78754. }());
  78755. BABYLON.TextureTools = TextureTools;
  78756. })(BABYLON || (BABYLON = {}));
  78757. //# sourceMappingURL=babylon.textureTools.js.map
  78758. var BABYLON;
  78759. (function (BABYLON) {
  78760. var FramingBehavior = /** @class */ (function () {
  78761. function FramingBehavior() {
  78762. this._mode = FramingBehavior.FitFrustumSidesMode;
  78763. this._radiusScale = 1.0;
  78764. this._positionScale = 0.5;
  78765. this._defaultElevation = 0.3;
  78766. this._elevationReturnTime = 1500;
  78767. this._elevationReturnWaitTime = 1000;
  78768. this._zoomStopsAnimation = false;
  78769. this._framingTime = 1500;
  78770. this._isPointerDown = false;
  78771. this._lastInteractionTime = -Infinity;
  78772. // Framing control
  78773. this._animatables = new Array();
  78774. this._betaIsAnimating = false;
  78775. }
  78776. Object.defineProperty(FramingBehavior.prototype, "name", {
  78777. get: function () {
  78778. return "Framing";
  78779. },
  78780. enumerable: true,
  78781. configurable: true
  78782. });
  78783. Object.defineProperty(FramingBehavior.prototype, "mode", {
  78784. /**
  78785. * Gets current mode used by the behavior.
  78786. */
  78787. get: function () {
  78788. return this._mode;
  78789. },
  78790. /**
  78791. * Sets the current mode used by the behavior
  78792. */
  78793. set: function (mode) {
  78794. this._mode = mode;
  78795. },
  78796. enumerable: true,
  78797. configurable: true
  78798. });
  78799. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  78800. /**
  78801. * Gets the scale applied to the radius
  78802. */
  78803. get: function () {
  78804. return this._radiusScale;
  78805. },
  78806. /**
  78807. * Sets the scale applied to the radius (1 by default)
  78808. */
  78809. set: function (radius) {
  78810. this._radiusScale = radius;
  78811. },
  78812. enumerable: true,
  78813. configurable: true
  78814. });
  78815. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  78816. /**
  78817. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78818. */
  78819. get: function () {
  78820. return this._positionScale;
  78821. },
  78822. /**
  78823. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  78824. */
  78825. set: function (scale) {
  78826. this._positionScale = scale;
  78827. },
  78828. enumerable: true,
  78829. configurable: true
  78830. });
  78831. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  78832. /**
  78833. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78834. * behaviour is triggered, in radians.
  78835. */
  78836. get: function () {
  78837. return this._defaultElevation;
  78838. },
  78839. /**
  78840. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  78841. * behaviour is triggered, in radians.
  78842. */
  78843. set: function (elevation) {
  78844. this._defaultElevation = elevation;
  78845. },
  78846. enumerable: true,
  78847. configurable: true
  78848. });
  78849. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  78850. /**
  78851. * Gets the time (in milliseconds) taken to return to the default beta position.
  78852. * Negative value indicates camera should not return to default.
  78853. */
  78854. get: function () {
  78855. return this._elevationReturnTime;
  78856. },
  78857. /**
  78858. * Sets the time (in milliseconds) taken to return to the default beta position.
  78859. * Negative value indicates camera should not return to default.
  78860. */
  78861. set: function (speed) {
  78862. this._elevationReturnTime = speed;
  78863. },
  78864. enumerable: true,
  78865. configurable: true
  78866. });
  78867. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  78868. /**
  78869. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78870. */
  78871. get: function () {
  78872. return this._elevationReturnWaitTime;
  78873. },
  78874. /**
  78875. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  78876. */
  78877. set: function (time) {
  78878. this._elevationReturnWaitTime = time;
  78879. },
  78880. enumerable: true,
  78881. configurable: true
  78882. });
  78883. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  78884. /**
  78885. * Gets the flag that indicates if user zooming should stop animation.
  78886. */
  78887. get: function () {
  78888. return this._zoomStopsAnimation;
  78889. },
  78890. /**
  78891. * Sets the flag that indicates if user zooming should stop animation.
  78892. */
  78893. set: function (flag) {
  78894. this._zoomStopsAnimation = flag;
  78895. },
  78896. enumerable: true,
  78897. configurable: true
  78898. });
  78899. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  78900. /**
  78901. * Gets the transition time when framing the mesh, in milliseconds
  78902. */
  78903. get: function () {
  78904. return this._framingTime;
  78905. },
  78906. /**
  78907. * Sets the transition time when framing the mesh, in milliseconds
  78908. */
  78909. set: function (time) {
  78910. this._framingTime = time;
  78911. },
  78912. enumerable: true,
  78913. configurable: true
  78914. });
  78915. FramingBehavior.prototype.init = function () {
  78916. // Do notihng
  78917. };
  78918. FramingBehavior.prototype.attach = function (camera) {
  78919. var _this = this;
  78920. this._attachedCamera = camera;
  78921. var scene = this._attachedCamera.getScene();
  78922. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  78923. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  78924. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78925. _this._isPointerDown = true;
  78926. return;
  78927. }
  78928. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  78929. _this._isPointerDown = false;
  78930. }
  78931. });
  78932. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  78933. if (mesh) {
  78934. _this.zoomOnMesh(mesh);
  78935. }
  78936. });
  78937. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78938. // Stop the animation if there is user interaction and the animation should stop for this interaction
  78939. _this._applyUserInteraction();
  78940. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  78941. // back to the default position after a given timeout
  78942. _this._maintainCameraAboveGround();
  78943. });
  78944. };
  78945. FramingBehavior.prototype.detach = function () {
  78946. if (!this._attachedCamera) {
  78947. return;
  78948. }
  78949. var scene = this._attachedCamera.getScene();
  78950. if (this._onPrePointerObservableObserver) {
  78951. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  78952. }
  78953. if (this._onAfterCheckInputsObserver) {
  78954. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78955. }
  78956. if (this._onMeshTargetChangedObserver) {
  78957. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78958. }
  78959. this._attachedCamera = null;
  78960. };
  78961. /**
  78962. * Targets the given mesh and updates zoom level accordingly.
  78963. * @param mesh The mesh to target.
  78964. * @param radius Optional. If a cached radius position already exists, overrides default.
  78965. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78966. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78967. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78968. */
  78969. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78970. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78971. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78972. mesh.computeWorldMatrix(true);
  78973. var boundingBox = mesh.getBoundingInfo().boundingBox;
  78974. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  78975. };
  78976. /**
  78977. * Targets the given mesh with its children and updates zoom level accordingly.
  78978. * @param mesh The mesh to target.
  78979. * @param radius Optional. If a cached radius position already exists, overrides default.
  78980. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78981. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78982. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78983. */
  78984. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  78985. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  78986. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  78987. mesh.computeWorldMatrix(true);
  78988. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  78989. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  78990. };
  78991. /**
  78992. * Targets the given meshes with their children and updates zoom level accordingly.
  78993. * @param meshes The mesh to target.
  78994. * @param radius Optional. If a cached radius position already exists, overrides default.
  78995. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  78996. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  78997. * @param onAnimationEnd Callback triggered at the end of the framing animation
  78998. */
  78999. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  79000. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79001. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79002. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  79003. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  79004. for (var i = 0; i < meshes.length; i++) {
  79005. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  79006. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  79007. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  79008. }
  79009. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  79010. };
  79011. /**
  79012. * Targets the given mesh and updates zoom level accordingly.
  79013. * @param mesh The mesh to target.
  79014. * @param radius Optional. If a cached radius position already exists, overrides default.
  79015. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  79016. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  79017. * @param onAnimationEnd Callback triggered at the end of the framing animation
  79018. */
  79019. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  79020. var _this = this;
  79021. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  79022. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  79023. var zoomTarget;
  79024. if (!this._attachedCamera) {
  79025. return;
  79026. }
  79027. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  79028. var bottom = minimumWorld.y;
  79029. var top = maximumWorld.y;
  79030. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  79031. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  79032. if (focusOnOriginXZ) {
  79033. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  79034. }
  79035. else {
  79036. var centerWorld = minimumWorld.add(radiusWorld);
  79037. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  79038. }
  79039. if (!this._vectorTransition) {
  79040. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  79041. }
  79042. this._betaIsAnimating = true;
  79043. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  79044. if (animatable) {
  79045. this._animatables.push(animatable);
  79046. }
  79047. // sets the radius and lower radius bounds
  79048. // Small delta ensures camera is not always at lower zoom limit.
  79049. var radius = 0;
  79050. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  79051. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79052. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  79053. radius = position;
  79054. }
  79055. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79056. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  79057. if (this._attachedCamera.lowerRadiusLimit === null) {
  79058. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  79059. }
  79060. }
  79061. // Set sensibilities
  79062. var extend = maximumWorld.subtract(minimumWorld).length();
  79063. this._attachedCamera.panningSensibility = 5000 / extend;
  79064. this._attachedCamera.wheelPrecision = 100 / radius;
  79065. // transition to new radius
  79066. if (!this._radiusTransition) {
  79067. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79068. }
  79069. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  79070. if (onAnimationEnd) {
  79071. onAnimationEnd();
  79072. }
  79073. if (_this._attachedCamera) {
  79074. _this._attachedCamera.storeState();
  79075. }
  79076. });
  79077. if (animatable) {
  79078. this._animatables.push(animatable);
  79079. }
  79080. };
  79081. /**
  79082. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  79083. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  79084. * frustum width.
  79085. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  79086. * to fully enclose the mesh in the viewing frustum.
  79087. */
  79088. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  79089. var size = maximumWorld.subtract(minimumWorld);
  79090. var boxVectorGlobalDiagonal = size.length();
  79091. var frustumSlope = this._getFrustumSlope();
  79092. // Formula for setting distance
  79093. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  79094. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  79095. // Horizon distance
  79096. var radius = radiusWithoutFraming * this._radiusScale;
  79097. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  79098. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  79099. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  79100. var camera = this._attachedCamera;
  79101. if (!camera) {
  79102. return 0;
  79103. }
  79104. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  79105. // Don't exceed the requested limit
  79106. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  79107. }
  79108. // Don't exceed the upper radius limit
  79109. if (camera.upperRadiusLimit) {
  79110. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  79111. }
  79112. return distance;
  79113. };
  79114. /**
  79115. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  79116. * is automatically returned to its default position (expected to be above ground plane).
  79117. */
  79118. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  79119. var _this = this;
  79120. if (this._elevationReturnTime < 0) {
  79121. return;
  79122. }
  79123. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  79124. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  79125. var limitBeta = Math.PI * 0.5;
  79126. // Bring the camera back up if below the ground plane
  79127. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  79128. this._betaIsAnimating = true;
  79129. //Transition to new position
  79130. this.stopAllAnimations();
  79131. if (!this._betaTransition) {
  79132. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  79133. }
  79134. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  79135. _this._clearAnimationLocks();
  79136. _this.stopAllAnimations();
  79137. });
  79138. if (animatabe) {
  79139. this._animatables.push(animatabe);
  79140. }
  79141. }
  79142. };
  79143. /**
  79144. * Returns the frustum slope based on the canvas ratio and camera FOV
  79145. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  79146. */
  79147. FramingBehavior.prototype._getFrustumSlope = function () {
  79148. // Calculate the viewport ratio
  79149. // Aspect Ratio is Height/Width.
  79150. var camera = this._attachedCamera;
  79151. if (!camera) {
  79152. return BABYLON.Vector2.Zero();
  79153. }
  79154. var engine = camera.getScene().getEngine();
  79155. var aspectRatio = engine.getAspectRatio(camera);
  79156. // Camera FOV is the vertical field of view (top-bottom) in radians.
  79157. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  79158. var frustumSlopeY = Math.tan(camera.fov / 2);
  79159. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  79160. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  79161. // along the forward vector.
  79162. var frustumSlopeX = frustumSlopeY * aspectRatio;
  79163. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  79164. };
  79165. /**
  79166. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  79167. */
  79168. FramingBehavior.prototype._clearAnimationLocks = function () {
  79169. this._betaIsAnimating = false;
  79170. };
  79171. /**
  79172. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79173. */
  79174. FramingBehavior.prototype._applyUserInteraction = function () {
  79175. if (this.isUserIsMoving) {
  79176. this._lastInteractionTime = BABYLON.Tools.Now;
  79177. this.stopAllAnimations();
  79178. this._clearAnimationLocks();
  79179. }
  79180. };
  79181. /**
  79182. * Stops and removes all animations that have been applied to the camera
  79183. */
  79184. FramingBehavior.prototype.stopAllAnimations = function () {
  79185. if (this._attachedCamera) {
  79186. this._attachedCamera.animations = [];
  79187. }
  79188. while (this._animatables.length) {
  79189. if (this._animatables[0]) {
  79190. this._animatables[0].onAnimationEnd = null;
  79191. this._animatables[0].stop();
  79192. }
  79193. this._animatables.shift();
  79194. }
  79195. };
  79196. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  79197. /**
  79198. * Gets a value indicating if the user is moving the camera
  79199. */
  79200. get: function () {
  79201. if (!this._attachedCamera) {
  79202. return false;
  79203. }
  79204. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79205. this._attachedCamera.inertialBetaOffset !== 0 ||
  79206. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79207. this._attachedCamera.inertialPanningX !== 0 ||
  79208. this._attachedCamera.inertialPanningY !== 0 ||
  79209. this._isPointerDown;
  79210. },
  79211. enumerable: true,
  79212. configurable: true
  79213. });
  79214. /**
  79215. * The easing function used by animations
  79216. */
  79217. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  79218. /**
  79219. * The easing mode used by animations
  79220. */
  79221. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  79222. // Statics
  79223. /**
  79224. * The camera can move all the way towards the mesh.
  79225. */
  79226. FramingBehavior.IgnoreBoundsSizeMode = 0;
  79227. /**
  79228. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  79229. */
  79230. FramingBehavior.FitFrustumSidesMode = 1;
  79231. return FramingBehavior;
  79232. }());
  79233. BABYLON.FramingBehavior = FramingBehavior;
  79234. })(BABYLON || (BABYLON = {}));
  79235. //# sourceMappingURL=babylon.framingBehavior.js.map
  79236. var BABYLON;
  79237. (function (BABYLON) {
  79238. /**
  79239. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  79240. */
  79241. var BouncingBehavior = /** @class */ (function () {
  79242. function BouncingBehavior() {
  79243. /**
  79244. * The duration of the animation, in milliseconds
  79245. */
  79246. this.transitionDuration = 450;
  79247. /**
  79248. * Length of the distance animated by the transition when lower radius is reached
  79249. */
  79250. this.lowerRadiusTransitionRange = 2;
  79251. /**
  79252. * Length of the distance animated by the transition when upper radius is reached
  79253. */
  79254. this.upperRadiusTransitionRange = -2;
  79255. this._autoTransitionRange = false;
  79256. // Animations
  79257. this._radiusIsAnimating = false;
  79258. this._radiusBounceTransition = null;
  79259. this._animatables = new Array();
  79260. }
  79261. Object.defineProperty(BouncingBehavior.prototype, "name", {
  79262. get: function () {
  79263. return "Bouncing";
  79264. },
  79265. enumerable: true,
  79266. configurable: true
  79267. });
  79268. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  79269. /**
  79270. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79271. */
  79272. get: function () {
  79273. return this._autoTransitionRange;
  79274. },
  79275. /**
  79276. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  79277. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  79278. */
  79279. set: function (value) {
  79280. var _this = this;
  79281. if (this._autoTransitionRange === value) {
  79282. return;
  79283. }
  79284. this._autoTransitionRange = value;
  79285. var camera = this._attachedCamera;
  79286. if (!camera) {
  79287. return;
  79288. }
  79289. if (value) {
  79290. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  79291. if (!mesh) {
  79292. return;
  79293. }
  79294. mesh.computeWorldMatrix(true);
  79295. var diagonal = mesh.getBoundingInfo().diagonalLength;
  79296. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  79297. _this.upperRadiusTransitionRange = diagonal * 0.05;
  79298. });
  79299. }
  79300. else if (this._onMeshTargetChangedObserver) {
  79301. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79302. }
  79303. },
  79304. enumerable: true,
  79305. configurable: true
  79306. });
  79307. BouncingBehavior.prototype.init = function () {
  79308. // Do notihng
  79309. };
  79310. BouncingBehavior.prototype.attach = function (camera) {
  79311. var _this = this;
  79312. this._attachedCamera = camera;
  79313. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79314. if (!_this._attachedCamera) {
  79315. return;
  79316. }
  79317. // Add the bounce animation to the lower radius limit
  79318. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  79319. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  79320. }
  79321. // Add the bounce animation to the upper radius limit
  79322. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  79323. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  79324. }
  79325. });
  79326. };
  79327. BouncingBehavior.prototype.detach = function () {
  79328. if (!this._attachedCamera) {
  79329. return;
  79330. }
  79331. if (this._onAfterCheckInputsObserver) {
  79332. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79333. }
  79334. if (this._onMeshTargetChangedObserver) {
  79335. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  79336. }
  79337. this._attachedCamera = null;
  79338. };
  79339. /**
  79340. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  79341. * @param radiusLimit The limit to check against.
  79342. * @return Bool to indicate if at limit.
  79343. */
  79344. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  79345. if (!this._attachedCamera) {
  79346. return false;
  79347. }
  79348. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  79349. return true;
  79350. }
  79351. return false;
  79352. };
  79353. /**
  79354. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  79355. * @param radiusDelta The delta by which to animate to. Can be negative.
  79356. */
  79357. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  79358. var _this = this;
  79359. if (!this._attachedCamera) {
  79360. return;
  79361. }
  79362. if (!this._radiusBounceTransition) {
  79363. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  79364. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  79365. }
  79366. // Prevent zoom until bounce has completed
  79367. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  79368. this._attachedCamera.wheelPrecision = Infinity;
  79369. this._attachedCamera.inertialRadiusOffset = 0;
  79370. // Animate to the radius limit
  79371. this.stopAllAnimations();
  79372. this._radiusIsAnimating = true;
  79373. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  79374. if (animatable) {
  79375. this._animatables.push(animatable);
  79376. }
  79377. };
  79378. /**
  79379. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  79380. */
  79381. BouncingBehavior.prototype._clearAnimationLocks = function () {
  79382. this._radiusIsAnimating = false;
  79383. if (this._attachedCamera) {
  79384. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  79385. }
  79386. };
  79387. /**
  79388. * Stops and removes all animations that have been applied to the camera
  79389. */
  79390. BouncingBehavior.prototype.stopAllAnimations = function () {
  79391. if (this._attachedCamera) {
  79392. this._attachedCamera.animations = [];
  79393. }
  79394. while (this._animatables.length) {
  79395. this._animatables[0].onAnimationEnd = null;
  79396. this._animatables[0].stop();
  79397. this._animatables.shift();
  79398. }
  79399. };
  79400. /**
  79401. * The easing function used by animations
  79402. */
  79403. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  79404. /**
  79405. * The easing mode used by animations
  79406. */
  79407. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  79408. return BouncingBehavior;
  79409. }());
  79410. BABYLON.BouncingBehavior = BouncingBehavior;
  79411. })(BABYLON || (BABYLON = {}));
  79412. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  79413. var BABYLON;
  79414. (function (BABYLON) {
  79415. var AutoRotationBehavior = /** @class */ (function () {
  79416. function AutoRotationBehavior() {
  79417. this._zoomStopsAnimation = false;
  79418. this._idleRotationSpeed = 0.05;
  79419. this._idleRotationWaitTime = 2000;
  79420. this._idleRotationSpinupTime = 2000;
  79421. this._isPointerDown = false;
  79422. this._lastFrameTime = null;
  79423. this._lastInteractionTime = -Infinity;
  79424. this._cameraRotationSpeed = 0;
  79425. this._lastFrameRadius = 0;
  79426. }
  79427. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  79428. get: function () {
  79429. return "AutoRotation";
  79430. },
  79431. enumerable: true,
  79432. configurable: true
  79433. });
  79434. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  79435. /**
  79436. * Gets the flag that indicates if user zooming should stop animation.
  79437. */
  79438. get: function () {
  79439. return this._zoomStopsAnimation;
  79440. },
  79441. /**
  79442. * Sets the flag that indicates if user zooming should stop animation.
  79443. */
  79444. set: function (flag) {
  79445. this._zoomStopsAnimation = flag;
  79446. },
  79447. enumerable: true,
  79448. configurable: true
  79449. });
  79450. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  79451. /**
  79452. * Gets the default speed at which the camera rotates around the model.
  79453. */
  79454. get: function () {
  79455. return this._idleRotationSpeed;
  79456. },
  79457. /**
  79458. * Sets the default speed at which the camera rotates around the model.
  79459. */
  79460. set: function (speed) {
  79461. this._idleRotationSpeed = speed;
  79462. },
  79463. enumerable: true,
  79464. configurable: true
  79465. });
  79466. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  79467. /**
  79468. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  79469. */
  79470. get: function () {
  79471. return this._idleRotationWaitTime;
  79472. },
  79473. /**
  79474. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  79475. */
  79476. set: function (time) {
  79477. this._idleRotationWaitTime = time;
  79478. },
  79479. enumerable: true,
  79480. configurable: true
  79481. });
  79482. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  79483. /**
  79484. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79485. */
  79486. get: function () {
  79487. return this._idleRotationSpinupTime;
  79488. },
  79489. /**
  79490. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  79491. */
  79492. set: function (time) {
  79493. this._idleRotationSpinupTime = time;
  79494. },
  79495. enumerable: true,
  79496. configurable: true
  79497. });
  79498. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  79499. /**
  79500. * Gets a value indicating if the camera is currently rotating because of this behavior
  79501. */
  79502. get: function () {
  79503. return Math.abs(this._cameraRotationSpeed) > 0;
  79504. },
  79505. enumerable: true,
  79506. configurable: true
  79507. });
  79508. AutoRotationBehavior.prototype.init = function () {
  79509. // Do notihng
  79510. };
  79511. AutoRotationBehavior.prototype.attach = function (camera) {
  79512. var _this = this;
  79513. this._attachedCamera = camera;
  79514. var scene = this._attachedCamera.getScene();
  79515. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  79516. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  79517. _this._isPointerDown = true;
  79518. return;
  79519. }
  79520. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  79521. _this._isPointerDown = false;
  79522. }
  79523. });
  79524. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  79525. var now = BABYLON.Tools.Now;
  79526. var dt = 0;
  79527. if (_this._lastFrameTime != null) {
  79528. dt = now - _this._lastFrameTime;
  79529. }
  79530. _this._lastFrameTime = now;
  79531. // Stop the animation if there is user interaction and the animation should stop for this interaction
  79532. _this._applyUserInteraction();
  79533. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  79534. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  79535. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  79536. // Step camera rotation by rotation speed
  79537. if (_this._attachedCamera) {
  79538. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  79539. }
  79540. });
  79541. };
  79542. AutoRotationBehavior.prototype.detach = function () {
  79543. if (!this._attachedCamera) {
  79544. return;
  79545. }
  79546. var scene = this._attachedCamera.getScene();
  79547. if (this._onPrePointerObservableObserver) {
  79548. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  79549. }
  79550. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  79551. this._attachedCamera = null;
  79552. };
  79553. /**
  79554. * Returns true if user is scrolling.
  79555. * @return true if user is scrolling.
  79556. */
  79557. AutoRotationBehavior.prototype._userIsZooming = function () {
  79558. if (!this._attachedCamera) {
  79559. return false;
  79560. }
  79561. return this._attachedCamera.inertialRadiusOffset !== 0;
  79562. };
  79563. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  79564. if (!this._attachedCamera) {
  79565. return false;
  79566. }
  79567. var zoomHasHitLimit = false;
  79568. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  79569. zoomHasHitLimit = true;
  79570. }
  79571. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  79572. this._lastFrameRadius = this._attachedCamera.radius;
  79573. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  79574. };
  79575. /**
  79576. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  79577. */
  79578. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  79579. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  79580. this._lastInteractionTime = BABYLON.Tools.Now;
  79581. }
  79582. };
  79583. // Tools
  79584. AutoRotationBehavior.prototype._userIsMoving = function () {
  79585. if (!this._attachedCamera) {
  79586. return false;
  79587. }
  79588. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  79589. this._attachedCamera.inertialBetaOffset !== 0 ||
  79590. this._attachedCamera.inertialRadiusOffset !== 0 ||
  79591. this._attachedCamera.inertialPanningX !== 0 ||
  79592. this._attachedCamera.inertialPanningY !== 0 ||
  79593. this._isPointerDown;
  79594. };
  79595. return AutoRotationBehavior;
  79596. }());
  79597. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  79598. })(BABYLON || (BABYLON = {}));
  79599. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  79600. var BABYLON;
  79601. (function (BABYLON) {
  79602. /**
  79603. * This class can be used to get instrumentation data from a Babylon engine
  79604. */
  79605. var EngineInstrumentation = /** @class */ (function () {
  79606. function EngineInstrumentation(engine) {
  79607. this.engine = engine;
  79608. this._captureGPUFrameTime = false;
  79609. this._gpuFrameTime = new BABYLON.PerfCounter();
  79610. this._captureShaderCompilationTime = false;
  79611. this._shaderCompilationTime = new BABYLON.PerfCounter();
  79612. // Observers
  79613. this._onBeginFrameObserver = null;
  79614. this._onEndFrameObserver = null;
  79615. this._onBeforeShaderCompilationObserver = null;
  79616. this._onAfterShaderCompilationObserver = null;
  79617. }
  79618. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  79619. // Properties
  79620. /**
  79621. * Gets the perf counter used for GPU frame time
  79622. */
  79623. get: function () {
  79624. return this._gpuFrameTime;
  79625. },
  79626. enumerable: true,
  79627. configurable: true
  79628. });
  79629. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  79630. /**
  79631. * Gets the GPU frame time capture status
  79632. */
  79633. get: function () {
  79634. return this._captureGPUFrameTime;
  79635. },
  79636. /**
  79637. * Enable or disable the GPU frame time capture
  79638. */
  79639. set: function (value) {
  79640. var _this = this;
  79641. if (value === this._captureGPUFrameTime) {
  79642. return;
  79643. }
  79644. this._captureGPUFrameTime = value;
  79645. if (value) {
  79646. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  79647. if (!_this._gpuFrameTimeToken) {
  79648. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  79649. }
  79650. });
  79651. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  79652. if (!_this._gpuFrameTimeToken) {
  79653. return;
  79654. }
  79655. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  79656. if (time > -1) {
  79657. _this._gpuFrameTimeToken = null;
  79658. _this._gpuFrameTime.fetchNewFrame();
  79659. _this._gpuFrameTime.addCount(time, true);
  79660. }
  79661. });
  79662. }
  79663. else {
  79664. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79665. this._onBeginFrameObserver = null;
  79666. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79667. this._onEndFrameObserver = null;
  79668. }
  79669. },
  79670. enumerable: true,
  79671. configurable: true
  79672. });
  79673. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  79674. /**
  79675. * Gets the perf counter used for shader compilation time
  79676. */
  79677. get: function () {
  79678. return this._shaderCompilationTime;
  79679. },
  79680. enumerable: true,
  79681. configurable: true
  79682. });
  79683. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  79684. /**
  79685. * Gets the shader compilation time capture status
  79686. */
  79687. get: function () {
  79688. return this._captureShaderCompilationTime;
  79689. },
  79690. /**
  79691. * Enable or disable the shader compilation time capture
  79692. */
  79693. set: function (value) {
  79694. var _this = this;
  79695. if (value === this._captureShaderCompilationTime) {
  79696. return;
  79697. }
  79698. this._captureShaderCompilationTime = value;
  79699. if (value) {
  79700. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  79701. _this._shaderCompilationTime.fetchNewFrame();
  79702. _this._shaderCompilationTime.beginMonitoring();
  79703. });
  79704. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  79705. _this._shaderCompilationTime.endMonitoring();
  79706. });
  79707. }
  79708. else {
  79709. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79710. this._onBeforeShaderCompilationObserver = null;
  79711. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79712. this._onAfterShaderCompilationObserver = null;
  79713. }
  79714. },
  79715. enumerable: true,
  79716. configurable: true
  79717. });
  79718. EngineInstrumentation.prototype.dispose = function () {
  79719. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  79720. this._onBeginFrameObserver = null;
  79721. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  79722. this._onEndFrameObserver = null;
  79723. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  79724. this._onBeforeShaderCompilationObserver = null;
  79725. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  79726. this._onAfterShaderCompilationObserver = null;
  79727. this.engine = null;
  79728. };
  79729. return EngineInstrumentation;
  79730. }());
  79731. BABYLON.EngineInstrumentation = EngineInstrumentation;
  79732. })(BABYLON || (BABYLON = {}));
  79733. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  79734. var BABYLON;
  79735. (function (BABYLON) {
  79736. /**
  79737. * This class can be used to get instrumentation data from a Babylon engine
  79738. */
  79739. var SceneInstrumentation = /** @class */ (function () {
  79740. function SceneInstrumentation(scene) {
  79741. var _this = this;
  79742. this.scene = scene;
  79743. this._captureActiveMeshesEvaluationTime = false;
  79744. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  79745. this._captureRenderTargetsRenderTime = false;
  79746. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  79747. this._captureFrameTime = false;
  79748. this._frameTime = new BABYLON.PerfCounter();
  79749. this._captureRenderTime = false;
  79750. this._renderTime = new BABYLON.PerfCounter();
  79751. this._captureInterFrameTime = false;
  79752. this._interFrameTime = new BABYLON.PerfCounter();
  79753. this._captureParticlesRenderTime = false;
  79754. this._particlesRenderTime = new BABYLON.PerfCounter();
  79755. this._captureSpritesRenderTime = false;
  79756. this._spritesRenderTime = new BABYLON.PerfCounter();
  79757. this._capturePhysicsTime = false;
  79758. this._physicsTime = new BABYLON.PerfCounter();
  79759. this._captureAnimationsTime = false;
  79760. this._animationsTime = new BABYLON.PerfCounter();
  79761. // Observers
  79762. this._onBeforeActiveMeshesEvaluationObserver = null;
  79763. this._onAfterActiveMeshesEvaluationObserver = null;
  79764. this._onBeforeRenderTargetsRenderObserver = null;
  79765. this._onAfterRenderTargetsRenderObserver = null;
  79766. this._onAfterRenderObserver = null;
  79767. this._onBeforeDrawPhaseObserver = null;
  79768. this._onAfterDrawPhaseObserver = null;
  79769. this._onBeforeAnimationsObserver = null;
  79770. this._onBeforeParticlesRenderingObserver = null;
  79771. this._onAfterParticlesRenderingObserver = null;
  79772. this._onBeforeSpritesRenderingObserver = null;
  79773. this._onAfterSpritesRenderingObserver = null;
  79774. this._onBeforePhysicsObserver = null;
  79775. this._onAfterPhysicsObserver = null;
  79776. this._onAfterAnimationsObserver = null;
  79777. // Before render
  79778. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  79779. if (_this._captureActiveMeshesEvaluationTime) {
  79780. _this._activeMeshesEvaluationTime.fetchNewFrame();
  79781. }
  79782. if (_this._captureRenderTargetsRenderTime) {
  79783. _this._renderTargetsRenderTime.fetchNewFrame();
  79784. }
  79785. if (_this._captureFrameTime) {
  79786. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  79787. _this._frameTime.beginMonitoring();
  79788. }
  79789. if (_this._captureInterFrameTime) {
  79790. _this._interFrameTime.endMonitoring();
  79791. }
  79792. if (_this._captureParticlesRenderTime) {
  79793. _this._particlesRenderTime.fetchNewFrame();
  79794. }
  79795. if (_this._captureSpritesRenderTime) {
  79796. _this._spritesRenderTime.fetchNewFrame();
  79797. }
  79798. if (_this._captureAnimationsTime) {
  79799. _this._animationsTime.beginMonitoring();
  79800. }
  79801. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  79802. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  79803. });
  79804. // After render
  79805. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  79806. if (_this._captureFrameTime) {
  79807. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  79808. _this._frameTime.endMonitoring();
  79809. }
  79810. if (_this._captureRenderTime) {
  79811. _this._renderTime.endMonitoring(false);
  79812. }
  79813. if (_this._captureInterFrameTime) {
  79814. _this._interFrameTime.beginMonitoring();
  79815. }
  79816. });
  79817. }
  79818. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  79819. // Properties
  79820. /**
  79821. * Gets the perf counter used for active meshes evaluation time
  79822. */
  79823. get: function () {
  79824. return this._activeMeshesEvaluationTime;
  79825. },
  79826. enumerable: true,
  79827. configurable: true
  79828. });
  79829. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  79830. /**
  79831. * Gets the active meshes evaluation time capture status
  79832. */
  79833. get: function () {
  79834. return this._captureActiveMeshesEvaluationTime;
  79835. },
  79836. /**
  79837. * Enable or disable the active meshes evaluation time capture
  79838. */
  79839. set: function (value) {
  79840. var _this = this;
  79841. if (value === this._captureActiveMeshesEvaluationTime) {
  79842. return;
  79843. }
  79844. this._captureActiveMeshesEvaluationTime = value;
  79845. if (value) {
  79846. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  79847. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  79848. _this._activeMeshesEvaluationTime.beginMonitoring();
  79849. });
  79850. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  79851. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  79852. _this._activeMeshesEvaluationTime.endMonitoring();
  79853. });
  79854. }
  79855. else {
  79856. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79857. this._onBeforeActiveMeshesEvaluationObserver = null;
  79858. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79859. this._onAfterActiveMeshesEvaluationObserver = null;
  79860. }
  79861. },
  79862. enumerable: true,
  79863. configurable: true
  79864. });
  79865. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  79866. /**
  79867. * Gets the perf counter used for render targets render time
  79868. */
  79869. get: function () {
  79870. return this._renderTargetsRenderTime;
  79871. },
  79872. enumerable: true,
  79873. configurable: true
  79874. });
  79875. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  79876. /**
  79877. * Gets the render targets render time capture status
  79878. */
  79879. get: function () {
  79880. return this._captureRenderTargetsRenderTime;
  79881. },
  79882. /**
  79883. * Enable or disable the render targets render time capture
  79884. */
  79885. set: function (value) {
  79886. var _this = this;
  79887. if (value === this._captureRenderTargetsRenderTime) {
  79888. return;
  79889. }
  79890. this._captureRenderTargetsRenderTime = value;
  79891. if (value) {
  79892. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  79893. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  79894. _this._renderTargetsRenderTime.beginMonitoring();
  79895. });
  79896. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  79897. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  79898. _this._renderTargetsRenderTime.endMonitoring(false);
  79899. });
  79900. }
  79901. else {
  79902. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79903. this._onBeforeRenderTargetsRenderObserver = null;
  79904. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79905. this._onAfterRenderTargetsRenderObserver = null;
  79906. }
  79907. },
  79908. enumerable: true,
  79909. configurable: true
  79910. });
  79911. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  79912. /**
  79913. * Gets the perf counter used for particles render time
  79914. */
  79915. get: function () {
  79916. return this._particlesRenderTime;
  79917. },
  79918. enumerable: true,
  79919. configurable: true
  79920. });
  79921. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  79922. /**
  79923. * Gets the particles render time capture status
  79924. */
  79925. get: function () {
  79926. return this._captureParticlesRenderTime;
  79927. },
  79928. /**
  79929. * Enable or disable the particles render time capture
  79930. */
  79931. set: function (value) {
  79932. var _this = this;
  79933. if (value === this._captureParticlesRenderTime) {
  79934. return;
  79935. }
  79936. this._captureParticlesRenderTime = value;
  79937. if (value) {
  79938. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  79939. BABYLON.Tools.StartPerformanceCounter("Particles");
  79940. _this._particlesRenderTime.beginMonitoring();
  79941. });
  79942. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  79943. BABYLON.Tools.EndPerformanceCounter("Particles");
  79944. _this._particlesRenderTime.endMonitoring(false);
  79945. });
  79946. }
  79947. else {
  79948. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79949. this._onBeforeParticlesRenderingObserver = null;
  79950. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79951. this._onAfterParticlesRenderingObserver = null;
  79952. }
  79953. },
  79954. enumerable: true,
  79955. configurable: true
  79956. });
  79957. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  79958. /**
  79959. * Gets the perf counter used for sprites render time
  79960. */
  79961. get: function () {
  79962. return this._spritesRenderTime;
  79963. },
  79964. enumerable: true,
  79965. configurable: true
  79966. });
  79967. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  79968. /**
  79969. * Gets the sprites render time capture status
  79970. */
  79971. get: function () {
  79972. return this._captureSpritesRenderTime;
  79973. },
  79974. /**
  79975. * Enable or disable the sprites render time capture
  79976. */
  79977. set: function (value) {
  79978. var _this = this;
  79979. if (value === this._captureSpritesRenderTime) {
  79980. return;
  79981. }
  79982. this._captureSpritesRenderTime = value;
  79983. if (value) {
  79984. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  79985. BABYLON.Tools.StartPerformanceCounter("Sprites");
  79986. _this._spritesRenderTime.beginMonitoring();
  79987. });
  79988. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  79989. BABYLON.Tools.EndPerformanceCounter("Sprites");
  79990. _this._spritesRenderTime.endMonitoring(false);
  79991. });
  79992. }
  79993. else {
  79994. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79995. this._onBeforeSpritesRenderingObserver = null;
  79996. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79997. this._onAfterSpritesRenderingObserver = null;
  79998. }
  79999. },
  80000. enumerable: true,
  80001. configurable: true
  80002. });
  80003. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  80004. /**
  80005. * Gets the perf counter used for physics time
  80006. */
  80007. get: function () {
  80008. return this._physicsTime;
  80009. },
  80010. enumerable: true,
  80011. configurable: true
  80012. });
  80013. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  80014. /**
  80015. * Gets the physics time capture status
  80016. */
  80017. get: function () {
  80018. return this._capturePhysicsTime;
  80019. },
  80020. /**
  80021. * Enable or disable the physics time capture
  80022. */
  80023. set: function (value) {
  80024. var _this = this;
  80025. if (value === this._capturePhysicsTime) {
  80026. return;
  80027. }
  80028. this._capturePhysicsTime = value;
  80029. if (value) {
  80030. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  80031. BABYLON.Tools.StartPerformanceCounter("Physics");
  80032. _this._physicsTime.beginMonitoring();
  80033. });
  80034. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  80035. BABYLON.Tools.EndPerformanceCounter("Physics");
  80036. _this._physicsTime.endMonitoring();
  80037. });
  80038. }
  80039. else {
  80040. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80041. this._onBeforePhysicsObserver = null;
  80042. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80043. this._onAfterPhysicsObserver = null;
  80044. }
  80045. },
  80046. enumerable: true,
  80047. configurable: true
  80048. });
  80049. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  80050. /**
  80051. * Gets the perf counter used for animations time
  80052. */
  80053. get: function () {
  80054. return this._animationsTime;
  80055. },
  80056. enumerable: true,
  80057. configurable: true
  80058. });
  80059. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  80060. /**
  80061. * Gets the animations time capture status
  80062. */
  80063. get: function () {
  80064. return this._captureAnimationsTime;
  80065. },
  80066. /**
  80067. * Enable or disable the animations time capture
  80068. */
  80069. set: function (value) {
  80070. var _this = this;
  80071. if (value === this._captureAnimationsTime) {
  80072. return;
  80073. }
  80074. this._captureAnimationsTime = value;
  80075. if (value) {
  80076. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  80077. _this._animationsTime.endMonitoring();
  80078. });
  80079. }
  80080. else {
  80081. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80082. this._onAfterAnimationsObserver = null;
  80083. }
  80084. },
  80085. enumerable: true,
  80086. configurable: true
  80087. });
  80088. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  80089. /**
  80090. * Gets the perf counter used for frame time capture
  80091. */
  80092. get: function () {
  80093. return this._frameTime;
  80094. },
  80095. enumerable: true,
  80096. configurable: true
  80097. });
  80098. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  80099. /**
  80100. * Gets the frame time capture status
  80101. */
  80102. get: function () {
  80103. return this._captureFrameTime;
  80104. },
  80105. /**
  80106. * Enable or disable the frame time capture
  80107. */
  80108. set: function (value) {
  80109. this._captureFrameTime = value;
  80110. },
  80111. enumerable: true,
  80112. configurable: true
  80113. });
  80114. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  80115. /**
  80116. * Gets the perf counter used for inter-frames time capture
  80117. */
  80118. get: function () {
  80119. return this._interFrameTime;
  80120. },
  80121. enumerable: true,
  80122. configurable: true
  80123. });
  80124. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  80125. /**
  80126. * Gets the inter-frames time capture status
  80127. */
  80128. get: function () {
  80129. return this._captureInterFrameTime;
  80130. },
  80131. /**
  80132. * Enable or disable the inter-frames time capture
  80133. */
  80134. set: function (value) {
  80135. this._captureInterFrameTime = value;
  80136. },
  80137. enumerable: true,
  80138. configurable: true
  80139. });
  80140. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  80141. /**
  80142. * Gets the perf counter used for render time capture
  80143. */
  80144. get: function () {
  80145. return this._renderTime;
  80146. },
  80147. enumerable: true,
  80148. configurable: true
  80149. });
  80150. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  80151. /**
  80152. * Gets the render time capture status
  80153. */
  80154. get: function () {
  80155. return this._captureRenderTime;
  80156. },
  80157. /**
  80158. * Enable or disable the render time capture
  80159. */
  80160. set: function (value) {
  80161. var _this = this;
  80162. if (value === this._captureRenderTime) {
  80163. return;
  80164. }
  80165. this._captureRenderTime = value;
  80166. if (value) {
  80167. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  80168. _this._renderTime.beginMonitoring();
  80169. BABYLON.Tools.StartPerformanceCounter("Main render");
  80170. });
  80171. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  80172. _this._renderTime.endMonitoring(false);
  80173. BABYLON.Tools.EndPerformanceCounter("Main render");
  80174. });
  80175. }
  80176. else {
  80177. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80178. this._onBeforeDrawPhaseObserver = null;
  80179. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80180. this._onAfterDrawPhaseObserver = null;
  80181. }
  80182. },
  80183. enumerable: true,
  80184. configurable: true
  80185. });
  80186. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  80187. /**
  80188. * Gets the perf counter used for draw calls
  80189. */
  80190. get: function () {
  80191. return this.scene.getEngine()._drawCalls;
  80192. },
  80193. enumerable: true,
  80194. configurable: true
  80195. });
  80196. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  80197. /**
  80198. * Gets the perf counter used for texture collisions
  80199. */
  80200. get: function () {
  80201. return this.scene.getEngine()._textureCollisions;
  80202. },
  80203. enumerable: true,
  80204. configurable: true
  80205. });
  80206. SceneInstrumentation.prototype.dispose = function () {
  80207. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  80208. this._onAfterRenderObserver = null;
  80209. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  80210. this._onBeforeActiveMeshesEvaluationObserver = null;
  80211. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  80212. this._onAfterActiveMeshesEvaluationObserver = null;
  80213. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  80214. this._onBeforeRenderTargetsRenderObserver = null;
  80215. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  80216. this._onAfterRenderTargetsRenderObserver = null;
  80217. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  80218. this._onBeforeAnimationsObserver = null;
  80219. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  80220. this._onBeforeParticlesRenderingObserver = null;
  80221. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  80222. this._onAfterParticlesRenderingObserver = null;
  80223. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  80224. this._onBeforeSpritesRenderingObserver = null;
  80225. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  80226. this._onAfterSpritesRenderingObserver = null;
  80227. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  80228. this._onBeforeDrawPhaseObserver = null;
  80229. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  80230. this._onAfterDrawPhaseObserver = null;
  80231. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  80232. this._onBeforePhysicsObserver = null;
  80233. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  80234. this._onAfterPhysicsObserver = null;
  80235. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  80236. this._onAfterAnimationsObserver = null;
  80237. this.scene = null;
  80238. };
  80239. return SceneInstrumentation;
  80240. }());
  80241. BABYLON.SceneInstrumentation = SceneInstrumentation;
  80242. })(BABYLON || (BABYLON = {}));
  80243. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  80244. var BABYLON;
  80245. (function (BABYLON) {
  80246. var _TimeToken = /** @class */ (function () {
  80247. function _TimeToken() {
  80248. this._timeElapsedQueryEnded = false;
  80249. }
  80250. return _TimeToken;
  80251. }());
  80252. BABYLON._TimeToken = _TimeToken;
  80253. })(BABYLON || (BABYLON = {}));
  80254. //# sourceMappingURL=babylon.timeToken.js.map
  80255. var BABYLON;
  80256. (function (BABYLON) {
  80257. /**
  80258. * Background material defines definition.
  80259. */
  80260. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  80261. __extends(BackgroundMaterialDefines, _super);
  80262. /**
  80263. * Constructor of the defines.
  80264. */
  80265. function BackgroundMaterialDefines() {
  80266. var _this = _super.call(this) || this;
  80267. /**
  80268. * True if the diffuse texture is in use.
  80269. */
  80270. _this.DIFFUSE = false;
  80271. /**
  80272. * The direct UV channel to use.
  80273. */
  80274. _this.DIFFUSEDIRECTUV = 0;
  80275. /**
  80276. * True if the diffuse texture is in gamma space.
  80277. */
  80278. _this.GAMMADIFFUSE = false;
  80279. /**
  80280. * True if the diffuse texture has opacity in the alpha channel.
  80281. */
  80282. _this.DIFFUSEHASALPHA = false;
  80283. /**
  80284. * True if you want the material to fade to transparent at grazing angle.
  80285. */
  80286. _this.OPACITYFRESNEL = false;
  80287. /**
  80288. * True if an extra blur needs to be added in the reflection.
  80289. */
  80290. _this.REFLECTIONBLUR = false;
  80291. /**
  80292. * True if you want the material to fade to reflection at grazing angle.
  80293. */
  80294. _this.REFLECTIONFRESNEL = false;
  80295. /**
  80296. * True if you want the material to falloff as far as you move away from the scene center.
  80297. */
  80298. _this.REFLECTIONFALLOFF = false;
  80299. /**
  80300. * False if the current Webgl implementation does not support the texture lod extension.
  80301. */
  80302. _this.TEXTURELODSUPPORT = false;
  80303. /**
  80304. * True to ensure the data are premultiplied.
  80305. */
  80306. _this.PREMULTIPLYALPHA = false;
  80307. /**
  80308. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  80309. */
  80310. _this.USERGBCOLOR = false;
  80311. /**
  80312. * True to add noise in order to reduce the banding effect.
  80313. */
  80314. _this.NOISE = false;
  80315. // Image Processing Configuration.
  80316. _this.IMAGEPROCESSING = false;
  80317. _this.VIGNETTE = false;
  80318. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  80319. _this.VIGNETTEBLENDMODEOPAQUE = false;
  80320. _this.TONEMAPPING = false;
  80321. _this.CONTRAST = false;
  80322. _this.COLORCURVES = false;
  80323. _this.COLORGRADING = false;
  80324. _this.COLORGRADING3D = false;
  80325. _this.SAMPLER3DGREENDEPTH = false;
  80326. _this.SAMPLER3DBGRMAP = false;
  80327. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  80328. _this.EXPOSURE = false;
  80329. // Reflection.
  80330. _this.REFLECTION = false;
  80331. _this.REFLECTIONMAP_3D = false;
  80332. _this.REFLECTIONMAP_SPHERICAL = false;
  80333. _this.REFLECTIONMAP_PLANAR = false;
  80334. _this.REFLECTIONMAP_CUBIC = false;
  80335. _this.REFLECTIONMAP_PROJECTION = false;
  80336. _this.REFLECTIONMAP_SKYBOX = false;
  80337. _this.REFLECTIONMAP_EXPLICIT = false;
  80338. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80339. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80340. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80341. _this.INVERTCUBICMAP = false;
  80342. _this.REFLECTIONMAP_OPPOSITEZ = false;
  80343. _this.LODINREFLECTIONALPHA = false;
  80344. _this.GAMMAREFLECTION = false;
  80345. // Default BJS.
  80346. _this.MAINUV1 = false;
  80347. _this.MAINUV2 = false;
  80348. _this.UV1 = false;
  80349. _this.UV2 = false;
  80350. _this.CLIPPLANE = false;
  80351. _this.POINTSIZE = false;
  80352. _this.FOG = false;
  80353. _this.NORMAL = false;
  80354. _this.NUM_BONE_INFLUENCERS = 0;
  80355. _this.BonesPerMesh = 0;
  80356. _this.INSTANCES = false;
  80357. _this.SHADOWFLOAT = false;
  80358. _this.rebuild();
  80359. return _this;
  80360. }
  80361. return BackgroundMaterialDefines;
  80362. }(BABYLON.MaterialDefines));
  80363. /**
  80364. * Background material used to create an efficient environement around your scene.
  80365. */
  80366. var BackgroundMaterial = /** @class */ (function (_super) {
  80367. __extends(BackgroundMaterial, _super);
  80368. /**
  80369. * constructor
  80370. * @param name The name of the material
  80371. * @param scene The scene to add the material to
  80372. */
  80373. function BackgroundMaterial(name, scene) {
  80374. var _this = _super.call(this, name, scene) || this;
  80375. _this.primaryColor = BABYLON.Color3.White();
  80376. _this.primaryLevel = 1;
  80377. _this.secondaryColor = BABYLON.Color3.Gray();
  80378. _this.secondaryLevel = 1;
  80379. _this.tertiaryColor = BABYLON.Color3.Black();
  80380. _this.tertiaryLevel = 1;
  80381. _this.reflectionTexture = null;
  80382. _this.reflectionBlur = 0;
  80383. _this.diffuseTexture = null;
  80384. /**
  80385. * Specify the list of lights casting shadow on the material.
  80386. * All scene shadow lights will be included if null.
  80387. */
  80388. _this._shadowLights = null;
  80389. _this.shadowLights = null;
  80390. _this.shadowBlurScale = 1;
  80391. _this.shadowLevel = 0;
  80392. _this.sceneCenter = BABYLON.Vector3.Zero();
  80393. _this.opacityFresnel = true;
  80394. _this.reflectionFresnel = false;
  80395. _this.reflectionFalloffDistance = 0.0;
  80396. _this.reflectionAmount = 1.0;
  80397. _this.reflectionReflectance0 = 0.05;
  80398. _this.reflectionReflectance90 = 0.5;
  80399. _this.useRGBColor = true;
  80400. _this.enableNoise = false;
  80401. /**
  80402. * Number of Simultaneous lights allowed on the material.
  80403. */
  80404. _this._maxSimultaneousLights = 4;
  80405. _this.maxSimultaneousLights = 4;
  80406. /**
  80407. * Keep track of the image processing observer to allow dispose and replace.
  80408. */
  80409. _this._imageProcessingObserver = null;
  80410. // Temp values kept as cache in the material.
  80411. _this._renderTargets = new BABYLON.SmartArray(16);
  80412. _this._reflectionControls = BABYLON.Vector4.Zero();
  80413. // Setup the default processing configuration to the scene.
  80414. _this._attachImageProcessingConfiguration(null);
  80415. _this.getRenderTargetTextures = function () {
  80416. _this._renderTargets.reset();
  80417. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  80418. _this._renderTargets.push(_this._diffuseTexture);
  80419. }
  80420. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  80421. _this._renderTargets.push(_this._reflectionTexture);
  80422. }
  80423. return _this._renderTargets;
  80424. };
  80425. return _this;
  80426. }
  80427. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  80428. /**
  80429. * Sets the reflection reflectance fresnel values according to the default standard
  80430. * empirically know to work well :-)
  80431. */
  80432. set: function (value) {
  80433. var reflectionWeight = value;
  80434. if (reflectionWeight < 0.5) {
  80435. reflectionWeight = reflectionWeight * 2.0;
  80436. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  80437. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  80438. }
  80439. else {
  80440. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  80441. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  80442. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  80443. }
  80444. },
  80445. enumerable: true,
  80446. configurable: true
  80447. });
  80448. /**
  80449. * Attaches a new image processing configuration to the PBR Material.
  80450. * @param configuration (if null the scene configuration will be use)
  80451. */
  80452. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  80453. var _this = this;
  80454. if (configuration === this._imageProcessingConfiguration) {
  80455. return;
  80456. }
  80457. // Detaches observer.
  80458. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80459. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80460. }
  80461. // Pick the scene configuration if needed.
  80462. if (!configuration) {
  80463. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  80464. }
  80465. else {
  80466. this._imageProcessingConfiguration = configuration;
  80467. }
  80468. // Attaches observer.
  80469. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  80470. _this._markAllSubMeshesAsImageProcessingDirty();
  80471. });
  80472. };
  80473. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  80474. /**
  80475. * Gets the image processing configuration used either in this material.
  80476. */
  80477. get: function () {
  80478. return this._imageProcessingConfiguration;
  80479. },
  80480. /**
  80481. * Sets the Default image processing configuration used either in the this material.
  80482. *
  80483. * If sets to null, the scene one is in use.
  80484. */
  80485. set: function (value) {
  80486. this._attachImageProcessingConfiguration(value);
  80487. // Ensure the effect will be rebuilt.
  80488. this._markAllSubMeshesAsTexturesDirty();
  80489. },
  80490. enumerable: true,
  80491. configurable: true
  80492. });
  80493. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  80494. /**
  80495. * Gets wether the color curves effect is enabled.
  80496. */
  80497. get: function () {
  80498. return this.imageProcessingConfiguration.colorCurvesEnabled;
  80499. },
  80500. /**
  80501. * Sets wether the color curves effect is enabled.
  80502. */
  80503. set: function (value) {
  80504. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  80505. },
  80506. enumerable: true,
  80507. configurable: true
  80508. });
  80509. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  80510. /**
  80511. * Gets wether the color grading effect is enabled.
  80512. */
  80513. get: function () {
  80514. return this.imageProcessingConfiguration.colorGradingEnabled;
  80515. },
  80516. /**
  80517. * Gets wether the color grading effect is enabled.
  80518. */
  80519. set: function (value) {
  80520. this.imageProcessingConfiguration.colorGradingEnabled = value;
  80521. },
  80522. enumerable: true,
  80523. configurable: true
  80524. });
  80525. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  80526. /**
  80527. * Gets wether tonemapping is enabled or not.
  80528. */
  80529. get: function () {
  80530. return this._imageProcessingConfiguration.toneMappingEnabled;
  80531. },
  80532. /**
  80533. * Sets wether tonemapping is enabled or not
  80534. */
  80535. set: function (value) {
  80536. this._imageProcessingConfiguration.toneMappingEnabled = value;
  80537. },
  80538. enumerable: true,
  80539. configurable: true
  80540. });
  80541. ;
  80542. ;
  80543. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  80544. /**
  80545. * The camera exposure used on this material.
  80546. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80547. * This corresponds to a photographic exposure.
  80548. */
  80549. get: function () {
  80550. return this._imageProcessingConfiguration.exposure;
  80551. },
  80552. /**
  80553. * The camera exposure used on this material.
  80554. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  80555. * This corresponds to a photographic exposure.
  80556. */
  80557. set: function (value) {
  80558. this._imageProcessingConfiguration.exposure = value;
  80559. },
  80560. enumerable: true,
  80561. configurable: true
  80562. });
  80563. ;
  80564. ;
  80565. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  80566. /**
  80567. * Gets The camera contrast used on this material.
  80568. */
  80569. get: function () {
  80570. return this._imageProcessingConfiguration.contrast;
  80571. },
  80572. /**
  80573. * Sets The camera contrast used on this material.
  80574. */
  80575. set: function (value) {
  80576. this._imageProcessingConfiguration.contrast = value;
  80577. },
  80578. enumerable: true,
  80579. configurable: true
  80580. });
  80581. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  80582. /**
  80583. * Gets the Color Grading 2D Lookup Texture.
  80584. */
  80585. get: function () {
  80586. return this._imageProcessingConfiguration.colorGradingTexture;
  80587. },
  80588. /**
  80589. * Sets the Color Grading 2D Lookup Texture.
  80590. */
  80591. set: function (value) {
  80592. this.imageProcessingConfiguration.colorGradingTexture = value;
  80593. },
  80594. enumerable: true,
  80595. configurable: true
  80596. });
  80597. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  80598. /**
  80599. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80600. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80601. * 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;
  80602. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80603. */
  80604. get: function () {
  80605. return this.imageProcessingConfiguration.colorCurves;
  80606. },
  80607. /**
  80608. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  80609. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  80610. * 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;
  80611. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  80612. */
  80613. set: function (value) {
  80614. this.imageProcessingConfiguration.colorCurves = value;
  80615. },
  80616. enumerable: true,
  80617. configurable: true
  80618. });
  80619. /**
  80620. * The entire material has been created in order to prevent overdraw.
  80621. * @returns false
  80622. */
  80623. BackgroundMaterial.prototype.needAlphaTesting = function () {
  80624. return true;
  80625. };
  80626. /**
  80627. * The entire material has been created in order to prevent overdraw.
  80628. * @returns true if blending is enable
  80629. */
  80630. BackgroundMaterial.prototype.needAlphaBlending = function () {
  80631. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  80632. };
  80633. /**
  80634. * Checks wether the material is ready to be rendered for a given mesh.
  80635. * @param mesh The mesh to render
  80636. * @param subMesh The submesh to check against
  80637. * @param useInstances Specify wether or not the material is used with instances
  80638. */
  80639. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  80640. var _this = this;
  80641. if (useInstances === void 0) { useInstances = false; }
  80642. if (subMesh.effect && this.isFrozen) {
  80643. if (this._wasPreviouslyReady) {
  80644. return true;
  80645. }
  80646. }
  80647. if (!subMesh._materialDefines) {
  80648. subMesh._materialDefines = new BackgroundMaterialDefines();
  80649. }
  80650. var scene = this.getScene();
  80651. var defines = subMesh._materialDefines;
  80652. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  80653. if (defines._renderId === scene.getRenderId()) {
  80654. return true;
  80655. }
  80656. }
  80657. var engine = scene.getEngine();
  80658. // Lights
  80659. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  80660. defines._needNormals = true;
  80661. // Textures
  80662. if (defines._areTexturesDirty) {
  80663. defines._needUVs = false;
  80664. if (scene.texturesEnabled) {
  80665. if (scene.getEngine().getCaps().textureLOD) {
  80666. defines.TEXTURELODSUPPORT = true;
  80667. }
  80668. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80669. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  80670. return false;
  80671. }
  80672. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  80673. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  80674. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  80675. defines.OPACITYFRESNEL = this._opacityFresnel;
  80676. }
  80677. else {
  80678. defines.DIFFUSE = false;
  80679. defines.DIFFUSEHASALPHA = false;
  80680. defines.GAMMADIFFUSE = false;
  80681. defines.OPACITYFRESNEL = false;
  80682. }
  80683. var reflectionTexture = this._reflectionTexture;
  80684. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80685. if (!reflectionTexture.isReadyOrNotBlocking()) {
  80686. return false;
  80687. }
  80688. defines.REFLECTION = true;
  80689. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  80690. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  80691. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  80692. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  80693. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  80694. defines.INVERTCUBICMAP = true;
  80695. }
  80696. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  80697. switch (reflectionTexture.coordinatesMode) {
  80698. case BABYLON.Texture.CUBIC_MODE:
  80699. case BABYLON.Texture.INVCUBIC_MODE:
  80700. defines.REFLECTIONMAP_CUBIC = true;
  80701. break;
  80702. case BABYLON.Texture.EXPLICIT_MODE:
  80703. defines.REFLECTIONMAP_EXPLICIT = true;
  80704. break;
  80705. case BABYLON.Texture.PLANAR_MODE:
  80706. defines.REFLECTIONMAP_PLANAR = true;
  80707. break;
  80708. case BABYLON.Texture.PROJECTION_MODE:
  80709. defines.REFLECTIONMAP_PROJECTION = true;
  80710. break;
  80711. case BABYLON.Texture.SKYBOX_MODE:
  80712. defines.REFLECTIONMAP_SKYBOX = true;
  80713. break;
  80714. case BABYLON.Texture.SPHERICAL_MODE:
  80715. defines.REFLECTIONMAP_SPHERICAL = true;
  80716. break;
  80717. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  80718. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  80719. break;
  80720. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  80721. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  80722. break;
  80723. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  80724. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  80725. break;
  80726. }
  80727. if (this.reflectionFresnel) {
  80728. defines.REFLECTIONFRESNEL = true;
  80729. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  80730. this._reflectionControls.x = this.reflectionAmount;
  80731. this._reflectionControls.y = this.reflectionReflectance0;
  80732. this._reflectionControls.z = this.reflectionReflectance90;
  80733. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  80734. }
  80735. else {
  80736. defines.REFLECTIONFRESNEL = false;
  80737. defines.REFLECTIONFALLOFF = false;
  80738. }
  80739. }
  80740. else {
  80741. defines.REFLECTION = false;
  80742. defines.REFLECTIONFALLOFF = false;
  80743. defines.REFLECTIONBLUR = false;
  80744. defines.REFLECTIONMAP_3D = false;
  80745. defines.REFLECTIONMAP_SPHERICAL = false;
  80746. defines.REFLECTIONMAP_PLANAR = false;
  80747. defines.REFLECTIONMAP_CUBIC = false;
  80748. defines.REFLECTIONMAP_PROJECTION = false;
  80749. defines.REFLECTIONMAP_SKYBOX = false;
  80750. defines.REFLECTIONMAP_EXPLICIT = false;
  80751. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  80752. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  80753. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  80754. defines.INVERTCUBICMAP = false;
  80755. defines.REFLECTIONMAP_OPPOSITEZ = false;
  80756. defines.LODINREFLECTIONALPHA = false;
  80757. defines.GAMMAREFLECTION = false;
  80758. }
  80759. }
  80760. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  80761. defines.USERGBCOLOR = this._useRGBColor;
  80762. defines.NOISE = this._enableNoise;
  80763. }
  80764. if (defines._areImageProcessingDirty) {
  80765. if (!this._imageProcessingConfiguration.isReady()) {
  80766. return false;
  80767. }
  80768. this._imageProcessingConfiguration.prepareDefines(defines);
  80769. }
  80770. // Misc.
  80771. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  80772. // Values that need to be evaluated on every frame
  80773. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._shouldTurnAlphaTestOn(mesh));
  80774. // Attribs
  80775. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  80776. if (mesh) {
  80777. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80778. mesh.createNormals(true);
  80779. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  80780. }
  80781. }
  80782. }
  80783. // Get correct effect
  80784. if (defines.isDirty) {
  80785. defines.markAsProcessed();
  80786. scene.resetCachedMaterial();
  80787. // Fallbacks
  80788. var fallbacks = new BABYLON.EffectFallbacks();
  80789. if (defines.FOG) {
  80790. fallbacks.addFallback(0, "FOG");
  80791. }
  80792. if (defines.POINTSIZE) {
  80793. fallbacks.addFallback(1, "POINTSIZE");
  80794. }
  80795. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  80796. if (defines.NUM_BONE_INFLUENCERS > 0) {
  80797. fallbacks.addCPUSkinningFallback(0, mesh);
  80798. }
  80799. //Attributes
  80800. var attribs = [BABYLON.VertexBuffer.PositionKind];
  80801. if (defines.NORMAL) {
  80802. attribs.push(BABYLON.VertexBuffer.NormalKind);
  80803. }
  80804. if (defines.UV1) {
  80805. attribs.push(BABYLON.VertexBuffer.UVKind);
  80806. }
  80807. if (defines.UV2) {
  80808. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  80809. }
  80810. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  80811. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  80812. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  80813. "vFogInfos", "vFogColor", "pointSize",
  80814. "vClipPlane", "mBones",
  80815. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  80816. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  80817. "shadowLevel", "alpha",
  80818. "vBackgroundCenter", "vReflectionControl",
  80819. "vDiffuseInfos", "diffuseMatrix",
  80820. ];
  80821. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  80822. var uniformBuffers = ["Material", "Scene"];
  80823. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  80824. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  80825. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  80826. uniformsNames: uniforms,
  80827. uniformBuffersNames: uniformBuffers,
  80828. samplers: samplers,
  80829. defines: defines,
  80830. maxSimultaneousLights: this._maxSimultaneousLights
  80831. });
  80832. var onCompiled = function (effect) {
  80833. if (_this.onCompiled) {
  80834. _this.onCompiled(effect);
  80835. }
  80836. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  80837. };
  80838. var join = defines.toString();
  80839. subMesh.setEffect(scene.getEngine().createEffect("background", {
  80840. attributes: attribs,
  80841. uniformsNames: uniforms,
  80842. uniformBuffersNames: uniformBuffers,
  80843. samplers: samplers,
  80844. defines: join,
  80845. fallbacks: fallbacks,
  80846. onCompiled: onCompiled,
  80847. onError: this.onError,
  80848. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  80849. }, engine), defines);
  80850. this.buildUniformLayout();
  80851. }
  80852. if (!subMesh.effect || !subMesh.effect.isReady()) {
  80853. return false;
  80854. }
  80855. defines._renderId = scene.getRenderId();
  80856. this._wasPreviouslyReady = true;
  80857. return true;
  80858. };
  80859. /**
  80860. * Build the uniform buffer used in the material.
  80861. */
  80862. BackgroundMaterial.prototype.buildUniformLayout = function () {
  80863. // Order is important !
  80864. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  80865. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  80866. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  80867. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  80868. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  80869. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  80870. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  80871. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  80872. this._uniformBuffer.addUniform("pointSize", 1);
  80873. this._uniformBuffer.addUniform("shadowLevel", 1);
  80874. this._uniformBuffer.addUniform("alpha", 1);
  80875. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  80876. this._uniformBuffer.addUniform("vReflectionControl", 4);
  80877. this._uniformBuffer.create();
  80878. };
  80879. /**
  80880. * Unbind the material.
  80881. */
  80882. BackgroundMaterial.prototype.unbind = function () {
  80883. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  80884. this._uniformBuffer.setTexture("diffuseSampler", null);
  80885. }
  80886. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  80887. this._uniformBuffer.setTexture("reflectionSampler", null);
  80888. }
  80889. _super.prototype.unbind.call(this);
  80890. };
  80891. /**
  80892. * Bind only the world matrix to the material.
  80893. * @param world The world matrix to bind.
  80894. */
  80895. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  80896. this._activeEffect.setMatrix("world", world);
  80897. };
  80898. /**
  80899. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  80900. * @param world The world matrix to bind.
  80901. * @param subMesh The submesh to bind for.
  80902. */
  80903. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  80904. var scene = this.getScene();
  80905. var defines = subMesh._materialDefines;
  80906. if (!defines) {
  80907. return;
  80908. }
  80909. var effect = subMesh.effect;
  80910. if (!effect) {
  80911. return;
  80912. }
  80913. this._activeEffect = effect;
  80914. // Matrices
  80915. this.bindOnlyWorldMatrix(world);
  80916. // Bones
  80917. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  80918. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  80919. if (mustRebind) {
  80920. this._uniformBuffer.bindToEffect(effect, "Material");
  80921. this.bindViewProjection(effect);
  80922. var reflectionTexture = this._reflectionTexture;
  80923. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  80924. // Texture uniforms
  80925. if (scene.texturesEnabled) {
  80926. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80927. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  80928. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  80929. }
  80930. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80931. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  80932. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  80933. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  80934. }
  80935. }
  80936. if (this.shadowLevel > 0) {
  80937. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  80938. }
  80939. this._uniformBuffer.updateFloat("alpha", this.alpha);
  80940. // Point size
  80941. if (this.pointsCloud) {
  80942. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  80943. }
  80944. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  80945. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  80946. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  80947. }
  80948. // Textures
  80949. if (scene.texturesEnabled) {
  80950. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  80951. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  80952. }
  80953. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80954. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  80955. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80956. }
  80957. else if (!defines.REFLECTIONBLUR) {
  80958. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80959. }
  80960. else {
  80961. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  80962. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  80963. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  80964. }
  80965. if (defines.REFLECTIONFRESNEL) {
  80966. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  80967. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  80968. }
  80969. }
  80970. }
  80971. // Clip plane
  80972. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  80973. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  80974. }
  80975. if (mustRebind || !this.isFrozen) {
  80976. if (scene.lightsEnabled) {
  80977. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  80978. }
  80979. // View
  80980. this.bindView(effect);
  80981. // Fog
  80982. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  80983. // image processing
  80984. this._imageProcessingConfiguration.bind(this._activeEffect);
  80985. }
  80986. this._uniformBuffer.update();
  80987. this._afterBind(mesh);
  80988. };
  80989. /**
  80990. * Dispose the material.
  80991. * @forceDisposeEffect Force disposal of the associated effect.
  80992. * @forceDisposeTextures Force disposal of the associated textures.
  80993. */
  80994. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80995. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  80996. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  80997. if (forceDisposeTextures) {
  80998. if (this.diffuseTexture) {
  80999. this.diffuseTexture.dispose();
  81000. }
  81001. if (this.reflectionTexture) {
  81002. this.reflectionTexture.dispose();
  81003. }
  81004. }
  81005. this._renderTargets.dispose();
  81006. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  81007. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  81008. }
  81009. _super.prototype.dispose.call(this, forceDisposeEffect);
  81010. };
  81011. /**
  81012. * Clones the material.
  81013. * @name The cloned name.
  81014. * @returns The cloned material.
  81015. */
  81016. BackgroundMaterial.prototype.clone = function (name) {
  81017. var _this = this;
  81018. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  81019. };
  81020. /**
  81021. * Serializes the current material to its JSON representation.
  81022. * @returns The JSON representation.
  81023. */
  81024. BackgroundMaterial.prototype.serialize = function () {
  81025. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81026. serializationObject.customType = "BABYLON.BackgroundMaterial";
  81027. return serializationObject;
  81028. };
  81029. /**
  81030. * Gets the class name of the material
  81031. * @returns "BackgroundMaterial"
  81032. */
  81033. BackgroundMaterial.prototype.getClassName = function () {
  81034. return "BackgroundMaterial";
  81035. };
  81036. /**
  81037. * Parse a JSON input to create back a background material.
  81038. * @param source
  81039. * @param scene
  81040. * @param rootUrl
  81041. * @returns the instantiated BackgroundMaterial.
  81042. */
  81043. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  81044. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  81045. };
  81046. /**
  81047. * Standard reflectance value at parallel view angle.
  81048. */
  81049. BackgroundMaterial.standardReflectance0 = 0.05;
  81050. /**
  81051. * Standard reflectance value at grazing angle.
  81052. */
  81053. BackgroundMaterial.standardReflectance90 = 0.5;
  81054. __decorate([
  81055. BABYLON.serializeAsColor3()
  81056. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  81057. __decorate([
  81058. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81059. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  81060. __decorate([
  81061. BABYLON.serialize()
  81062. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  81063. __decorate([
  81064. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81065. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  81066. __decorate([
  81067. BABYLON.serializeAsColor3()
  81068. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  81069. __decorate([
  81070. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81071. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  81072. __decorate([
  81073. BABYLON.serialize()
  81074. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  81075. __decorate([
  81076. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81077. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  81078. __decorate([
  81079. BABYLON.serializeAsColor3()
  81080. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  81081. __decorate([
  81082. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81083. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  81084. __decorate([
  81085. BABYLON.serialize()
  81086. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  81087. __decorate([
  81088. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  81089. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  81090. __decorate([
  81091. BABYLON.serializeAsTexture()
  81092. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  81093. __decorate([
  81094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81095. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  81096. __decorate([
  81097. BABYLON.serialize()
  81098. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  81099. __decorate([
  81100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81101. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  81102. __decorate([
  81103. BABYLON.serializeAsTexture()
  81104. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  81105. __decorate([
  81106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81107. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  81108. __decorate([
  81109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81110. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  81111. __decorate([
  81112. BABYLON.serialize()
  81113. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  81114. __decorate([
  81115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81116. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  81117. __decorate([
  81118. BABYLON.serialize()
  81119. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  81120. __decorate([
  81121. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81122. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  81123. __decorate([
  81124. BABYLON.serializeAsVector3()
  81125. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  81126. __decorate([
  81127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81128. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  81129. __decorate([
  81130. BABYLON.serialize()
  81131. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  81132. __decorate([
  81133. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81134. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  81135. __decorate([
  81136. BABYLON.serialize()
  81137. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  81138. __decorate([
  81139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81140. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  81141. __decorate([
  81142. BABYLON.serialize()
  81143. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  81144. __decorate([
  81145. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81146. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  81147. __decorate([
  81148. BABYLON.serialize()
  81149. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  81150. __decorate([
  81151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81152. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  81153. __decorate([
  81154. BABYLON.serialize()
  81155. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  81156. __decorate([
  81157. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81158. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  81159. __decorate([
  81160. BABYLON.serialize()
  81161. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  81162. __decorate([
  81163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81164. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  81165. __decorate([
  81166. BABYLON.serialize()
  81167. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  81168. __decorate([
  81169. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81170. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  81171. __decorate([
  81172. BABYLON.serialize()
  81173. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  81174. __decorate([
  81175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81176. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  81177. __decorate([
  81178. BABYLON.serialize()
  81179. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  81180. __decorate([
  81181. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  81182. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  81183. __decorate([
  81184. BABYLON.serializeAsImageProcessingConfiguration()
  81185. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  81186. return BackgroundMaterial;
  81187. }(BABYLON.PushMaterial));
  81188. BABYLON.BackgroundMaterial = BackgroundMaterial;
  81189. })(BABYLON || (BABYLON = {}));
  81190. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  81191. var __assign = (this && this.__assign) || Object.assign || function(t) {
  81192. for (var s, i = 1, n = arguments.length; i < n; i++) {
  81193. s = arguments[i];
  81194. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  81195. t[p] = s[p];
  81196. }
  81197. return t;
  81198. };
  81199. var BABYLON;
  81200. (function (BABYLON) {
  81201. /**
  81202. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  81203. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  81204. * It also helps with the default setup of your imageProcessing configuration.
  81205. */
  81206. var EnvironmentHelper = /** @class */ (function () {
  81207. /**
  81208. * constructor
  81209. * @param options
  81210. * @param scene The scene to add the material to
  81211. */
  81212. function EnvironmentHelper(options, scene) {
  81213. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  81214. this._scene = scene;
  81215. this._setupBackground();
  81216. this._setupImageProcessing();
  81217. }
  81218. /**
  81219. * Creates the default options for the helper.
  81220. */
  81221. EnvironmentHelper._getDefaultOptions = function () {
  81222. return {
  81223. createGround: true,
  81224. groundSize: 15,
  81225. groundTexture: this._groundTextureCDNUrl,
  81226. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81227. groundOpacity: 0.9,
  81228. enableGroundShadow: true,
  81229. groundShadowLevel: 0.5,
  81230. enableGroundMirror: false,
  81231. groundMirrorSizeRatio: 0.3,
  81232. groundMirrorBlurKernel: 64,
  81233. groundMirrorAmount: 1,
  81234. groundMirrorFresnelWeight: 1,
  81235. groundMirrorFallOffDistance: 0,
  81236. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  81237. groundYBias: 0.00001,
  81238. createSkybox: true,
  81239. skyboxSize: 20,
  81240. skyboxTexture: this._skyboxTextureCDNUrl,
  81241. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  81242. backgroundYRotation: 0,
  81243. sizeAuto: true,
  81244. rootPosition: BABYLON.Vector3.Zero(),
  81245. setupImageProcessing: true,
  81246. environmentTexture: this._environmentTextureCDNUrl,
  81247. cameraExposure: 0.8,
  81248. cameraContrast: 1.2,
  81249. toneMappingEnabled: true,
  81250. };
  81251. };
  81252. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  81253. /**
  81254. * Gets the root mesh created by the helper.
  81255. */
  81256. get: function () {
  81257. return this._rootMesh;
  81258. },
  81259. enumerable: true,
  81260. configurable: true
  81261. });
  81262. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  81263. /**
  81264. * Gets the skybox created by the helper.
  81265. */
  81266. get: function () {
  81267. return this._skybox;
  81268. },
  81269. enumerable: true,
  81270. configurable: true
  81271. });
  81272. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  81273. /**
  81274. * Gets the skybox texture created by the helper.
  81275. */
  81276. get: function () {
  81277. return this._skyboxTexture;
  81278. },
  81279. enumerable: true,
  81280. configurable: true
  81281. });
  81282. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  81283. /**
  81284. * Gets the skybox material created by the helper.
  81285. */
  81286. get: function () {
  81287. return this._skyboxMaterial;
  81288. },
  81289. enumerable: true,
  81290. configurable: true
  81291. });
  81292. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  81293. /**
  81294. * Gets the ground mesh created by the helper.
  81295. */
  81296. get: function () {
  81297. return this._ground;
  81298. },
  81299. enumerable: true,
  81300. configurable: true
  81301. });
  81302. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  81303. /**
  81304. * Gets the ground texture created by the helper.
  81305. */
  81306. get: function () {
  81307. return this._groundTexture;
  81308. },
  81309. enumerable: true,
  81310. configurable: true
  81311. });
  81312. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  81313. /**
  81314. * Gets the ground mirror created by the helper.
  81315. */
  81316. get: function () {
  81317. return this._groundMirror;
  81318. },
  81319. enumerable: true,
  81320. configurable: true
  81321. });
  81322. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  81323. /**
  81324. * Gets the ground mirror render list to helps pushing the meshes
  81325. * you wish in the ground reflection.
  81326. */
  81327. get: function () {
  81328. if (this._groundMirror) {
  81329. return this._groundMirror.renderList;
  81330. }
  81331. return null;
  81332. },
  81333. enumerable: true,
  81334. configurable: true
  81335. });
  81336. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  81337. /**
  81338. * Gets the ground material created by the helper.
  81339. */
  81340. get: function () {
  81341. return this._groundMaterial;
  81342. },
  81343. enumerable: true,
  81344. configurable: true
  81345. });
  81346. /**
  81347. * Updates the background according to the new options
  81348. * @param options
  81349. */
  81350. EnvironmentHelper.prototype.updateOptions = function (options) {
  81351. var newOptions = __assign({}, this._options, options);
  81352. if (this._ground && !newOptions.createGround) {
  81353. this._ground.dispose();
  81354. this._ground = null;
  81355. }
  81356. if (this._groundMaterial && !newOptions.createGround) {
  81357. this._groundMaterial.dispose();
  81358. this._groundMaterial = null;
  81359. }
  81360. if (this._groundTexture) {
  81361. if (this._options.groundTexture != newOptions.groundTexture) {
  81362. this._groundTexture.dispose();
  81363. this._groundTexture = null;
  81364. }
  81365. }
  81366. if (this._skybox && !newOptions.createSkybox) {
  81367. this._skybox.dispose();
  81368. this._skybox = null;
  81369. }
  81370. if (this._skyboxMaterial && !newOptions.createSkybox) {
  81371. this._skyboxMaterial.dispose();
  81372. this._skyboxMaterial = null;
  81373. }
  81374. if (this._skyboxTexture) {
  81375. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  81376. this._skyboxTexture.dispose();
  81377. this._skyboxTexture = null;
  81378. }
  81379. }
  81380. if (this._groundMirror && !newOptions.enableGroundMirror) {
  81381. this._groundMirror.dispose();
  81382. this._groundMirror = null;
  81383. }
  81384. if (this._scene.environmentTexture) {
  81385. if (this._options.environmentTexture != newOptions.environmentTexture) {
  81386. this._scene.environmentTexture.dispose();
  81387. }
  81388. }
  81389. this._options = newOptions;
  81390. this._setupBackground();
  81391. this._setupImageProcessing();
  81392. };
  81393. /**
  81394. * Sets the primary color of all the available elements.
  81395. * @param color
  81396. */
  81397. EnvironmentHelper.prototype.setMainColor = function (color) {
  81398. if (this.groundMaterial) {
  81399. this.groundMaterial.primaryColor = color;
  81400. }
  81401. if (this.skyboxMaterial) {
  81402. this.skyboxMaterial.primaryColor = color;
  81403. }
  81404. if (this.groundMirror) {
  81405. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  81406. }
  81407. };
  81408. /**
  81409. * Setup the image processing according to the specified options.
  81410. */
  81411. EnvironmentHelper.prototype._setupImageProcessing = function () {
  81412. if (this._options.setupImageProcessing) {
  81413. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  81414. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  81415. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  81416. this._setupEnvironmentTexture();
  81417. }
  81418. };
  81419. /**
  81420. * Setup the environment texture according to the specified options.
  81421. */
  81422. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  81423. if (this._scene.environmentTexture) {
  81424. return;
  81425. }
  81426. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  81427. this._scene.environmentTexture = this._options.environmentTexture;
  81428. return;
  81429. }
  81430. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  81431. this._scene.environmentTexture = environmentTexture;
  81432. };
  81433. /**
  81434. * Setup the background according to the specified options.
  81435. */
  81436. EnvironmentHelper.prototype._setupBackground = function () {
  81437. if (!this._rootMesh) {
  81438. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  81439. }
  81440. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  81441. var sceneSize = this._getSceneSize();
  81442. if (this._options.createGround) {
  81443. this._setupGround(sceneSize);
  81444. this._setupGroundMaterial();
  81445. this._setupGroundDiffuseTexture();
  81446. if (this._options.enableGroundMirror) {
  81447. this._setupGroundMirrorTexture(sceneSize);
  81448. }
  81449. this._setupMirrorInGroundMaterial();
  81450. }
  81451. if (this._options.createSkybox) {
  81452. this._setupSkybox(sceneSize);
  81453. this._setupSkyboxMaterial();
  81454. this._setupSkyboxReflectionTexture();
  81455. }
  81456. this._rootMesh.position.x = sceneSize.rootPosition.x;
  81457. this._rootMesh.position.z = sceneSize.rootPosition.z;
  81458. this._rootMesh.position.y = sceneSize.rootPosition.y;
  81459. };
  81460. /**
  81461. * Get the scene sizes according to the setup.
  81462. */
  81463. EnvironmentHelper.prototype._getSceneSize = function () {
  81464. var groundSize = this._options.groundSize;
  81465. var skyboxSize = this._options.skyboxSize;
  81466. var rootPosition = this._options.rootPosition;
  81467. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  81468. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81469. }
  81470. var sceneExtends = this._scene.getWorldExtends();
  81471. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  81472. if (this._options.sizeAuto) {
  81473. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  81474. this._scene.activeCamera.upperRadiusLimit) {
  81475. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  81476. skyboxSize = groundSize;
  81477. }
  81478. var sceneDiagonalLenght = sceneDiagonal.length();
  81479. if (sceneDiagonalLenght > groundSize) {
  81480. groundSize = sceneDiagonalLenght * 2;
  81481. skyboxSize = groundSize;
  81482. }
  81483. // 10 % bigger.
  81484. groundSize *= 1.1;
  81485. skyboxSize *= 1.5;
  81486. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  81487. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  81488. }
  81489. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  81490. };
  81491. /**
  81492. * Setup the ground according to the specified options.
  81493. */
  81494. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  81495. var _this = this;
  81496. if (!this._ground) {
  81497. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  81498. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  81499. this._ground.parent = this._rootMesh;
  81500. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  81501. }
  81502. this._ground.receiveShadows = this._options.enableGroundShadow;
  81503. };
  81504. /**
  81505. * Setup the ground material according to the specified options.
  81506. */
  81507. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  81508. if (!this._groundMaterial) {
  81509. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  81510. }
  81511. this._groundMaterial.alpha = this._options.groundOpacity;
  81512. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  81513. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  81514. this._groundMaterial.primaryLevel = 1;
  81515. this._groundMaterial.primaryColor = this._options.groundColor;
  81516. this._groundMaterial.secondaryLevel = 0;
  81517. this._groundMaterial.tertiaryLevel = 0;
  81518. this._groundMaterial.useRGBColor = false;
  81519. this._groundMaterial.enableNoise = true;
  81520. if (this._ground) {
  81521. this._ground.material = this._groundMaterial;
  81522. }
  81523. };
  81524. /**
  81525. * Setup the ground diffuse texture according to the specified options.
  81526. */
  81527. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  81528. if (!this._groundMaterial) {
  81529. return;
  81530. }
  81531. if (this._groundTexture) {
  81532. return;
  81533. }
  81534. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  81535. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  81536. return;
  81537. }
  81538. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  81539. diffuseTexture.gammaSpace = false;
  81540. diffuseTexture.hasAlpha = true;
  81541. this._groundMaterial.diffuseTexture = diffuseTexture;
  81542. };
  81543. /**
  81544. * Setup the ground mirror texture according to the specified options.
  81545. */
  81546. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  81547. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  81548. if (!this._groundMirror) {
  81549. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  81550. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  81551. this._groundMirror.anisotropicFilteringLevel = 1;
  81552. this._groundMirror.wrapU = wrapping;
  81553. this._groundMirror.wrapV = wrapping;
  81554. this._groundMirror.gammaSpace = false;
  81555. if (this._groundMirror.renderList) {
  81556. for (var i = 0; i < this._scene.meshes.length; i++) {
  81557. var mesh = this._scene.meshes[i];
  81558. if (mesh !== this._ground &&
  81559. mesh !== this._skybox &&
  81560. mesh !== this._rootMesh) {
  81561. this._groundMirror.renderList.push(mesh);
  81562. }
  81563. }
  81564. }
  81565. }
  81566. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  81567. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  81568. };
  81569. /**
  81570. * Setup the ground to receive the mirror texture.
  81571. */
  81572. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  81573. if (this._groundMaterial) {
  81574. this._groundMaterial.reflectionTexture = this._groundMirror;
  81575. this._groundMaterial.reflectionFresnel = true;
  81576. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  81577. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  81578. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  81579. }
  81580. };
  81581. /**
  81582. * Setup the skybox according to the specified options.
  81583. */
  81584. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  81585. var _this = this;
  81586. if (!this._skybox) {
  81587. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  81588. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  81589. }
  81590. this._skybox.parent = this._rootMesh;
  81591. };
  81592. /**
  81593. * Setup the skybox material according to the specified options.
  81594. */
  81595. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  81596. if (!this._skybox) {
  81597. return;
  81598. }
  81599. if (!this._skyboxMaterial) {
  81600. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  81601. }
  81602. this._skyboxMaterial.useRGBColor = false;
  81603. this._skyboxMaterial.primaryLevel = 1;
  81604. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  81605. this._skyboxMaterial.secondaryLevel = 0;
  81606. this._skyboxMaterial.tertiaryLevel = 0;
  81607. this._skyboxMaterial.enableNoise = true;
  81608. this._skybox.material = this._skyboxMaterial;
  81609. };
  81610. /**
  81611. * Setup the skybox reflection texture according to the specified options.
  81612. */
  81613. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  81614. if (!this._skyboxMaterial) {
  81615. return;
  81616. }
  81617. if (this._skyboxTexture) {
  81618. return;
  81619. }
  81620. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  81621. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81622. return;
  81623. }
  81624. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  81625. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  81626. this._skyboxTexture.gammaSpace = false;
  81627. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  81628. };
  81629. /**
  81630. * Dispose all the elements created by the Helper.
  81631. */
  81632. EnvironmentHelper.prototype.dispose = function () {
  81633. if (this._groundMaterial) {
  81634. this._groundMaterial.dispose(true, true);
  81635. }
  81636. if (this._skyboxMaterial) {
  81637. this._skyboxMaterial.dispose(true, true);
  81638. }
  81639. this._rootMesh.dispose(false);
  81640. };
  81641. /**
  81642. * Default ground texture URL.
  81643. */
  81644. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  81645. /**
  81646. * Default skybox texture URL.
  81647. */
  81648. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  81649. /**
  81650. * Default environment texture URL.
  81651. */
  81652. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  81653. return EnvironmentHelper;
  81654. }());
  81655. BABYLON.EnvironmentHelper = EnvironmentHelper;
  81656. })(BABYLON || (BABYLON = {}));
  81657. //# sourceMappingURL=babylon.environmentHelper.js.map
  81658. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","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#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 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}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}"};
  81659. 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#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}\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 SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  81660. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81661. var BABYLON;
  81662. (function (BABYLON) {
  81663. var GridMaterialDefines = /** @class */ (function (_super) {
  81664. __extends(GridMaterialDefines, _super);
  81665. function GridMaterialDefines() {
  81666. var _this = _super.call(this) || this;
  81667. _this.TRANSPARENT = false;
  81668. _this.FOG = false;
  81669. _this.PREMULTIPLYALPHA = false;
  81670. _this.rebuild();
  81671. return _this;
  81672. }
  81673. return GridMaterialDefines;
  81674. }(BABYLON.MaterialDefines));
  81675. /**
  81676. * The grid materials allows you to wrap any shape with a grid.
  81677. * Colors are customizable.
  81678. */
  81679. var GridMaterial = /** @class */ (function (_super) {
  81680. __extends(GridMaterial, _super);
  81681. /**
  81682. * constructor
  81683. * @param name The name given to the material in order to identify it afterwards.
  81684. * @param scene The scene the material is used in.
  81685. */
  81686. function GridMaterial(name, scene) {
  81687. var _this = _super.call(this, name, scene) || this;
  81688. /**
  81689. * Main color of the grid (e.g. between lines)
  81690. */
  81691. _this.mainColor = BABYLON.Color3.Black();
  81692. /**
  81693. * Color of the grid lines.
  81694. */
  81695. _this.lineColor = BABYLON.Color3.Teal();
  81696. /**
  81697. * The scale of the grid compared to unit.
  81698. */
  81699. _this.gridRatio = 1.0;
  81700. /**
  81701. * Allows setting an offset for the grid lines.
  81702. */
  81703. _this.gridOffset = BABYLON.Vector3.Zero();
  81704. /**
  81705. * The frequency of thicker lines.
  81706. */
  81707. _this.majorUnitFrequency = 10;
  81708. /**
  81709. * The visibility of minor units in the grid.
  81710. */
  81711. _this.minorUnitVisibility = 0.33;
  81712. /**
  81713. * The grid opacity outside of the lines.
  81714. */
  81715. _this.opacity = 1.0;
  81716. /**
  81717. * Determine RBG output is premultiplied by alpha value.
  81718. */
  81719. _this.preMultiplyAlpha = false;
  81720. _this._gridControl = new BABYLON.Vector4(_this.gridRatio, _this.majorUnitFrequency, _this.minorUnitVisibility, _this.opacity);
  81721. return _this;
  81722. }
  81723. /**
  81724. * Returns wehter or not the grid requires alpha blending.
  81725. */
  81726. GridMaterial.prototype.needAlphaBlending = function () {
  81727. return this.opacity < 1.0;
  81728. };
  81729. GridMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  81730. return this.needAlphaBlending();
  81731. };
  81732. GridMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  81733. if (this.isFrozen) {
  81734. if (this._wasPreviouslyReady && subMesh.effect) {
  81735. return true;
  81736. }
  81737. }
  81738. if (!subMesh._materialDefines) {
  81739. subMesh._materialDefines = new GridMaterialDefines();
  81740. }
  81741. var defines = subMesh._materialDefines;
  81742. var scene = this.getScene();
  81743. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  81744. if (this._renderId === scene.getRenderId()) {
  81745. return true;
  81746. }
  81747. }
  81748. if (defines.TRANSPARENT !== (this.opacity < 1.0)) {
  81749. defines.TRANSPARENT = !defines.TRANSPARENT;
  81750. defines.markAsUnprocessed();
  81751. }
  81752. if (defines.PREMULTIPLYALPHA != this.preMultiplyAlpha) {
  81753. defines.PREMULTIPLYALPHA = !defines.PREMULTIPLYALPHA;
  81754. defines.markAsUnprocessed();
  81755. }
  81756. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, false, this.fogEnabled, defines);
  81757. // Get correct effect
  81758. if (defines.isDirty) {
  81759. defines.markAsProcessed();
  81760. scene.resetCachedMaterial();
  81761. // Attributes
  81762. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  81763. // Defines
  81764. var join = defines.toString();
  81765. subMesh.setEffect(scene.getEngine().createEffect("grid", attribs, ["projection", "worldView", "mainColor", "lineColor", "gridControl", "gridOffset", "vFogInfos", "vFogColor", "world", "view"], [], join, undefined, this.onCompiled, this.onError), defines);
  81766. }
  81767. if (!subMesh.effect || !subMesh.effect.isReady()) {
  81768. return false;
  81769. }
  81770. this._renderId = scene.getRenderId();
  81771. this._wasPreviouslyReady = true;
  81772. return true;
  81773. };
  81774. GridMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  81775. var scene = this.getScene();
  81776. var defines = subMesh._materialDefines;
  81777. if (!defines) {
  81778. return;
  81779. }
  81780. var effect = subMesh.effect;
  81781. if (!effect) {
  81782. return;
  81783. }
  81784. this._activeEffect = effect;
  81785. // Matrices
  81786. this.bindOnlyWorldMatrix(world);
  81787. this._activeEffect.setMatrix("worldView", world.multiply(scene.getViewMatrix()));
  81788. this._activeEffect.setMatrix("view", scene.getViewMatrix());
  81789. this._activeEffect.setMatrix("projection", scene.getProjectionMatrix());
  81790. // Uniforms
  81791. if (this._mustRebind(scene, effect)) {
  81792. this._activeEffect.setColor3("mainColor", this.mainColor);
  81793. this._activeEffect.setColor3("lineColor", this.lineColor);
  81794. this._activeEffect.setVector3("gridOffset", this.gridOffset);
  81795. this._gridControl.x = this.gridRatio;
  81796. this._gridControl.y = Math.round(this.majorUnitFrequency);
  81797. this._gridControl.z = this.minorUnitVisibility;
  81798. this._gridControl.w = this.opacity;
  81799. this._activeEffect.setVector4("gridControl", this._gridControl);
  81800. }
  81801. // Fog
  81802. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  81803. this._afterBind(mesh, this._activeEffect);
  81804. };
  81805. GridMaterial.prototype.dispose = function (forceDisposeEffect) {
  81806. _super.prototype.dispose.call(this, forceDisposeEffect);
  81807. };
  81808. GridMaterial.prototype.clone = function (name) {
  81809. var _this = this;
  81810. return BABYLON.SerializationHelper.Clone(function () { return new GridMaterial(name, _this.getScene()); }, this);
  81811. };
  81812. GridMaterial.prototype.serialize = function () {
  81813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  81814. serializationObject.customType = "BABYLON.GridMaterial";
  81815. return serializationObject;
  81816. };
  81817. GridMaterial.prototype.getClassName = function () {
  81818. return "GridMaterial";
  81819. };
  81820. GridMaterial.Parse = function (source, scene, rootUrl) {
  81821. return BABYLON.SerializationHelper.Parse(function () { return new GridMaterial(source.name, scene); }, source, scene, rootUrl);
  81822. };
  81823. __decorate([
  81824. BABYLON.serializeAsColor3()
  81825. ], GridMaterial.prototype, "mainColor", void 0);
  81826. __decorate([
  81827. BABYLON.serializeAsColor3()
  81828. ], GridMaterial.prototype, "lineColor", void 0);
  81829. __decorate([
  81830. BABYLON.serialize()
  81831. ], GridMaterial.prototype, "gridRatio", void 0);
  81832. __decorate([
  81833. BABYLON.serializeAsColor3()
  81834. ], GridMaterial.prototype, "gridOffset", void 0);
  81835. __decorate([
  81836. BABYLON.serialize()
  81837. ], GridMaterial.prototype, "majorUnitFrequency", void 0);
  81838. __decorate([
  81839. BABYLON.serialize()
  81840. ], GridMaterial.prototype, "minorUnitVisibility", void 0);
  81841. __decorate([
  81842. BABYLON.serialize()
  81843. ], GridMaterial.prototype, "opacity", void 0);
  81844. __decorate([
  81845. BABYLON.serialize()
  81846. ], GridMaterial.prototype, "preMultiplyAlpha", void 0);
  81847. return GridMaterial;
  81848. }(BABYLON.PushMaterial));
  81849. BABYLON.GridMaterial = GridMaterial;
  81850. })(BABYLON || (BABYLON = {}));
  81851. //# sourceMappingURL=babylon.gridmaterial.js.map
  81852. 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}";
  81853. 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}";
  81854. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  81855. var BABYLON;
  81856. (function (BABYLON) {
  81857. var GLTFLoaderCoordinateSystemMode;
  81858. (function (GLTFLoaderCoordinateSystemMode) {
  81859. /**
  81860. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  81861. */
  81862. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  81863. /**
  81864. * Sets the useRightHandedSystem flag on the scene.
  81865. */
  81866. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  81867. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  81868. var GLTFLoaderAnimationStartMode;
  81869. (function (GLTFLoaderAnimationStartMode) {
  81870. /**
  81871. * No animation will start.
  81872. */
  81873. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  81874. /**
  81875. * The first animation will start.
  81876. */
  81877. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  81878. /**
  81879. * All animations will start.
  81880. */
  81881. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  81882. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  81883. var GLTFFileLoader = /** @class */ (function () {
  81884. function GLTFFileLoader() {
  81885. // #region Common options
  81886. /**
  81887. * Raised when the asset has been parsed.
  81888. * The data.json property stores the glTF JSON.
  81889. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  81890. */
  81891. this.onParsedObservable = new BABYLON.Observable();
  81892. // #endregion
  81893. // #region V2 options
  81894. /**
  81895. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  81896. */
  81897. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  81898. /**
  81899. * The animation start mode (NONE, FIRST, ALL).
  81900. */
  81901. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  81902. /**
  81903. * Set to true to compile materials before raising the success callback.
  81904. */
  81905. this.compileMaterials = false;
  81906. /**
  81907. * Set to true to also compile materials with clip planes.
  81908. */
  81909. this.useClipPlane = false;
  81910. /**
  81911. * Set to true to compile shadow generators before raising the success callback.
  81912. */
  81913. this.compileShadowGenerators = false;
  81914. /**
  81915. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  81916. */
  81917. this.onMeshLoadedObservable = new BABYLON.Observable();
  81918. /**
  81919. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  81920. */
  81921. this.onTextureLoadedObservable = new BABYLON.Observable();
  81922. /**
  81923. * Raised when the loader creates a material after parsing the glTF properties of the material.
  81924. */
  81925. this.onMaterialLoadedObservable = new BABYLON.Observable();
  81926. /**
  81927. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  81928. * For assets with LODs, raised when all of the LODs are complete.
  81929. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  81930. */
  81931. this.onCompleteObservable = new BABYLON.Observable();
  81932. /**
  81933. * Raised when the loader is disposed.
  81934. */
  81935. this.onDisposeObservable = new BABYLON.Observable();
  81936. // #endregion
  81937. this._loader = null;
  81938. this.name = "gltf";
  81939. this.extensions = {
  81940. ".gltf": { isBinary: false },
  81941. ".glb": { isBinary: true }
  81942. };
  81943. }
  81944. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  81945. set: function (callback) {
  81946. if (this._onParsedObserver) {
  81947. this.onParsedObservable.remove(this._onParsedObserver);
  81948. }
  81949. this._onParsedObserver = this.onParsedObservable.add(callback);
  81950. },
  81951. enumerable: true,
  81952. configurable: true
  81953. });
  81954. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  81955. set: function (callback) {
  81956. if (this._onMeshLoadedObserver) {
  81957. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  81958. }
  81959. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  81960. },
  81961. enumerable: true,
  81962. configurable: true
  81963. });
  81964. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  81965. set: function (callback) {
  81966. if (this._onTextureLoadedObserver) {
  81967. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  81968. }
  81969. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  81970. },
  81971. enumerable: true,
  81972. configurable: true
  81973. });
  81974. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  81975. set: function (callback) {
  81976. if (this._onMaterialLoadedObserver) {
  81977. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  81978. }
  81979. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  81980. },
  81981. enumerable: true,
  81982. configurable: true
  81983. });
  81984. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  81985. set: function (callback) {
  81986. if (this._onCompleteObserver) {
  81987. this.onCompleteObservable.remove(this._onCompleteObserver);
  81988. }
  81989. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  81990. },
  81991. enumerable: true,
  81992. configurable: true
  81993. });
  81994. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  81995. set: function (callback) {
  81996. if (this._onDisposeObserver) {
  81997. this.onDisposeObservable.remove(this._onDisposeObserver);
  81998. }
  81999. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  82000. },
  82001. enumerable: true,
  82002. configurable: true
  82003. });
  82004. /**
  82005. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  82006. */
  82007. GLTFFileLoader.prototype.dispose = function () {
  82008. if (this._loader) {
  82009. this._loader.dispose();
  82010. this._loader = null;
  82011. }
  82012. this.onParsedObservable.clear();
  82013. this.onMeshLoadedObservable.clear();
  82014. this.onTextureLoadedObservable.clear();
  82015. this.onMaterialLoadedObservable.clear();
  82016. this.onCompleteObservable.clear();
  82017. this.onDisposeObservable.notifyObservers(this);
  82018. this.onDisposeObservable.clear();
  82019. };
  82020. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  82021. try {
  82022. var loaderData = this._parse(data);
  82023. this._loader = this._getLoader(loaderData);
  82024. this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  82025. }
  82026. catch (e) {
  82027. if (onError) {
  82028. onError(e.message, e);
  82029. }
  82030. else {
  82031. BABYLON.Tools.Error(e.message);
  82032. }
  82033. }
  82034. };
  82035. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82036. try {
  82037. var loaderData = this._parse(data);
  82038. this._loader = this._getLoader(loaderData);
  82039. this._loader.loadAsync(scene, loaderData, rootUrl, onSuccess, onProgress, onError);
  82040. }
  82041. catch (e) {
  82042. if (onError) {
  82043. onError(e.message, e);
  82044. }
  82045. else {
  82046. BABYLON.Tools.Error(e.message);
  82047. }
  82048. }
  82049. };
  82050. GLTFFileLoader.prototype.loadAssetsAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  82051. try {
  82052. var loaderData = this._parse(data);
  82053. this._loader = this._getLoader(loaderData);
  82054. this._loader.importMeshAsync(null, scene, loaderData, rootUrl, function (meshes, particleSystems, skeletons) {
  82055. var container = new BABYLON.AssetContainer(scene);
  82056. Array.prototype.push.apply(container.meshes, meshes);
  82057. Array.prototype.push.apply(container.particleSystems, particleSystems);
  82058. Array.prototype.push.apply(container.skeletons, skeletons);
  82059. container.removeAllFromScene();
  82060. onSuccess(container);
  82061. }, onProgress, onError);
  82062. }
  82063. catch (e) {
  82064. if (onError) {
  82065. onError(e.message, e);
  82066. }
  82067. else {
  82068. BABYLON.Tools.Error(e.message);
  82069. }
  82070. }
  82071. };
  82072. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  82073. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  82074. };
  82075. GLTFFileLoader.prototype.createPlugin = function () {
  82076. return new GLTFFileLoader();
  82077. };
  82078. GLTFFileLoader.prototype._parse = function (data) {
  82079. var parsedData;
  82080. if (data instanceof ArrayBuffer) {
  82081. parsedData = GLTFFileLoader._parseBinary(data);
  82082. }
  82083. else {
  82084. parsedData = {
  82085. json: JSON.parse(data),
  82086. bin: null
  82087. };
  82088. }
  82089. this.onParsedObservable.notifyObservers(parsedData);
  82090. return parsedData;
  82091. };
  82092. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  82093. var _this = this;
  82094. var loaderVersion = { major: 2, minor: 0 };
  82095. var asset = loaderData.json.asset || {};
  82096. var version = GLTFFileLoader._parseVersion(asset.version);
  82097. if (!version) {
  82098. throw new Error("Invalid version: " + asset.version);
  82099. }
  82100. if (asset.minVersion !== undefined) {
  82101. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  82102. if (!minVersion) {
  82103. throw new Error("Invalid minimum version: " + asset.minVersion);
  82104. }
  82105. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  82106. throw new Error("Incompatible minimum version: " + asset.minVersion);
  82107. }
  82108. }
  82109. var createLoaders = {
  82110. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  82111. 2: GLTFFileLoader.CreateGLTFLoaderV2
  82112. };
  82113. var createLoader = createLoaders[version.major];
  82114. if (!createLoader) {
  82115. throw new Error("Unsupported version: " + asset.version);
  82116. }
  82117. var loader = createLoader();
  82118. loader.coordinateSystemMode = this.coordinateSystemMode;
  82119. loader.animationStartMode = this.animationStartMode;
  82120. loader.compileMaterials = this.compileMaterials;
  82121. loader.useClipPlane = this.useClipPlane;
  82122. loader.compileShadowGenerators = this.compileShadowGenerators;
  82123. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  82124. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  82125. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  82126. loader.onCompleteObservable.add(function () { return _this.onCompleteObservable.notifyObservers(_this); });
  82127. return loader;
  82128. };
  82129. GLTFFileLoader._parseBinary = function (data) {
  82130. var Binary = {
  82131. Magic: 0x46546C67
  82132. };
  82133. var binaryReader = new BinaryReader(data);
  82134. var magic = binaryReader.readUint32();
  82135. if (magic !== Binary.Magic) {
  82136. throw new Error("Unexpected magic: " + magic);
  82137. }
  82138. var version = binaryReader.readUint32();
  82139. switch (version) {
  82140. case 1: return GLTFFileLoader._parseV1(binaryReader);
  82141. case 2: return GLTFFileLoader._parseV2(binaryReader);
  82142. }
  82143. throw new Error("Unsupported version: " + version);
  82144. };
  82145. GLTFFileLoader._parseV1 = function (binaryReader) {
  82146. var ContentFormat = {
  82147. JSON: 0
  82148. };
  82149. var length = binaryReader.readUint32();
  82150. if (length != binaryReader.getLength()) {
  82151. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  82152. }
  82153. var contentLength = binaryReader.readUint32();
  82154. var contentFormat = binaryReader.readUint32();
  82155. var content;
  82156. switch (contentFormat) {
  82157. case ContentFormat.JSON: {
  82158. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  82159. break;
  82160. }
  82161. default: {
  82162. throw new Error("Unexpected content format: " + contentFormat);
  82163. }
  82164. }
  82165. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  82166. var body = binaryReader.readUint8Array(bytesRemaining);
  82167. return {
  82168. json: content,
  82169. bin: body
  82170. };
  82171. };
  82172. GLTFFileLoader._parseV2 = function (binaryReader) {
  82173. var ChunkFormat = {
  82174. JSON: 0x4E4F534A,
  82175. BIN: 0x004E4942
  82176. };
  82177. var length = binaryReader.readUint32();
  82178. if (length !== binaryReader.getLength()) {
  82179. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  82180. }
  82181. // JSON chunk
  82182. var chunkLength = binaryReader.readUint32();
  82183. var chunkFormat = binaryReader.readUint32();
  82184. if (chunkFormat !== ChunkFormat.JSON) {
  82185. throw new Error("First chunk format is not JSON");
  82186. }
  82187. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  82188. // Look for BIN chunk
  82189. var bin = null;
  82190. while (binaryReader.getPosition() < binaryReader.getLength()) {
  82191. var chunkLength_1 = binaryReader.readUint32();
  82192. var chunkFormat_1 = binaryReader.readUint32();
  82193. switch (chunkFormat_1) {
  82194. case ChunkFormat.JSON: {
  82195. throw new Error("Unexpected JSON chunk");
  82196. }
  82197. case ChunkFormat.BIN: {
  82198. bin = binaryReader.readUint8Array(chunkLength_1);
  82199. break;
  82200. }
  82201. default: {
  82202. // ignore unrecognized chunkFormat
  82203. binaryReader.skipBytes(chunkLength_1);
  82204. break;
  82205. }
  82206. }
  82207. }
  82208. return {
  82209. json: json,
  82210. bin: bin
  82211. };
  82212. };
  82213. GLTFFileLoader._parseVersion = function (version) {
  82214. if (version === "1.0" || version === "1.0.1") {
  82215. return {
  82216. major: 1,
  82217. minor: 0
  82218. };
  82219. }
  82220. var match = (version + "").match(/^(\d+)\.(\d+)/);
  82221. if (!match) {
  82222. return null;
  82223. }
  82224. return {
  82225. major: parseInt(match[1]),
  82226. minor: parseInt(match[2])
  82227. };
  82228. };
  82229. GLTFFileLoader._compareVersion = function (a, b) {
  82230. if (a.major > b.major)
  82231. return 1;
  82232. if (a.major < b.major)
  82233. return -1;
  82234. if (a.minor > b.minor)
  82235. return 1;
  82236. if (a.minor < b.minor)
  82237. return -1;
  82238. return 0;
  82239. };
  82240. GLTFFileLoader._decodeBufferToText = function (buffer) {
  82241. var result = "";
  82242. var length = buffer.byteLength;
  82243. for (var i = 0; i < length; i++) {
  82244. result += String.fromCharCode(buffer[i]);
  82245. }
  82246. return result;
  82247. };
  82248. // #endregion
  82249. // #region V1 options
  82250. GLTFFileLoader.IncrementalLoading = true;
  82251. GLTFFileLoader.HomogeneousCoordinates = false;
  82252. return GLTFFileLoader;
  82253. }());
  82254. BABYLON.GLTFFileLoader = GLTFFileLoader;
  82255. var BinaryReader = /** @class */ (function () {
  82256. function BinaryReader(arrayBuffer) {
  82257. this._arrayBuffer = arrayBuffer;
  82258. this._dataView = new DataView(arrayBuffer);
  82259. this._byteOffset = 0;
  82260. }
  82261. BinaryReader.prototype.getPosition = function () {
  82262. return this._byteOffset;
  82263. };
  82264. BinaryReader.prototype.getLength = function () {
  82265. return this._arrayBuffer.byteLength;
  82266. };
  82267. BinaryReader.prototype.readUint32 = function () {
  82268. var value = this._dataView.getUint32(this._byteOffset, true);
  82269. this._byteOffset += 4;
  82270. return value;
  82271. };
  82272. BinaryReader.prototype.readUint8Array = function (length) {
  82273. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  82274. this._byteOffset += length;
  82275. return value;
  82276. };
  82277. BinaryReader.prototype.skipBytes = function (length) {
  82278. this._byteOffset += length;
  82279. };
  82280. return BinaryReader;
  82281. }());
  82282. if (BABYLON.SceneLoader) {
  82283. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  82284. }
  82285. })(BABYLON || (BABYLON = {}));
  82286. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  82287. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82288. var BABYLON;
  82289. (function (BABYLON) {
  82290. var GLTF1;
  82291. (function (GLTF1) {
  82292. /**
  82293. * Enums
  82294. */
  82295. var EComponentType;
  82296. (function (EComponentType) {
  82297. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  82298. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82299. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  82300. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82301. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  82302. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  82303. var EShaderType;
  82304. (function (EShaderType) {
  82305. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  82306. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  82307. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  82308. var EParameterType;
  82309. (function (EParameterType) {
  82310. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  82311. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  82312. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  82313. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  82314. EParameterType[EParameterType["INT"] = 5124] = "INT";
  82315. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  82316. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  82317. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  82318. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  82319. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  82320. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  82321. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  82322. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  82323. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  82324. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  82325. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  82326. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  82327. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  82328. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  82329. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  82330. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  82331. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  82332. var ETextureWrapMode;
  82333. (function (ETextureWrapMode) {
  82334. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  82335. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  82336. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  82337. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  82338. var ETextureFilterType;
  82339. (function (ETextureFilterType) {
  82340. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  82341. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  82342. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  82343. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  82344. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  82345. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  82346. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  82347. var ETextureFormat;
  82348. (function (ETextureFormat) {
  82349. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  82350. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  82351. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  82352. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  82353. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  82354. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  82355. var ECullingType;
  82356. (function (ECullingType) {
  82357. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  82358. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  82359. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  82360. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  82361. var EBlendingFunction;
  82362. (function (EBlendingFunction) {
  82363. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  82364. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  82365. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  82366. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  82367. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  82368. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  82369. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  82370. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  82371. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  82372. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  82373. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  82374. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  82375. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  82376. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  82377. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  82378. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  82379. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  82380. })(BABYLON || (BABYLON = {}));
  82381. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  82382. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  82383. var BABYLON;
  82384. (function (BABYLON) {
  82385. var GLTF1;
  82386. (function (GLTF1) {
  82387. /**
  82388. * Tokenizer. Used for shaders compatibility
  82389. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  82390. */
  82391. var ETokenType;
  82392. (function (ETokenType) {
  82393. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  82394. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  82395. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  82396. })(ETokenType || (ETokenType = {}));
  82397. var Tokenizer = /** @class */ (function () {
  82398. function Tokenizer(toParse) {
  82399. this._pos = 0;
  82400. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  82401. this._toParse = toParse;
  82402. this._maxPos = toParse.length;
  82403. }
  82404. Tokenizer.prototype.getNextToken = function () {
  82405. if (this.isEnd())
  82406. return ETokenType.END_OF_INPUT;
  82407. this.currentString = this.read();
  82408. this.currentToken = ETokenType.UNKNOWN;
  82409. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  82410. this.currentToken = ETokenType.IDENTIFIER;
  82411. this.currentIdentifier = this.currentString;
  82412. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  82413. this.currentIdentifier += this.currentString;
  82414. this.forward();
  82415. }
  82416. }
  82417. return this.currentToken;
  82418. };
  82419. Tokenizer.prototype.peek = function () {
  82420. return this._toParse[this._pos];
  82421. };
  82422. Tokenizer.prototype.read = function () {
  82423. return this._toParse[this._pos++];
  82424. };
  82425. Tokenizer.prototype.forward = function () {
  82426. this._pos++;
  82427. };
  82428. Tokenizer.prototype.isEnd = function () {
  82429. return this._pos >= this._maxPos;
  82430. };
  82431. return Tokenizer;
  82432. }());
  82433. /**
  82434. * Values
  82435. */
  82436. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  82437. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  82438. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  82439. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  82440. /**
  82441. * Parse
  82442. */
  82443. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  82444. for (var buf in parsedBuffers) {
  82445. var parsedBuffer = parsedBuffers[buf];
  82446. gltfRuntime.buffers[buf] = parsedBuffer;
  82447. gltfRuntime.buffersCount++;
  82448. }
  82449. };
  82450. var parseShaders = function (parsedShaders, gltfRuntime) {
  82451. for (var sha in parsedShaders) {
  82452. var parsedShader = parsedShaders[sha];
  82453. gltfRuntime.shaders[sha] = parsedShader;
  82454. gltfRuntime.shaderscount++;
  82455. }
  82456. };
  82457. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  82458. for (var object in parsedObjects) {
  82459. var parsedObject = parsedObjects[object];
  82460. gltfRuntime[runtimeProperty][object] = parsedObject;
  82461. }
  82462. };
  82463. /**
  82464. * Utils
  82465. */
  82466. var normalizeUVs = function (buffer) {
  82467. if (!buffer) {
  82468. return;
  82469. }
  82470. for (var i = 0; i < buffer.length / 2; i++) {
  82471. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  82472. }
  82473. };
  82474. var getAttribute = function (attributeParameter) {
  82475. if (attributeParameter.semantic === "NORMAL") {
  82476. return "normal";
  82477. }
  82478. else if (attributeParameter.semantic === "POSITION") {
  82479. return "position";
  82480. }
  82481. else if (attributeParameter.semantic === "JOINT") {
  82482. return "matricesIndices";
  82483. }
  82484. else if (attributeParameter.semantic === "WEIGHT") {
  82485. return "matricesWeights";
  82486. }
  82487. else if (attributeParameter.semantic === "COLOR") {
  82488. return "color";
  82489. }
  82490. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  82491. var channel = Number(attributeParameter.semantic.split("_")[1]);
  82492. return "uv" + (channel === 0 ? "" : channel + 1);
  82493. }
  82494. return null;
  82495. };
  82496. /**
  82497. * Loads and creates animations
  82498. */
  82499. var loadAnimations = function (gltfRuntime) {
  82500. for (var anim in gltfRuntime.animations) {
  82501. var animation = gltfRuntime.animations[anim];
  82502. if (!animation.channels || !animation.samplers) {
  82503. continue;
  82504. }
  82505. var lastAnimation = null;
  82506. for (var i = 0; i < animation.channels.length; i++) {
  82507. // Get parameters and load buffers
  82508. var channel = animation.channels[i];
  82509. var sampler = animation.samplers[channel.sampler];
  82510. if (!sampler) {
  82511. continue;
  82512. }
  82513. var inputData = null;
  82514. var outputData = null;
  82515. if (animation.parameters) {
  82516. inputData = animation.parameters[sampler.input];
  82517. outputData = animation.parameters[sampler.output];
  82518. }
  82519. else {
  82520. inputData = sampler.input;
  82521. outputData = sampler.output;
  82522. }
  82523. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  82524. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  82525. var targetID = channel.target.id;
  82526. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  82527. if (targetNode === null) {
  82528. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  82529. }
  82530. if (targetNode === null) {
  82531. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  82532. continue;
  82533. }
  82534. var isBone = targetNode instanceof BABYLON.Bone;
  82535. // Get target path (position, rotation or scaling)
  82536. var targetPath = channel.target.path;
  82537. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  82538. if (targetPathIndex !== -1) {
  82539. targetPath = babylonAnimationPaths[targetPathIndex];
  82540. }
  82541. // Determine animation type
  82542. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  82543. if (!isBone) {
  82544. if (targetPath === "rotationQuaternion") {
  82545. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  82546. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  82547. }
  82548. else {
  82549. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  82550. }
  82551. }
  82552. // Create animation and key frames
  82553. var babylonAnimation = null;
  82554. var keys = [];
  82555. var arrayOffset = 0;
  82556. var modifyKey = false;
  82557. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  82558. babylonAnimation = lastAnimation;
  82559. modifyKey = true;
  82560. }
  82561. if (!modifyKey) {
  82562. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  82563. }
  82564. // For each frame
  82565. for (var j = 0; j < bufferInput.length; j++) {
  82566. var value = null;
  82567. if (targetPath === "rotationQuaternion") {
  82568. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  82569. arrayOffset += 4;
  82570. }
  82571. else {
  82572. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  82573. arrayOffset += 3;
  82574. }
  82575. if (isBone) {
  82576. var bone = targetNode;
  82577. var translation = BABYLON.Vector3.Zero();
  82578. var rotationQuaternion = new BABYLON.Quaternion();
  82579. var scaling = BABYLON.Vector3.Zero();
  82580. // Warning on decompose
  82581. var mat = bone.getBaseMatrix();
  82582. if (modifyKey && lastAnimation) {
  82583. mat = lastAnimation.getKeys()[j].value;
  82584. }
  82585. mat.decompose(scaling, rotationQuaternion, translation);
  82586. if (targetPath === "position") {
  82587. translation = value;
  82588. }
  82589. else if (targetPath === "rotationQuaternion") {
  82590. rotationQuaternion = value;
  82591. }
  82592. else {
  82593. scaling = value;
  82594. }
  82595. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  82596. }
  82597. if (!modifyKey) {
  82598. keys.push({
  82599. frame: bufferInput[j],
  82600. value: value
  82601. });
  82602. }
  82603. else if (lastAnimation) {
  82604. lastAnimation.getKeys()[j].value = value;
  82605. }
  82606. }
  82607. // Finish
  82608. if (!modifyKey && babylonAnimation) {
  82609. babylonAnimation.setKeys(keys);
  82610. targetNode.animations.push(babylonAnimation);
  82611. }
  82612. lastAnimation = babylonAnimation;
  82613. gltfRuntime.scene.stopAnimation(targetNode);
  82614. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  82615. }
  82616. }
  82617. };
  82618. /**
  82619. * Returns the bones transformation matrix
  82620. */
  82621. var configureBoneTransformation = function (node) {
  82622. var mat = null;
  82623. if (node.translation || node.rotation || node.scale) {
  82624. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  82625. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  82626. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  82627. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  82628. }
  82629. else {
  82630. mat = BABYLON.Matrix.FromArray(node.matrix);
  82631. }
  82632. return mat;
  82633. };
  82634. /**
  82635. * Returns the parent bone
  82636. */
  82637. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  82638. // Try to find
  82639. for (var i = 0; i < newSkeleton.bones.length; i++) {
  82640. if (newSkeleton.bones[i].name === jointName) {
  82641. return newSkeleton.bones[i];
  82642. }
  82643. }
  82644. // Not found, search in gltf nodes
  82645. var nodes = gltfRuntime.nodes;
  82646. for (var nde in nodes) {
  82647. var node = nodes[nde];
  82648. if (!node.jointName) {
  82649. continue;
  82650. }
  82651. var children = node.children;
  82652. for (var i = 0; i < children.length; i++) {
  82653. var child = gltfRuntime.nodes[children[i]];
  82654. if (!child.jointName) {
  82655. continue;
  82656. }
  82657. if (child.jointName === jointName) {
  82658. var mat = configureBoneTransformation(node);
  82659. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  82660. bone.id = nde;
  82661. return bone;
  82662. }
  82663. }
  82664. }
  82665. return null;
  82666. };
  82667. /**
  82668. * Returns the appropriate root node
  82669. */
  82670. var getNodeToRoot = function (nodesToRoot, id) {
  82671. for (var i = 0; i < nodesToRoot.length; i++) {
  82672. var nodeToRoot = nodesToRoot[i];
  82673. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  82674. var child = nodeToRoot.node.children[j];
  82675. if (child === id) {
  82676. return nodeToRoot.bone;
  82677. }
  82678. }
  82679. }
  82680. return null;
  82681. };
  82682. /**
  82683. * Returns the node with the joint name
  82684. */
  82685. var getJointNode = function (gltfRuntime, jointName) {
  82686. var nodes = gltfRuntime.nodes;
  82687. var node = nodes[jointName];
  82688. if (node) {
  82689. return {
  82690. node: node,
  82691. id: jointName
  82692. };
  82693. }
  82694. for (var nde in nodes) {
  82695. node = nodes[nde];
  82696. if (node.jointName === jointName) {
  82697. return {
  82698. node: node,
  82699. id: nde
  82700. };
  82701. }
  82702. }
  82703. return null;
  82704. };
  82705. /**
  82706. * Checks if a nodes is in joints
  82707. */
  82708. var nodeIsInJoints = function (skins, id) {
  82709. for (var i = 0; i < skins.jointNames.length; i++) {
  82710. if (skins.jointNames[i] === id) {
  82711. return true;
  82712. }
  82713. }
  82714. return false;
  82715. };
  82716. /**
  82717. * Fills the nodes to root for bones and builds hierarchy
  82718. */
  82719. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  82720. // Creates nodes for root
  82721. for (var nde in gltfRuntime.nodes) {
  82722. var node = gltfRuntime.nodes[nde];
  82723. var id = nde;
  82724. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  82725. continue;
  82726. }
  82727. // Create node to root bone
  82728. var mat = configureBoneTransformation(node);
  82729. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  82730. bone.id = id;
  82731. nodesToRoot.push({ bone: bone, node: node, id: id });
  82732. }
  82733. // Parenting
  82734. for (var i = 0; i < nodesToRoot.length; i++) {
  82735. var nodeToRoot = nodesToRoot[i];
  82736. var children = nodeToRoot.node.children;
  82737. for (var j = 0; j < children.length; j++) {
  82738. var child = null;
  82739. for (var k = 0; k < nodesToRoot.length; k++) {
  82740. if (nodesToRoot[k].id === children[j]) {
  82741. child = nodesToRoot[k];
  82742. break;
  82743. }
  82744. }
  82745. if (child) {
  82746. child.bone._parent = nodeToRoot.bone;
  82747. nodeToRoot.bone.children.push(child.bone);
  82748. }
  82749. }
  82750. }
  82751. };
  82752. /**
  82753. * Imports a skeleton
  82754. */
  82755. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  82756. if (!newSkeleton) {
  82757. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  82758. }
  82759. if (!skins.babylonSkeleton) {
  82760. return newSkeleton;
  82761. }
  82762. // Find the root bones
  82763. var nodesToRoot = [];
  82764. var nodesToRootToAdd = [];
  82765. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  82766. newSkeleton.bones = [];
  82767. // Joints
  82768. for (var i = 0; i < skins.jointNames.length; i++) {
  82769. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82770. if (!jointNode) {
  82771. continue;
  82772. }
  82773. var node = jointNode.node;
  82774. if (!node) {
  82775. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  82776. continue;
  82777. }
  82778. var id = jointNode.id;
  82779. // Optimize, if the bone already exists...
  82780. var existingBone = gltfRuntime.scene.getBoneByID(id);
  82781. if (existingBone) {
  82782. newSkeleton.bones.push(existingBone);
  82783. continue;
  82784. }
  82785. // Search for parent bone
  82786. var foundBone = false;
  82787. var parentBone = null;
  82788. for (var j = 0; j < i; j++) {
  82789. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  82790. if (!jointNode_1) {
  82791. continue;
  82792. }
  82793. var joint = jointNode_1.node;
  82794. if (!joint) {
  82795. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  82796. continue;
  82797. }
  82798. var children = joint.children;
  82799. if (!children) {
  82800. continue;
  82801. }
  82802. foundBone = false;
  82803. for (var k = 0; k < children.length; k++) {
  82804. if (children[k] === id) {
  82805. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  82806. foundBone = true;
  82807. break;
  82808. }
  82809. }
  82810. if (foundBone) {
  82811. break;
  82812. }
  82813. }
  82814. // Create bone
  82815. var mat = configureBoneTransformation(node);
  82816. if (!parentBone && nodesToRoot.length > 0) {
  82817. parentBone = getNodeToRoot(nodesToRoot, id);
  82818. if (parentBone) {
  82819. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  82820. nodesToRootToAdd.push(parentBone);
  82821. }
  82822. }
  82823. }
  82824. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  82825. bone.id = id;
  82826. }
  82827. // Polish
  82828. var bones = newSkeleton.bones;
  82829. newSkeleton.bones = [];
  82830. for (var i = 0; i < skins.jointNames.length; i++) {
  82831. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  82832. if (!jointNode) {
  82833. continue;
  82834. }
  82835. for (var j = 0; j < bones.length; j++) {
  82836. if (bones[j].id === jointNode.id) {
  82837. newSkeleton.bones.push(bones[j]);
  82838. break;
  82839. }
  82840. }
  82841. }
  82842. newSkeleton.prepare();
  82843. // Finish
  82844. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  82845. newSkeleton.bones.push(nodesToRootToAdd[i]);
  82846. }
  82847. return newSkeleton;
  82848. };
  82849. /**
  82850. * Imports a mesh and its geometries
  82851. */
  82852. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  82853. if (!newMesh) {
  82854. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  82855. newMesh.id = id;
  82856. }
  82857. if (!node.babylonNode) {
  82858. return newMesh;
  82859. }
  82860. var subMaterials = [];
  82861. var vertexData = new BABYLON.VertexData();
  82862. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  82863. var verticesStarts = new Array();
  82864. var verticesCounts = new Array();
  82865. var indexStarts = new Array();
  82866. var indexCounts = new Array();
  82867. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82868. var meshID = meshes[meshIndex];
  82869. var mesh = gltfRuntime.meshes[meshID];
  82870. if (!mesh) {
  82871. continue;
  82872. }
  82873. // Positions, normals and UVs
  82874. for (var i = 0; i < mesh.primitives.length; i++) {
  82875. // Temporary vertex data
  82876. var tempVertexData = new BABYLON.VertexData();
  82877. var primitive = mesh.primitives[i];
  82878. if (primitive.mode !== 4) {
  82879. // continue;
  82880. }
  82881. var attributes = primitive.attributes;
  82882. var accessor = null;
  82883. var buffer = null;
  82884. // Set positions, normal and uvs
  82885. for (var semantic in attributes) {
  82886. // Link accessor and buffer view
  82887. accessor = gltfRuntime.accessors[attributes[semantic]];
  82888. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82889. if (semantic === "NORMAL") {
  82890. tempVertexData.normals = new Float32Array(buffer.length);
  82891. tempVertexData.normals.set(buffer);
  82892. }
  82893. else if (semantic === "POSITION") {
  82894. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  82895. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  82896. for (var j = 0; j < buffer.length; j += 4) {
  82897. tempVertexData.positions[j] = buffer[j];
  82898. tempVertexData.positions[j + 1] = buffer[j + 1];
  82899. tempVertexData.positions[j + 2] = buffer[j + 2];
  82900. }
  82901. }
  82902. else {
  82903. tempVertexData.positions = new Float32Array(buffer.length);
  82904. tempVertexData.positions.set(buffer);
  82905. }
  82906. verticesCounts.push(tempVertexData.positions.length);
  82907. }
  82908. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  82909. var channel = Number(semantic.split("_")[1]);
  82910. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  82911. var uvs = new Float32Array(buffer.length);
  82912. uvs.set(buffer);
  82913. normalizeUVs(uvs);
  82914. tempVertexData.set(uvs, uvKind);
  82915. }
  82916. else if (semantic === "JOINT") {
  82917. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  82918. tempVertexData.matricesIndices.set(buffer);
  82919. }
  82920. else if (semantic === "WEIGHT") {
  82921. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  82922. tempVertexData.matricesWeights.set(buffer);
  82923. }
  82924. else if (semantic === "COLOR") {
  82925. tempVertexData.colors = new Float32Array(buffer.length);
  82926. tempVertexData.colors.set(buffer);
  82927. }
  82928. }
  82929. // Indices
  82930. accessor = gltfRuntime.accessors[primitive.indices];
  82931. if (accessor) {
  82932. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  82933. tempVertexData.indices = new Int32Array(buffer.length);
  82934. tempVertexData.indices.set(buffer);
  82935. indexCounts.push(tempVertexData.indices.length);
  82936. }
  82937. else {
  82938. // Set indices on the fly
  82939. var indices = [];
  82940. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  82941. indices.push(j);
  82942. }
  82943. tempVertexData.indices = new Int32Array(indices);
  82944. indexCounts.push(tempVertexData.indices.length);
  82945. }
  82946. vertexData.merge(tempVertexData);
  82947. // Sub material
  82948. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  82949. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  82950. // Update vertices start and index start
  82951. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  82952. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  82953. }
  82954. }
  82955. var material;
  82956. if (subMaterials.length > 1) {
  82957. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  82958. material.subMaterials = subMaterials;
  82959. }
  82960. else {
  82961. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  82962. }
  82963. if (subMaterials.length === 1) {
  82964. material = subMaterials[0];
  82965. }
  82966. if (!newMesh.material) {
  82967. newMesh.material = material;
  82968. }
  82969. // Apply geometry
  82970. geometry.setAllVerticesData(vertexData, false);
  82971. newMesh.computeWorldMatrix(true);
  82972. // Apply submeshes
  82973. newMesh.subMeshes = [];
  82974. var index = 0;
  82975. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  82976. var meshID = meshes[meshIndex];
  82977. var mesh = gltfRuntime.meshes[meshID];
  82978. if (!mesh) {
  82979. continue;
  82980. }
  82981. for (var i = 0; i < mesh.primitives.length; i++) {
  82982. if (mesh.primitives[i].mode !== 4) {
  82983. //continue;
  82984. }
  82985. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  82986. index++;
  82987. }
  82988. }
  82989. // Finish
  82990. return newMesh;
  82991. };
  82992. /**
  82993. * Configure node transformation from position, rotation and scaling
  82994. */
  82995. var configureNode = function (newNode, position, rotation, scaling) {
  82996. if (newNode.position) {
  82997. newNode.position = position;
  82998. }
  82999. if (newNode.rotationQuaternion || newNode.rotation) {
  83000. newNode.rotationQuaternion = rotation;
  83001. }
  83002. if (newNode.scaling) {
  83003. newNode.scaling = scaling;
  83004. }
  83005. };
  83006. /**
  83007. * Configures node from transformation matrix
  83008. */
  83009. var configureNodeFromMatrix = function (newNode, node, parent) {
  83010. if (node.matrix) {
  83011. var position = new BABYLON.Vector3(0, 0, 0);
  83012. var rotation = new BABYLON.Quaternion();
  83013. var scaling = new BABYLON.Vector3(0, 0, 0);
  83014. var mat = BABYLON.Matrix.FromArray(node.matrix);
  83015. mat.decompose(scaling, rotation, position);
  83016. configureNode(newNode, position, rotation, scaling);
  83017. }
  83018. else if (node.translation && node.rotation && node.scale) {
  83019. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  83020. }
  83021. newNode.computeWorldMatrix(true);
  83022. };
  83023. /**
  83024. * Imports a node
  83025. */
  83026. var importNode = function (gltfRuntime, node, id, parent) {
  83027. var lastNode = null;
  83028. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  83029. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  83030. return null;
  83031. }
  83032. }
  83033. // Meshes
  83034. if (node.skin) {
  83035. if (node.meshes) {
  83036. var skin = gltfRuntime.skins[node.skin];
  83037. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  83038. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  83039. if (newMesh.skeleton === null) {
  83040. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  83041. if (!skin.babylonSkeleton) {
  83042. skin.babylonSkeleton = newMesh.skeleton;
  83043. }
  83044. }
  83045. lastNode = newMesh;
  83046. }
  83047. }
  83048. else if (node.meshes) {
  83049. /**
  83050. * Improve meshes property
  83051. */
  83052. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  83053. lastNode = newMesh;
  83054. }
  83055. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  83056. var light = gltfRuntime.lights[node.light];
  83057. if (light) {
  83058. if (light.type === "ambient") {
  83059. var ambienLight = light[light.type];
  83060. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83061. hemiLight.name = node.name || "";
  83062. if (ambienLight.color) {
  83063. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  83064. }
  83065. lastNode = hemiLight;
  83066. }
  83067. else if (light.type === "directional") {
  83068. var directionalLight = light[light.type];
  83069. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83070. dirLight.name = node.name || "";
  83071. if (directionalLight.color) {
  83072. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  83073. }
  83074. lastNode = dirLight;
  83075. }
  83076. else if (light.type === "point") {
  83077. var pointLight = light[light.type];
  83078. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83079. ptLight.name = node.name || "";
  83080. if (pointLight.color) {
  83081. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  83082. }
  83083. lastNode = ptLight;
  83084. }
  83085. else if (light.type === "spot") {
  83086. var spotLight = light[light.type];
  83087. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  83088. spLight.name = node.name || "";
  83089. if (spotLight.color) {
  83090. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  83091. }
  83092. if (spotLight.fallOfAngle) {
  83093. spLight.angle = spotLight.fallOfAngle;
  83094. }
  83095. if (spotLight.fallOffExponent) {
  83096. spLight.exponent = spotLight.fallOffExponent;
  83097. }
  83098. lastNode = spLight;
  83099. }
  83100. }
  83101. }
  83102. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  83103. var camera = gltfRuntime.cameras[node.camera];
  83104. if (camera) {
  83105. if (camera.type === "orthographic") {
  83106. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83107. orthoCamera.name = node.name || "";
  83108. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  83109. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  83110. lastNode = orthoCamera;
  83111. }
  83112. else if (camera.type === "perspective") {
  83113. var perspectiveCamera = camera[camera.type];
  83114. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  83115. persCamera.name = node.name || "";
  83116. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  83117. if (!perspectiveCamera.aspectRatio) {
  83118. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  83119. }
  83120. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  83121. persCamera.maxZ = perspectiveCamera.zfar;
  83122. persCamera.minZ = perspectiveCamera.znear;
  83123. }
  83124. lastNode = persCamera;
  83125. }
  83126. }
  83127. }
  83128. // Empty node
  83129. if (!node.jointName) {
  83130. if (node.babylonNode) {
  83131. return node.babylonNode;
  83132. }
  83133. else if (lastNode === null) {
  83134. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  83135. node.babylonNode = dummy;
  83136. lastNode = dummy;
  83137. }
  83138. }
  83139. if (lastNode !== null) {
  83140. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  83141. configureNodeFromMatrix(lastNode, node, parent);
  83142. }
  83143. else {
  83144. var translation = node.translation || [0, 0, 0];
  83145. var rotation = node.rotation || [0, 0, 0, 1];
  83146. var scale = node.scale || [1, 1, 1];
  83147. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  83148. }
  83149. lastNode.updateCache(true);
  83150. node.babylonNode = lastNode;
  83151. }
  83152. return lastNode;
  83153. };
  83154. /**
  83155. * Traverses nodes and creates them
  83156. */
  83157. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  83158. if (meshIncluded === void 0) { meshIncluded = false; }
  83159. var node = gltfRuntime.nodes[id];
  83160. var newNode = null;
  83161. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  83162. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  83163. meshIncluded = true;
  83164. }
  83165. else {
  83166. meshIncluded = false;
  83167. }
  83168. }
  83169. else {
  83170. meshIncluded = true;
  83171. }
  83172. if (!node.jointName && meshIncluded) {
  83173. newNode = importNode(gltfRuntime, node, id, parent);
  83174. if (newNode !== null) {
  83175. newNode.id = id;
  83176. newNode.parent = parent;
  83177. }
  83178. }
  83179. if (node.children) {
  83180. for (var i = 0; i < node.children.length; i++) {
  83181. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  83182. }
  83183. }
  83184. };
  83185. /**
  83186. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  83187. */
  83188. var postLoad = function (gltfRuntime) {
  83189. // Nodes
  83190. var currentScene = gltfRuntime.currentScene;
  83191. if (currentScene) {
  83192. for (var i = 0; i < currentScene.nodes.length; i++) {
  83193. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83194. }
  83195. }
  83196. else {
  83197. for (var thing in gltfRuntime.scenes) {
  83198. currentScene = gltfRuntime.scenes[thing];
  83199. for (var i = 0; i < currentScene.nodes.length; i++) {
  83200. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83201. }
  83202. }
  83203. }
  83204. // Set animations
  83205. loadAnimations(gltfRuntime);
  83206. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  83207. var skeleton = gltfRuntime.scene.skeletons[i];
  83208. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  83209. }
  83210. };
  83211. /**
  83212. * onBind shaderrs callback to set uniforms and matrices
  83213. */
  83214. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  83215. var materialValues = material.values || technique.parameters;
  83216. for (var unif in unTreatedUniforms) {
  83217. var uniform = unTreatedUniforms[unif];
  83218. var type = uniform.type;
  83219. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  83220. if (uniform.semantic && !uniform.source && !uniform.node) {
  83221. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  83222. }
  83223. else if (uniform.semantic && (uniform.source || uniform.node)) {
  83224. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  83225. if (source === null) {
  83226. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  83227. }
  83228. if (source === null) {
  83229. continue;
  83230. }
  83231. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  83232. }
  83233. }
  83234. else {
  83235. var value = materialValues[technique.uniforms[unif]];
  83236. if (!value) {
  83237. continue;
  83238. }
  83239. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83240. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  83241. if (texture === null || texture === undefined) {
  83242. continue;
  83243. }
  83244. shaderMaterial.getEffect().setTexture(unif, texture);
  83245. }
  83246. else {
  83247. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  83248. }
  83249. }
  83250. }
  83251. onSuccess(shaderMaterial);
  83252. };
  83253. /**
  83254. * Prepare uniforms to send the only one time
  83255. * Loads the appropriate textures
  83256. */
  83257. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  83258. var materialValues = material.values || technique.parameters;
  83259. var techniqueUniforms = technique.uniforms;
  83260. /**
  83261. * Prepare values here (not matrices)
  83262. */
  83263. for (var unif in unTreatedUniforms) {
  83264. var uniform = unTreatedUniforms[unif];
  83265. var type = uniform.type;
  83266. var value = materialValues[techniqueUniforms[unif]];
  83267. if (value === undefined) {
  83268. // In case the value is the same for all materials
  83269. value = uniform.value;
  83270. }
  83271. if (!value) {
  83272. continue;
  83273. }
  83274. var onLoadTexture = function (uniformName) {
  83275. return function (texture) {
  83276. if (uniform.value && uniformName) {
  83277. // Static uniform
  83278. shaderMaterial.setTexture(uniformName, texture);
  83279. delete unTreatedUniforms[uniformName];
  83280. }
  83281. };
  83282. };
  83283. // Texture (sampler2D)
  83284. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  83285. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  83286. }
  83287. else {
  83288. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  83289. // Static uniform
  83290. delete unTreatedUniforms[unif];
  83291. }
  83292. }
  83293. }
  83294. };
  83295. /**
  83296. * Shader compilation failed
  83297. */
  83298. var onShaderCompileError = function (program, shaderMaterial, onError) {
  83299. return function (effect, error) {
  83300. shaderMaterial.dispose(true);
  83301. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  83302. };
  83303. };
  83304. /**
  83305. * Shader compilation success
  83306. */
  83307. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  83308. return function (_) {
  83309. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  83310. shaderMaterial.onBind = function (mesh) {
  83311. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  83312. };
  83313. };
  83314. };
  83315. /**
  83316. * Returns the appropriate uniform if already handled by babylon
  83317. */
  83318. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  83319. for (var unif in technique.uniforms) {
  83320. var uniform = technique.uniforms[unif];
  83321. var uniformParameter = technique.parameters[uniform];
  83322. if (tokenizer.currentIdentifier === unif) {
  83323. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  83324. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83325. if (transformIndex !== -1) {
  83326. delete unTreatedUniforms[unif];
  83327. return babylonTransforms[transformIndex];
  83328. }
  83329. }
  83330. }
  83331. }
  83332. return tokenizer.currentIdentifier;
  83333. };
  83334. /**
  83335. * All shaders loaded. Create materials one by one
  83336. */
  83337. var importMaterials = function (gltfRuntime) {
  83338. // Create materials
  83339. for (var mat in gltfRuntime.materials) {
  83340. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  83341. }
  83342. };
  83343. /**
  83344. * Implementation of the base glTF spec
  83345. */
  83346. var GLTFLoaderBase = /** @class */ (function () {
  83347. function GLTFLoaderBase() {
  83348. }
  83349. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  83350. var gltfRuntime = {
  83351. extensions: {},
  83352. accessors: {},
  83353. buffers: {},
  83354. bufferViews: {},
  83355. meshes: {},
  83356. lights: {},
  83357. cameras: {},
  83358. nodes: {},
  83359. images: {},
  83360. textures: {},
  83361. shaders: {},
  83362. programs: {},
  83363. samplers: {},
  83364. techniques: {},
  83365. materials: {},
  83366. animations: {},
  83367. skins: {},
  83368. extensionsUsed: [],
  83369. scenes: {},
  83370. buffersCount: 0,
  83371. shaderscount: 0,
  83372. scene: scene,
  83373. rootUrl: rootUrl,
  83374. loadedBufferCount: 0,
  83375. loadedBufferViews: {},
  83376. loadedShaderCount: 0,
  83377. importOnlyMeshes: false,
  83378. dummyNodes: []
  83379. };
  83380. // Parse
  83381. if (parsedData.extensions) {
  83382. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  83383. }
  83384. if (parsedData.extensionsUsed) {
  83385. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  83386. }
  83387. if (parsedData.buffers) {
  83388. parseBuffers(parsedData.buffers, gltfRuntime);
  83389. }
  83390. if (parsedData.bufferViews) {
  83391. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  83392. }
  83393. if (parsedData.accessors) {
  83394. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  83395. }
  83396. if (parsedData.meshes) {
  83397. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  83398. }
  83399. if (parsedData.lights) {
  83400. parseObject(parsedData.lights, "lights", gltfRuntime);
  83401. }
  83402. if (parsedData.cameras) {
  83403. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  83404. }
  83405. if (parsedData.nodes) {
  83406. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  83407. }
  83408. if (parsedData.images) {
  83409. parseObject(parsedData.images, "images", gltfRuntime);
  83410. }
  83411. if (parsedData.textures) {
  83412. parseObject(parsedData.textures, "textures", gltfRuntime);
  83413. }
  83414. if (parsedData.shaders) {
  83415. parseShaders(parsedData.shaders, gltfRuntime);
  83416. }
  83417. if (parsedData.programs) {
  83418. parseObject(parsedData.programs, "programs", gltfRuntime);
  83419. }
  83420. if (parsedData.samplers) {
  83421. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  83422. }
  83423. if (parsedData.techniques) {
  83424. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  83425. }
  83426. if (parsedData.materials) {
  83427. parseObject(parsedData.materials, "materials", gltfRuntime);
  83428. }
  83429. if (parsedData.animations) {
  83430. parseObject(parsedData.animations, "animations", gltfRuntime);
  83431. }
  83432. if (parsedData.skins) {
  83433. parseObject(parsedData.skins, "skins", gltfRuntime);
  83434. }
  83435. if (parsedData.scenes) {
  83436. gltfRuntime.scenes = parsedData.scenes;
  83437. }
  83438. if (parsedData.scene && parsedData.scenes) {
  83439. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  83440. }
  83441. return gltfRuntime;
  83442. };
  83443. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  83444. var buffer = gltfRuntime.buffers[id];
  83445. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  83446. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  83447. }
  83448. else {
  83449. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  83450. if (request) {
  83451. onError(request.status + " " + request.statusText);
  83452. }
  83453. });
  83454. }
  83455. };
  83456. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  83457. var texture = gltfRuntime.textures[id];
  83458. if (!texture || !texture.source) {
  83459. onError("");
  83460. return;
  83461. }
  83462. if (texture.babylonTexture) {
  83463. onSuccess(null);
  83464. return;
  83465. }
  83466. var source = gltfRuntime.images[texture.source];
  83467. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  83468. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  83469. }
  83470. else {
  83471. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  83472. if (request) {
  83473. onError(request.status + " " + request.statusText);
  83474. }
  83475. });
  83476. }
  83477. };
  83478. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  83479. var texture = gltfRuntime.textures[id];
  83480. if (texture.babylonTexture) {
  83481. onSuccess(texture.babylonTexture);
  83482. return;
  83483. }
  83484. var sampler = gltfRuntime.samplers[texture.sampler];
  83485. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  83486. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  83487. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  83488. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  83489. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  83490. var blob = new Blob([buffer]);
  83491. var blobURL = URL.createObjectURL(blob);
  83492. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  83493. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  83494. if (sampler.wrapS !== undefined) {
  83495. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  83496. }
  83497. if (sampler.wrapT !== undefined) {
  83498. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  83499. }
  83500. newTexture.name = id;
  83501. texture.babylonTexture = newTexture;
  83502. onSuccess(newTexture);
  83503. };
  83504. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  83505. var shader = gltfRuntime.shaders[id];
  83506. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  83507. var shaderString = atob(shader.uri.split(",")[1]);
  83508. onSuccess(shaderString);
  83509. }
  83510. else {
  83511. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  83512. if (request) {
  83513. onError(request.status + " " + request.statusText);
  83514. }
  83515. });
  83516. }
  83517. };
  83518. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  83519. var material = gltfRuntime.materials[id];
  83520. if (!material.technique) {
  83521. if (onError) {
  83522. onError("No technique found.");
  83523. }
  83524. return;
  83525. }
  83526. var technique = gltfRuntime.techniques[material.technique];
  83527. if (!technique) {
  83528. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  83529. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  83530. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83531. onSuccess(defaultMaterial);
  83532. return;
  83533. }
  83534. var program = gltfRuntime.programs[technique.program];
  83535. var states = technique.states;
  83536. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  83537. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  83538. var newVertexShader = "";
  83539. var newPixelShader = "";
  83540. var vertexTokenizer = new Tokenizer(vertexShader);
  83541. var pixelTokenizer = new Tokenizer(pixelShader);
  83542. var unTreatedUniforms = {};
  83543. var uniforms = [];
  83544. var attributes = [];
  83545. var samplers = [];
  83546. // Fill uniform, sampler2D and attributes
  83547. for (var unif in technique.uniforms) {
  83548. var uniform = technique.uniforms[unif];
  83549. var uniformParameter = technique.parameters[uniform];
  83550. unTreatedUniforms[unif] = uniformParameter;
  83551. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  83552. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  83553. if (transformIndex !== -1) {
  83554. uniforms.push(babylonTransforms[transformIndex]);
  83555. delete unTreatedUniforms[unif];
  83556. }
  83557. else {
  83558. uniforms.push(unif);
  83559. }
  83560. }
  83561. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  83562. samplers.push(unif);
  83563. }
  83564. else {
  83565. uniforms.push(unif);
  83566. }
  83567. }
  83568. for (var attr in technique.attributes) {
  83569. var attribute = technique.attributes[attr];
  83570. var attributeParameter = technique.parameters[attribute];
  83571. if (attributeParameter.semantic) {
  83572. attributes.push(getAttribute(attributeParameter));
  83573. }
  83574. }
  83575. // Configure vertex shader
  83576. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  83577. var tokenType = vertexTokenizer.currentToken;
  83578. if (tokenType !== ETokenType.IDENTIFIER) {
  83579. newVertexShader += vertexTokenizer.currentString;
  83580. continue;
  83581. }
  83582. var foundAttribute = false;
  83583. for (var attr in technique.attributes) {
  83584. var attribute = technique.attributes[attr];
  83585. var attributeParameter = technique.parameters[attribute];
  83586. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  83587. newVertexShader += getAttribute(attributeParameter);
  83588. foundAttribute = true;
  83589. break;
  83590. }
  83591. }
  83592. if (foundAttribute) {
  83593. continue;
  83594. }
  83595. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  83596. }
  83597. // Configure pixel shader
  83598. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  83599. var tokenType = pixelTokenizer.currentToken;
  83600. if (tokenType !== ETokenType.IDENTIFIER) {
  83601. newPixelShader += pixelTokenizer.currentString;
  83602. continue;
  83603. }
  83604. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  83605. }
  83606. // Create shader material
  83607. var shaderPath = {
  83608. vertex: program.vertexShader + id,
  83609. fragment: program.fragmentShader + id
  83610. };
  83611. var options = {
  83612. attributes: attributes,
  83613. uniforms: uniforms,
  83614. samplers: samplers,
  83615. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  83616. };
  83617. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  83618. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  83619. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  83620. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  83621. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  83622. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  83623. if (states && states.functions) {
  83624. var functions = states.functions;
  83625. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  83626. shaderMaterial.backFaceCulling = false;
  83627. }
  83628. var blendFunc = functions.blendFuncSeparate;
  83629. if (blendFunc) {
  83630. 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) {
  83631. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  83632. }
  83633. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83634. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83635. }
  83636. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83637. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  83638. }
  83639. 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) {
  83640. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  83641. }
  83642. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  83643. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  83644. }
  83645. 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) {
  83646. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  83647. }
  83648. }
  83649. }
  83650. };
  83651. return GLTFLoaderBase;
  83652. }());
  83653. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  83654. /**
  83655. * glTF V1 Loader
  83656. */
  83657. var GLTFLoader = /** @class */ (function () {
  83658. function GLTFLoader() {
  83659. // #region Stubs for IGLTFLoader interface
  83660. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  83661. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  83662. this.compileMaterials = false;
  83663. this.useClipPlane = false;
  83664. this.compileShadowGenerators = false;
  83665. this.onDisposeObservable = new BABYLON.Observable();
  83666. this.onMeshLoadedObservable = new BABYLON.Observable();
  83667. this.onTextureLoadedObservable = new BABYLON.Observable();
  83668. this.onMaterialLoadedObservable = new BABYLON.Observable();
  83669. this.onCompleteObservable = new BABYLON.Observable();
  83670. }
  83671. GLTFLoader.RegisterExtension = function (extension) {
  83672. if (GLTFLoader.Extensions[extension.name]) {
  83673. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  83674. return;
  83675. }
  83676. GLTFLoader.Extensions[extension.name] = extension;
  83677. };
  83678. GLTFLoader.prototype.dispose = function () { };
  83679. // #endregion
  83680. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  83681. var _this = this;
  83682. scene.useRightHandedSystem = true;
  83683. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83684. gltfRuntime.importOnlyMeshes = true;
  83685. if (meshesNames === "") {
  83686. gltfRuntime.importMeshesNames = [];
  83687. }
  83688. else if (typeof meshesNames === "string") {
  83689. gltfRuntime.importMeshesNames = [meshesNames];
  83690. }
  83691. else if (meshesNames && !(meshesNames instanceof Array)) {
  83692. gltfRuntime.importMeshesNames = [meshesNames];
  83693. }
  83694. else {
  83695. gltfRuntime.importMeshesNames = [];
  83696. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  83697. }
  83698. // Create nodes
  83699. _this._createNodes(gltfRuntime);
  83700. var meshes = new Array();
  83701. var skeletons = new Array();
  83702. // Fill arrays of meshes and skeletons
  83703. for (var nde in gltfRuntime.nodes) {
  83704. var node = gltfRuntime.nodes[nde];
  83705. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  83706. meshes.push(node.babylonNode);
  83707. }
  83708. }
  83709. for (var skl in gltfRuntime.skins) {
  83710. var skin = gltfRuntime.skins[skl];
  83711. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  83712. skeletons.push(skin.babylonSkeleton);
  83713. }
  83714. }
  83715. // Load buffers, shaders, materials, etc.
  83716. _this._loadBuffersAsync(gltfRuntime, function () {
  83717. _this._loadShadersAsync(gltfRuntime, function () {
  83718. importMaterials(gltfRuntime);
  83719. postLoad(gltfRuntime);
  83720. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83721. onSuccess(meshes, [], skeletons);
  83722. }
  83723. });
  83724. }, onProgress);
  83725. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  83726. onSuccess(meshes, [], skeletons);
  83727. }
  83728. }, onError);
  83729. return true;
  83730. };
  83731. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  83732. var _this = this;
  83733. scene.useRightHandedSystem = true;
  83734. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  83735. // Load runtime extensios
  83736. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  83737. // Create nodes
  83738. _this._createNodes(gltfRuntime);
  83739. // Load buffers, shaders, materials, etc.
  83740. _this._loadBuffersAsync(gltfRuntime, function () {
  83741. _this._loadShadersAsync(gltfRuntime, function () {
  83742. importMaterials(gltfRuntime);
  83743. postLoad(gltfRuntime);
  83744. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  83745. onSuccess();
  83746. }
  83747. });
  83748. });
  83749. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  83750. onSuccess();
  83751. }
  83752. }, onError);
  83753. }, onError);
  83754. };
  83755. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  83756. var hasShaders = false;
  83757. var processShader = function (sha, shader) {
  83758. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  83759. gltfRuntime.loadedShaderCount++;
  83760. if (shaderString) {
  83761. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  83762. }
  83763. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  83764. onload();
  83765. }
  83766. }, function () {
  83767. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  83768. });
  83769. };
  83770. for (var sha in gltfRuntime.shaders) {
  83771. hasShaders = true;
  83772. var shader = gltfRuntime.shaders[sha];
  83773. if (shader) {
  83774. processShader.bind(this, sha, shader)();
  83775. }
  83776. else {
  83777. BABYLON.Tools.Error("No shader named: " + sha);
  83778. }
  83779. }
  83780. if (!hasShaders) {
  83781. onload();
  83782. }
  83783. };
  83784. ;
  83785. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  83786. var hasBuffers = false;
  83787. var processBuffer = function (buf, buffer) {
  83788. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  83789. gltfRuntime.loadedBufferCount++;
  83790. if (bufferView) {
  83791. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  83792. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  83793. }
  83794. gltfRuntime.loadedBufferViews[buf] = bufferView;
  83795. }
  83796. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  83797. onLoad();
  83798. }
  83799. }, function () {
  83800. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  83801. });
  83802. };
  83803. for (var buf in gltfRuntime.buffers) {
  83804. hasBuffers = true;
  83805. var buffer = gltfRuntime.buffers[buf];
  83806. if (buffer) {
  83807. processBuffer.bind(this, buf, buffer)();
  83808. }
  83809. else {
  83810. BABYLON.Tools.Error("No buffer named: " + buf);
  83811. }
  83812. }
  83813. if (!hasBuffers) {
  83814. onLoad();
  83815. }
  83816. };
  83817. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  83818. var currentScene = gltfRuntime.currentScene;
  83819. if (currentScene) {
  83820. // Only one scene even if multiple scenes are defined
  83821. for (var i = 0; i < currentScene.nodes.length; i++) {
  83822. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83823. }
  83824. }
  83825. else {
  83826. // Load all scenes
  83827. for (var thing in gltfRuntime.scenes) {
  83828. currentScene = gltfRuntime.scenes[thing];
  83829. for (var i = 0; i < currentScene.nodes.length; i++) {
  83830. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  83831. }
  83832. }
  83833. }
  83834. };
  83835. GLTFLoader.Extensions = {};
  83836. return GLTFLoader;
  83837. }());
  83838. GLTF1.GLTFLoader = GLTFLoader;
  83839. ;
  83840. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  83841. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  83842. })(BABYLON || (BABYLON = {}));
  83843. //# sourceMappingURL=babylon.glTFLoader.js.map
  83844. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  83845. var BABYLON;
  83846. (function (BABYLON) {
  83847. var GLTF1;
  83848. (function (GLTF1) {
  83849. /**
  83850. * Utils functions for GLTF
  83851. */
  83852. var GLTFUtils = /** @class */ (function () {
  83853. function GLTFUtils() {
  83854. }
  83855. /**
  83856. * Sets the given "parameter" matrix
  83857. * @param scene: the {BABYLON.Scene} object
  83858. * @param source: the source node where to pick the matrix
  83859. * @param parameter: the GLTF technique parameter
  83860. * @param uniformName: the name of the shader's uniform
  83861. * @param shaderMaterial: the shader material
  83862. */
  83863. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  83864. var mat = null;
  83865. if (parameter.semantic === "MODEL") {
  83866. mat = source.getWorldMatrix();
  83867. }
  83868. else if (parameter.semantic === "PROJECTION") {
  83869. mat = scene.getProjectionMatrix();
  83870. }
  83871. else if (parameter.semantic === "VIEW") {
  83872. mat = scene.getViewMatrix();
  83873. }
  83874. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  83875. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  83876. }
  83877. else if (parameter.semantic === "MODELVIEW") {
  83878. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  83879. }
  83880. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  83881. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  83882. }
  83883. else if (parameter.semantic === "MODELINVERSE") {
  83884. mat = source.getWorldMatrix().invert();
  83885. }
  83886. else if (parameter.semantic === "VIEWINVERSE") {
  83887. mat = scene.getViewMatrix().invert();
  83888. }
  83889. else if (parameter.semantic === "PROJECTIONINVERSE") {
  83890. mat = scene.getProjectionMatrix().invert();
  83891. }
  83892. else if (parameter.semantic === "MODELVIEWINVERSE") {
  83893. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  83894. }
  83895. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  83896. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  83897. }
  83898. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  83899. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  83900. }
  83901. else {
  83902. debugger;
  83903. }
  83904. if (mat) {
  83905. switch (parameter.type) {
  83906. case GLTF1.EParameterType.FLOAT_MAT2:
  83907. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  83908. break;
  83909. case GLTF1.EParameterType.FLOAT_MAT3:
  83910. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  83911. break;
  83912. case GLTF1.EParameterType.FLOAT_MAT4:
  83913. shaderMaterial.setMatrix(uniformName, mat);
  83914. break;
  83915. default: break;
  83916. }
  83917. }
  83918. };
  83919. /**
  83920. * Sets the given "parameter" matrix
  83921. * @param shaderMaterial: the shader material
  83922. * @param uniform: the name of the shader's uniform
  83923. * @param value: the value of the uniform
  83924. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  83925. */
  83926. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  83927. switch (type) {
  83928. case GLTF1.EParameterType.FLOAT:
  83929. shaderMaterial.setFloat(uniform, value);
  83930. return true;
  83931. case GLTF1.EParameterType.FLOAT_VEC2:
  83932. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  83933. return true;
  83934. case GLTF1.EParameterType.FLOAT_VEC3:
  83935. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  83936. return true;
  83937. case GLTF1.EParameterType.FLOAT_VEC4:
  83938. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  83939. return true;
  83940. default: return false;
  83941. }
  83942. };
  83943. /**
  83944. * If the uri is a base64 string
  83945. * @param uri: the uri to test
  83946. */
  83947. GLTFUtils.IsBase64 = function (uri) {
  83948. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  83949. };
  83950. /**
  83951. * Decode the base64 uri
  83952. * @param uri: the uri to decode
  83953. */
  83954. GLTFUtils.DecodeBase64 = function (uri) {
  83955. var decodedString = atob(uri.split(",")[1]);
  83956. var bufferLength = decodedString.length;
  83957. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  83958. for (var i = 0; i < bufferLength; i++) {
  83959. bufferView[i] = decodedString.charCodeAt(i);
  83960. }
  83961. return bufferView.buffer;
  83962. };
  83963. /**
  83964. * Returns the wrap mode of the texture
  83965. * @param mode: the mode value
  83966. */
  83967. GLTFUtils.GetWrapMode = function (mode) {
  83968. switch (mode) {
  83969. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  83970. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  83971. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83972. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  83973. }
  83974. };
  83975. /**
  83976. * Returns the byte stride giving an accessor
  83977. * @param accessor: the GLTF accessor objet
  83978. */
  83979. GLTFUtils.GetByteStrideFromType = function (accessor) {
  83980. // Needs this function since "byteStride" isn't requiered in glTF format
  83981. var type = accessor.type;
  83982. switch (type) {
  83983. case "VEC2": return 2;
  83984. case "VEC3": return 3;
  83985. case "VEC4": return 4;
  83986. case "MAT2": return 4;
  83987. case "MAT3": return 9;
  83988. case "MAT4": return 16;
  83989. default: return 1;
  83990. }
  83991. };
  83992. /**
  83993. * Returns the texture filter mode giving a mode value
  83994. * @param mode: the filter mode value
  83995. */
  83996. GLTFUtils.GetTextureFilterMode = function (mode) {
  83997. switch (mode) {
  83998. case GLTF1.ETextureFilterType.LINEAR:
  83999. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  84000. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  84001. case GLTF1.ETextureFilterType.NEAREST:
  84002. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  84003. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  84004. }
  84005. };
  84006. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  84007. var byteOffset = bufferView.byteOffset + byteOffset;
  84008. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  84009. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  84010. throw new Error("Buffer access is out of range");
  84011. }
  84012. var buffer = loadedBufferView.buffer;
  84013. byteOffset += loadedBufferView.byteOffset;
  84014. switch (componentType) {
  84015. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  84016. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  84017. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  84018. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  84019. default: return new Float32Array(buffer, byteOffset, byteLength);
  84020. }
  84021. };
  84022. /**
  84023. * Returns a buffer from its accessor
  84024. * @param gltfRuntime: the GLTF runtime
  84025. * @param accessor: the GLTF accessor
  84026. */
  84027. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  84028. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  84029. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  84030. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  84031. };
  84032. /**
  84033. * Decodes a buffer view into a string
  84034. * @param view: the buffer view
  84035. */
  84036. GLTFUtils.DecodeBufferToText = function (view) {
  84037. var result = "";
  84038. var length = view.byteLength;
  84039. for (var i = 0; i < length; ++i) {
  84040. result += String.fromCharCode(view[i]);
  84041. }
  84042. return result;
  84043. };
  84044. /**
  84045. * Returns the default material of gltf. Related to
  84046. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  84047. * @param scene: the Babylon.js scene
  84048. */
  84049. GLTFUtils.GetDefaultMaterial = function (scene) {
  84050. if (!GLTFUtils._DefaultMaterial) {
  84051. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  84052. "precision highp float;",
  84053. "",
  84054. "uniform mat4 worldView;",
  84055. "uniform mat4 projection;",
  84056. "",
  84057. "attribute vec3 position;",
  84058. "",
  84059. "void main(void)",
  84060. "{",
  84061. " gl_Position = projection * worldView * vec4(position, 1.0);",
  84062. "}"
  84063. ].join("\n");
  84064. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  84065. "precision highp float;",
  84066. "",
  84067. "uniform vec4 u_emission;",
  84068. "",
  84069. "void main(void)",
  84070. "{",
  84071. " gl_FragColor = u_emission;",
  84072. "}"
  84073. ].join("\n");
  84074. var shaderPath = {
  84075. vertex: "GLTFDefaultMaterial",
  84076. fragment: "GLTFDefaultMaterial"
  84077. };
  84078. var options = {
  84079. attributes: ["position"],
  84080. uniforms: ["worldView", "projection", "u_emission"],
  84081. samplers: new Array(),
  84082. needAlphaBlending: false
  84083. };
  84084. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  84085. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  84086. }
  84087. return GLTFUtils._DefaultMaterial;
  84088. };
  84089. // The GLTF default material
  84090. GLTFUtils._DefaultMaterial = null;
  84091. return GLTFUtils;
  84092. }());
  84093. GLTF1.GLTFUtils = GLTFUtils;
  84094. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84095. })(BABYLON || (BABYLON = {}));
  84096. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  84097. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84098. var BABYLON;
  84099. (function (BABYLON) {
  84100. var GLTF1;
  84101. (function (GLTF1) {
  84102. var GLTFLoaderExtension = /** @class */ (function () {
  84103. function GLTFLoaderExtension(name) {
  84104. this._name = name;
  84105. }
  84106. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  84107. get: function () {
  84108. return this._name;
  84109. },
  84110. enumerable: true,
  84111. configurable: true
  84112. });
  84113. /**
  84114. * Defines an override for loading the runtime
  84115. * Return true to stop further extensions from loading the runtime
  84116. */
  84117. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84118. return false;
  84119. };
  84120. /**
  84121. * Defines an onverride for creating gltf runtime
  84122. * Return true to stop further extensions from creating the runtime
  84123. */
  84124. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84125. return false;
  84126. };
  84127. /**
  84128. * Defines an override for loading buffers
  84129. * Return true to stop further extensions from loading this buffer
  84130. */
  84131. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  84132. return false;
  84133. };
  84134. /**
  84135. * Defines an override for loading texture buffers
  84136. * Return true to stop further extensions from loading this texture data
  84137. */
  84138. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84139. return false;
  84140. };
  84141. /**
  84142. * Defines an override for creating textures
  84143. * Return true to stop further extensions from loading this texture
  84144. */
  84145. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  84146. return false;
  84147. };
  84148. /**
  84149. * Defines an override for loading shader strings
  84150. * Return true to stop further extensions from loading this shader data
  84151. */
  84152. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84153. return false;
  84154. };
  84155. /**
  84156. * Defines an override for loading materials
  84157. * Return true to stop further extensions from loading this material
  84158. */
  84159. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84160. return false;
  84161. };
  84162. // ---------
  84163. // Utilities
  84164. // ---------
  84165. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84166. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84167. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  84168. }, function () {
  84169. setTimeout(function () {
  84170. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  84171. });
  84172. });
  84173. };
  84174. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84175. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84176. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  84177. }, function () {
  84178. setTimeout(function () {
  84179. onSuccess();
  84180. });
  84181. });
  84182. };
  84183. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  84184. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84185. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  84186. }, function () {
  84187. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  84188. });
  84189. };
  84190. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  84191. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  84192. };
  84193. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84194. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84195. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84196. }, function () {
  84197. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  84198. });
  84199. };
  84200. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84201. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84202. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84203. }, function () {
  84204. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  84205. });
  84206. };
  84207. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84208. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84209. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84210. }, function () {
  84211. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  84212. });
  84213. };
  84214. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  84215. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  84216. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84217. }, function () {
  84218. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  84219. });
  84220. };
  84221. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  84222. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  84223. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  84224. if (func(loaderExtension)) {
  84225. return;
  84226. }
  84227. }
  84228. defaultFunc();
  84229. };
  84230. return GLTFLoaderExtension;
  84231. }());
  84232. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  84233. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84234. })(BABYLON || (BABYLON = {}));
  84235. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  84236. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84237. var BABYLON;
  84238. (function (BABYLON) {
  84239. var GLTF1;
  84240. (function (GLTF1) {
  84241. var BinaryExtensionBufferName = "binary_glTF";
  84242. ;
  84243. ;
  84244. var GLTFBinaryExtension = /** @class */ (function (_super) {
  84245. __extends(GLTFBinaryExtension, _super);
  84246. function GLTFBinaryExtension() {
  84247. return _super.call(this, "KHR_binary_glTF") || this;
  84248. }
  84249. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  84250. var extensionsUsed = data.json.extensionsUsed;
  84251. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  84252. return false;
  84253. }
  84254. this._bin = data.bin;
  84255. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  84256. return true;
  84257. };
  84258. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84259. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  84260. return false;
  84261. }
  84262. if (id !== BinaryExtensionBufferName) {
  84263. return false;
  84264. }
  84265. onSuccess(this._bin);
  84266. return true;
  84267. };
  84268. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  84269. var texture = gltfRuntime.textures[id];
  84270. var source = gltfRuntime.images[texture.source];
  84271. if (!source.extensions || !(this.name in source.extensions)) {
  84272. return false;
  84273. }
  84274. var sourceExt = source.extensions[this.name];
  84275. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  84276. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84277. onSuccess(buffer);
  84278. return true;
  84279. };
  84280. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  84281. var shader = gltfRuntime.shaders[id];
  84282. if (!shader.extensions || !(this.name in shader.extensions)) {
  84283. return false;
  84284. }
  84285. var binaryExtensionShader = shader.extensions[this.name];
  84286. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  84287. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  84288. setTimeout(function () {
  84289. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  84290. onSuccess(shaderString);
  84291. });
  84292. return true;
  84293. };
  84294. return GLTFBinaryExtension;
  84295. }(GLTF1.GLTFLoaderExtension));
  84296. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  84297. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  84298. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84299. })(BABYLON || (BABYLON = {}));
  84300. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  84301. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84302. var BABYLON;
  84303. (function (BABYLON) {
  84304. var GLTF1;
  84305. (function (GLTF1) {
  84306. ;
  84307. ;
  84308. ;
  84309. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  84310. __extends(GLTFMaterialsCommonExtension, _super);
  84311. function GLTFMaterialsCommonExtension() {
  84312. return _super.call(this, "KHR_materials_common") || this;
  84313. }
  84314. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  84315. if (!gltfRuntime.extensions)
  84316. return false;
  84317. var extension = gltfRuntime.extensions[this.name];
  84318. if (!extension)
  84319. return false;
  84320. // Create lights
  84321. var lights = extension.lights;
  84322. if (lights) {
  84323. for (var thing in lights) {
  84324. var light = lights[thing];
  84325. switch (light.type) {
  84326. case "ambient":
  84327. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  84328. var ambient = light.ambient;
  84329. if (ambient) {
  84330. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  84331. }
  84332. break;
  84333. case "point":
  84334. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  84335. var point = light.point;
  84336. if (point) {
  84337. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  84338. }
  84339. break;
  84340. case "directional":
  84341. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  84342. var directional = light.directional;
  84343. if (directional) {
  84344. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  84345. }
  84346. break;
  84347. case "spot":
  84348. var spot = light.spot;
  84349. if (spot) {
  84350. 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);
  84351. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  84352. }
  84353. break;
  84354. default:
  84355. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  84356. break;
  84357. }
  84358. }
  84359. }
  84360. return false;
  84361. };
  84362. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  84363. var material = gltfRuntime.materials[id];
  84364. if (!material || !material.extensions)
  84365. return false;
  84366. var extension = material.extensions[this.name];
  84367. if (!extension)
  84368. return false;
  84369. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  84370. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  84371. if (extension.technique === "CONSTANT") {
  84372. standardMaterial.disableLighting = true;
  84373. }
  84374. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  84375. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  84376. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  84377. // Ambient
  84378. if (typeof extension.values.ambient === "string") {
  84379. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  84380. }
  84381. else {
  84382. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  84383. }
  84384. // Diffuse
  84385. if (typeof extension.values.diffuse === "string") {
  84386. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  84387. }
  84388. else {
  84389. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  84390. }
  84391. // Emission
  84392. if (typeof extension.values.emission === "string") {
  84393. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  84394. }
  84395. else {
  84396. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  84397. }
  84398. // Specular
  84399. if (typeof extension.values.specular === "string") {
  84400. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  84401. }
  84402. else {
  84403. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  84404. }
  84405. return true;
  84406. };
  84407. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  84408. // Create buffer from texture url
  84409. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  84410. // Create texture from buffer
  84411. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  84412. }, onError);
  84413. };
  84414. return GLTFMaterialsCommonExtension;
  84415. }(GLTF1.GLTFLoaderExtension));
  84416. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  84417. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  84418. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  84419. })(BABYLON || (BABYLON = {}));
  84420. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  84421. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84422. var BABYLON;
  84423. (function (BABYLON) {
  84424. var GLTF2;
  84425. (function (GLTF2) {
  84426. /**
  84427. * Enums
  84428. */
  84429. var EComponentType;
  84430. (function (EComponentType) {
  84431. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  84432. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  84433. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  84434. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  84435. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  84436. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  84437. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  84438. var EMeshPrimitiveMode;
  84439. (function (EMeshPrimitiveMode) {
  84440. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  84441. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  84442. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  84443. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  84444. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  84445. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  84446. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  84447. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  84448. var ETextureMagFilter;
  84449. (function (ETextureMagFilter) {
  84450. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  84451. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  84452. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  84453. var ETextureMinFilter;
  84454. (function (ETextureMinFilter) {
  84455. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  84456. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  84457. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  84458. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  84459. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  84460. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  84461. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  84462. var ETextureWrapMode;
  84463. (function (ETextureWrapMode) {
  84464. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  84465. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  84466. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  84467. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  84468. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  84469. })(BABYLON || (BABYLON = {}));
  84470. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  84471. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  84472. var BABYLON;
  84473. (function (BABYLON) {
  84474. var GLTF2;
  84475. (function (GLTF2) {
  84476. var GLTFLoaderTracker = /** @class */ (function () {
  84477. function GLTFLoaderTracker(onComplete) {
  84478. this._pendingCount = 0;
  84479. this._callback = onComplete;
  84480. }
  84481. GLTFLoaderTracker.prototype._addPendingData = function (data) {
  84482. this._pendingCount++;
  84483. };
  84484. GLTFLoaderTracker.prototype._removePendingData = function (data) {
  84485. if (--this._pendingCount === 0) {
  84486. this._callback();
  84487. }
  84488. };
  84489. return GLTFLoaderTracker;
  84490. }());
  84491. var GLTFLoader = /** @class */ (function () {
  84492. function GLTFLoader() {
  84493. this._disposed = false;
  84494. this._defaultSampler = {};
  84495. this._renderReady = false;
  84496. this._requests = new Array();
  84497. this._renderReadyObservable = new BABYLON.Observable();
  84498. // Count of pending work that needs to complete before the asset is rendered.
  84499. this._renderPendingCount = 0;
  84500. // Count of pending work that needs to complete before the loader is disposed.
  84501. this._loaderPendingCount = 0;
  84502. this._loaderTrackers = new Array();
  84503. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  84504. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  84505. this.compileMaterials = false;
  84506. this.useClipPlane = false;
  84507. this.compileShadowGenerators = false;
  84508. this.onDisposeObservable = new BABYLON.Observable();
  84509. this.onMeshLoadedObservable = new BABYLON.Observable();
  84510. this.onTextureLoadedObservable = new BABYLON.Observable();
  84511. this.onMaterialLoadedObservable = new BABYLON.Observable();
  84512. this.onCompleteObservable = new BABYLON.Observable();
  84513. }
  84514. GLTFLoader.RegisterExtension = function (extension) {
  84515. if (GLTFLoader.Extensions[extension.name]) {
  84516. BABYLON.Tools.Error("Extension with the same name '" + extension.name + "' already exists");
  84517. return;
  84518. }
  84519. GLTFLoader.Extensions[extension.name] = extension;
  84520. // Keep the order of registration so that extensions registered first are called first.
  84521. GLTF2.GLTFLoaderExtension._Extensions.push(extension);
  84522. };
  84523. GLTFLoader.prototype.dispose = function () {
  84524. if (this._disposed) {
  84525. return;
  84526. }
  84527. this._disposed = true;
  84528. this._abortRequests();
  84529. this._releaseResources();
  84530. this.onDisposeObservable.notifyObservers(this);
  84531. };
  84532. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84533. var _this = this;
  84534. this._loadAsync(meshesNames, scene, data, rootUrl, function () {
  84535. if (onSuccess) {
  84536. onSuccess(_this._getMeshes(), [], _this._getSkeletons());
  84537. }
  84538. }, onProgress, onError);
  84539. };
  84540. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  84541. this._loadAsync(null, scene, data, rootUrl, onSuccess, onProgress, onError);
  84542. };
  84543. GLTFLoader.prototype._loadAsync = function (nodeNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  84544. var _this = this;
  84545. this._babylonScene = scene;
  84546. this._rootUrl = rootUrl;
  84547. this._successCallback = onSuccess;
  84548. this._progressCallback = onProgress;
  84549. this._errorCallback = onError;
  84550. this._tryCatchOnError(function () {
  84551. _this._loadData(data);
  84552. _this._addPendingData(_this);
  84553. _this._loadDefaultScene(nodeNames);
  84554. _this._loadAnimations();
  84555. _this._removePendingData(_this);
  84556. });
  84557. };
  84558. GLTFLoader.prototype._onProgress = function () {
  84559. if (!this._progressCallback) {
  84560. return;
  84561. }
  84562. var lengthComputable = true;
  84563. var loaded = 0;
  84564. var total = 0;
  84565. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  84566. var request = _a[_i];
  84567. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  84568. return;
  84569. }
  84570. lengthComputable = lengthComputable && request._lengthComputable;
  84571. loaded += request._loaded;
  84572. total += request._total;
  84573. }
  84574. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  84575. };
  84576. GLTFLoader.prototype._executeWhenRenderReady = function (func) {
  84577. if (this._renderReady) {
  84578. func();
  84579. }
  84580. else {
  84581. this._renderReadyObservable.add(func);
  84582. }
  84583. };
  84584. GLTFLoader.prototype._onRenderReady = function () {
  84585. this._rootNode.babylonMesh.setEnabled(true);
  84586. this._startAnimations();
  84587. if (this._successCallback) {
  84588. this._successCallback();
  84589. }
  84590. this._renderReadyObservable.notifyObservers(this);
  84591. };
  84592. GLTFLoader.prototype._onComplete = function () {
  84593. this._abortRequests();
  84594. this._releaseResources();
  84595. this.onCompleteObservable.notifyObservers(this);
  84596. };
  84597. GLTFLoader.prototype._loadData = function (data) {
  84598. this._gltf = data.json;
  84599. // Assign the index of each object for convinience.
  84600. GLTFLoader._AssignIndices(this._gltf.accessors);
  84601. GLTFLoader._AssignIndices(this._gltf.animations);
  84602. GLTFLoader._AssignIndices(this._gltf.buffers);
  84603. GLTFLoader._AssignIndices(this._gltf.bufferViews);
  84604. GLTFLoader._AssignIndices(this._gltf.images);
  84605. GLTFLoader._AssignIndices(this._gltf.materials);
  84606. GLTFLoader._AssignIndices(this._gltf.meshes);
  84607. GLTFLoader._AssignIndices(this._gltf.nodes);
  84608. GLTFLoader._AssignIndices(this._gltf.samplers);
  84609. GLTFLoader._AssignIndices(this._gltf.scenes);
  84610. GLTFLoader._AssignIndices(this._gltf.skins);
  84611. GLTFLoader._AssignIndices(this._gltf.textures);
  84612. if (data.bin) {
  84613. var buffers = this._gltf.buffers;
  84614. if (buffers && buffers[0] && !buffers[0].uri) {
  84615. var binaryBuffer = buffers[0];
  84616. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  84617. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  84618. }
  84619. binaryBuffer.loadedData = data.bin;
  84620. }
  84621. else {
  84622. BABYLON.Tools.Warn("Unexpected BIN chunk");
  84623. }
  84624. }
  84625. };
  84626. GLTFLoader.prototype._getMeshes = function () {
  84627. var meshes = new Array();
  84628. // Root mesh is always first.
  84629. meshes.push(this._rootNode.babylonMesh);
  84630. var nodes = this._gltf.nodes;
  84631. if (nodes) {
  84632. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  84633. var node = nodes_1[_i];
  84634. if (node.babylonMesh) {
  84635. meshes.push(node.babylonMesh);
  84636. }
  84637. }
  84638. }
  84639. return meshes;
  84640. };
  84641. GLTFLoader.prototype._getSkeletons = function () {
  84642. var skeletons = new Array();
  84643. var skins = this._gltf.skins;
  84644. if (skins) {
  84645. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  84646. var skin = skins_1[_i];
  84647. if (skin.babylonSkeleton) {
  84648. skeletons.push(skin.babylonSkeleton);
  84649. }
  84650. }
  84651. }
  84652. return skeletons;
  84653. };
  84654. GLTFLoader.prototype._startAnimations = function () {
  84655. var animations = this._gltf.animations;
  84656. if (!animations) {
  84657. return;
  84658. }
  84659. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  84660. var animation = animations_1[_i];
  84661. animation.babylonAnimationGroup.normalize();
  84662. }
  84663. switch (this.animationStartMode) {
  84664. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  84665. // do nothing
  84666. break;
  84667. }
  84668. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  84669. var animation = animations[0];
  84670. animation.babylonAnimationGroup.start(true);
  84671. break;
  84672. }
  84673. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  84674. for (var _a = 0, animations_2 = animations; _a < animations_2.length; _a++) {
  84675. var animation = animations_2[_a];
  84676. animation.babylonAnimationGroup.start(true);
  84677. }
  84678. break;
  84679. }
  84680. default: {
  84681. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  84682. return;
  84683. }
  84684. }
  84685. };
  84686. GLTFLoader.prototype._loadDefaultScene = function (nodeNames) {
  84687. var scene = GLTFLoader._GetProperty(this._gltf.scenes, this._gltf.scene || 0);
  84688. if (!scene) {
  84689. throw new Error("Failed to find scene " + (this._gltf.scene || 0));
  84690. }
  84691. this._loadScene("#/scenes/" + scene.index, scene, nodeNames);
  84692. };
  84693. GLTFLoader.prototype._loadScene = function (context, scene, nodeNames) {
  84694. var _this = this;
  84695. this._rootNode = { babylonMesh: new BABYLON.Mesh("__root__", this._babylonScene) };
  84696. switch (this.coordinateSystemMode) {
  84697. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  84698. if (!this._babylonScene.useRightHandedSystem) {
  84699. this._rootNode.rotation = [0, 1, 0, 0];
  84700. this._rootNode.scale = [1, 1, -1];
  84701. this._loadTransform(this._rootNode);
  84702. }
  84703. break;
  84704. }
  84705. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  84706. this._babylonScene.useRightHandedSystem = true;
  84707. break;
  84708. }
  84709. default: {
  84710. BABYLON.Tools.Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  84711. return;
  84712. }
  84713. }
  84714. this.onMeshLoadedObservable.notifyObservers(this._rootNode.babylonMesh);
  84715. var nodeIndices = scene.nodes;
  84716. this._traverseNodes(context, nodeIndices, function (node, parentNode) {
  84717. node.parent = parentNode;
  84718. return true;
  84719. }, this._rootNode);
  84720. if (nodeNames) {
  84721. if (!(nodeNames instanceof Array)) {
  84722. nodeNames = [nodeNames];
  84723. }
  84724. var filteredNodeIndices_1 = new Array();
  84725. this._traverseNodes(context, nodeIndices, function (node) {
  84726. if (nodeNames.indexOf(node.name) !== -1) {
  84727. filteredNodeIndices_1.push(node.index);
  84728. node.parent = _this._rootNode;
  84729. return false;
  84730. }
  84731. return true;
  84732. }, this._rootNode);
  84733. nodeIndices = filteredNodeIndices_1;
  84734. }
  84735. for (var _i = 0, nodeIndices_1 = nodeIndices; _i < nodeIndices_1.length; _i++) {
  84736. var index = nodeIndices_1[_i];
  84737. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84738. if (!node) {
  84739. throw new Error(context + ": Failed to find node " + index);
  84740. }
  84741. this._loadNode("#/nodes/" + index, node);
  84742. }
  84743. // Disable the root mesh until the asset is ready to render.
  84744. this._rootNode.babylonMesh.setEnabled(false);
  84745. };
  84746. GLTFLoader.prototype._loadNode = function (context, node) {
  84747. if (GLTF2.GLTFLoaderExtension.LoadNode(this, context, node)) {
  84748. return;
  84749. }
  84750. node.babylonMesh = new BABYLON.Mesh(node.name || "mesh" + node.index, this._babylonScene);
  84751. this._loadTransform(node);
  84752. if (node.mesh != null) {
  84753. var mesh = GLTFLoader._GetProperty(this._gltf.meshes, node.mesh);
  84754. if (!mesh) {
  84755. throw new Error(context + ": Failed to find mesh " + node.mesh);
  84756. }
  84757. this._loadMesh("#/meshes/" + node.mesh, node, mesh);
  84758. }
  84759. node.babylonMesh.parent = node.parent.babylonMesh;
  84760. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  84761. node.babylonAnimationTargets.push(node.babylonMesh);
  84762. if (node.skin != null) {
  84763. var skin_1 = GLTFLoader._GetProperty(this._gltf.skins, node.skin);
  84764. if (!skin_1) {
  84765. throw new Error(context + ": Failed to find skin " + node.skin);
  84766. }
  84767. this._loadSkinAsync("#/skins/" + node.skin, skin_1, function () {
  84768. node.babylonMesh.skeleton = skin_1.babylonSkeleton;
  84769. node.babylonMesh._refreshBoundingInfo(true);
  84770. });
  84771. node.babylonMesh.parent = this._rootNode.babylonMesh;
  84772. node.babylonMesh.position = BABYLON.Vector3.Zero();
  84773. node.babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84774. node.babylonMesh.scaling = BABYLON.Vector3.One();
  84775. }
  84776. if (node.camera != null) {
  84777. // TODO: handle cameras
  84778. }
  84779. if (node.children) {
  84780. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  84781. var index = _a[_i];
  84782. var childNode = GLTFLoader._GetProperty(this._gltf.nodes, index);
  84783. if (!childNode) {
  84784. throw new Error(context + ": Failed to find child node " + index);
  84785. }
  84786. this._loadNode("#/nodes/" + index, childNode);
  84787. }
  84788. }
  84789. this.onMeshLoadedObservable.notifyObservers(node.babylonMesh);
  84790. };
  84791. GLTFLoader.prototype._loadMesh = function (context, node, mesh) {
  84792. var _this = this;
  84793. var primitives = mesh.primitives;
  84794. if (!primitives || primitives.length === 0) {
  84795. throw new Error(context + ": Primitives are missing");
  84796. }
  84797. this._createMorphTargets(context, node, mesh);
  84798. this._loadAllVertexDataAsync(context, mesh, function () {
  84799. _this._loadMorphTargets(context, node, mesh);
  84800. var vertexData = new BABYLON.VertexData();
  84801. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  84802. var primitive = primitives_1[_i];
  84803. vertexData.merge(primitive.vertexData);
  84804. }
  84805. node.babylonMesh.hasVertexAlpha = mesh.hasVertexAlpha;
  84806. new BABYLON.Geometry(node.babylonMesh.name, _this._babylonScene, vertexData, false, node.babylonMesh);
  84807. // TODO: optimize this so that sub meshes can be created without being overwritten after setting vertex data.
  84808. // Sub meshes must be cleared and created after setting vertex data because of mesh._createGlobalSubMesh.
  84809. node.babylonMesh.subMeshes = [];
  84810. var verticesStart = 0;
  84811. var indicesStart = 0;
  84812. for (var index = 0; index < primitives.length; index++) {
  84813. var vertexData_1 = primitives[index].vertexData;
  84814. var verticesCount = vertexData_1.positions.length;
  84815. var indicesCount = vertexData_1.indices.length;
  84816. BABYLON.SubMesh.AddToMesh(index, verticesStart, verticesCount, indicesStart, indicesCount, node.babylonMesh);
  84817. verticesStart += verticesCount;
  84818. indicesStart += indicesCount;
  84819. }
  84820. ;
  84821. });
  84822. if (primitives.length === 1) {
  84823. var primitive = primitives[0];
  84824. if (primitive.material == null) {
  84825. node.babylonMesh.material = this._getDefaultMaterial();
  84826. }
  84827. else {
  84828. var material = GLTFLoader._GetProperty(this._gltf.materials, primitive.material);
  84829. if (!material) {
  84830. throw new Error(context + ": Failed to find material " + primitive.material);
  84831. }
  84832. this._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84833. if (isNew) {
  84834. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84835. }
  84836. node.babylonMesh.material = babylonMaterial;
  84837. });
  84838. }
  84839. }
  84840. else {
  84841. var multiMaterial = new BABYLON.MultiMaterial(node.babylonMesh.name, this._babylonScene);
  84842. node.babylonMesh.material = multiMaterial;
  84843. var subMaterials_1 = multiMaterial.subMaterials;
  84844. var _loop_1 = function (index) {
  84845. var primitive = primitives[index];
  84846. if (primitive.material == null) {
  84847. subMaterials_1[index] = this_1._getDefaultMaterial();
  84848. }
  84849. else {
  84850. var material = GLTFLoader._GetProperty(this_1._gltf.materials, primitive.material);
  84851. if (!material) {
  84852. throw new Error(context + ": Failed to find material " + primitive.material);
  84853. }
  84854. this_1._loadMaterial("#/materials/" + material.index, material, function (babylonMaterial, isNew) {
  84855. if (isNew) {
  84856. _this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  84857. }
  84858. subMaterials_1[index] = babylonMaterial;
  84859. });
  84860. }
  84861. };
  84862. var this_1 = this;
  84863. for (var index = 0; index < primitives.length; index++) {
  84864. _loop_1(index);
  84865. }
  84866. ;
  84867. }
  84868. };
  84869. GLTFLoader.prototype._loadAllVertexDataAsync = function (context, mesh, onSuccess) {
  84870. var primitives = mesh.primitives;
  84871. var numRemainingPrimitives = primitives.length;
  84872. var _loop_2 = function (index) {
  84873. var primitive = primitives[index];
  84874. this_2._loadVertexDataAsync(context + "/primitive/" + index, mesh, primitive, function (vertexData) {
  84875. primitive.vertexData = vertexData;
  84876. if (--numRemainingPrimitives === 0) {
  84877. onSuccess();
  84878. }
  84879. });
  84880. };
  84881. var this_2 = this;
  84882. for (var index = 0; index < primitives.length; index++) {
  84883. _loop_2(index);
  84884. }
  84885. };
  84886. /**
  84887. * Converts a data bufferview into a Float4 Texture Coordinate Array, based on the accessor component type
  84888. * @param {ArrayBufferView} data
  84889. * @param {IGLTFAccessor} accessor
  84890. */
  84891. GLTFLoader.prototype._convertToFloat4TextureCoordArray = function (context, data, accessor) {
  84892. if (accessor.componentType == GLTF2.EComponentType.FLOAT) {
  84893. return data;
  84894. }
  84895. var buffer = data;
  84896. var factor = 1;
  84897. switch (accessor.componentType) {
  84898. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84899. factor = 1 / 255;
  84900. break;
  84901. }
  84902. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84903. factor = 1 / 65535;
  84904. break;
  84905. }
  84906. default: {
  84907. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84908. }
  84909. }
  84910. var result = new Float32Array(accessor.count * 2);
  84911. for (var i = 0; i < result.length; ++i) {
  84912. result[i] = buffer[i] * factor;
  84913. }
  84914. return result;
  84915. };
  84916. /**
  84917. * Converts a data bufferview into a Float4 Color Array, based on the accessor component type
  84918. * @param {ArrayBufferView} data
  84919. * @param {IGLTFAccessor} accessor
  84920. */
  84921. GLTFLoader.prototype._convertToFloat4ColorArray = function (context, data, accessor) {
  84922. var colorComponentCount = GLTFLoader._GetNumComponents(context, accessor.type);
  84923. if (colorComponentCount === 4 && accessor.componentType === GLTF2.EComponentType.FLOAT) {
  84924. return data;
  84925. }
  84926. var buffer = data;
  84927. var factor = 1;
  84928. switch (accessor.componentType) {
  84929. case GLTF2.EComponentType.FLOAT: {
  84930. factor = 1;
  84931. break;
  84932. }
  84933. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  84934. factor = 1 / 255;
  84935. break;
  84936. }
  84937. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  84938. factor = 1 / 65535;
  84939. break;
  84940. }
  84941. default: {
  84942. throw new Error(context + ": Invalid component type (" + accessor.componentType + ")");
  84943. }
  84944. }
  84945. var result = new Float32Array(accessor.count * 4);
  84946. if (colorComponentCount === 4) {
  84947. for (var i = 0; i < result.length; ++i) {
  84948. result[i] = buffer[i] * factor;
  84949. }
  84950. }
  84951. else {
  84952. var offset = 0;
  84953. for (var i = 0; i < result.length; ++i) {
  84954. if ((i + 1) % 4 === 0) {
  84955. result[i] = 1;
  84956. }
  84957. else {
  84958. result[i] = buffer[offset++] * factor;
  84959. }
  84960. }
  84961. }
  84962. return result;
  84963. };
  84964. GLTFLoader.prototype._loadVertexDataAsync = function (context, mesh, primitive, onSuccess) {
  84965. var _this = this;
  84966. var attributes = primitive.attributes;
  84967. if (!attributes) {
  84968. throw new Error(context + ": Attributes are missing");
  84969. }
  84970. if (primitive.mode && primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  84971. // TODO: handle other primitive modes
  84972. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  84973. }
  84974. var vertexData = new BABYLON.VertexData();
  84975. var numRemainingAttributes = Object.keys(attributes).length;
  84976. var _loop_3 = function (attribute) {
  84977. var accessor = GLTFLoader._GetProperty(this_3._gltf.accessors, attributes[attribute]);
  84978. if (!accessor) {
  84979. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  84980. }
  84981. this_3._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  84982. switch (attribute) {
  84983. case "POSITION": {
  84984. vertexData.positions = data;
  84985. break;
  84986. }
  84987. case "NORMAL": {
  84988. vertexData.normals = data;
  84989. break;
  84990. }
  84991. case "TANGENT": {
  84992. vertexData.tangents = data;
  84993. break;
  84994. }
  84995. case "TEXCOORD_0": {
  84996. vertexData.uvs = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  84997. break;
  84998. }
  84999. case "TEXCOORD_1": {
  85000. vertexData.uvs2 = _this._convertToFloat4TextureCoordArray(context, data, accessor);
  85001. break;
  85002. }
  85003. case "JOINTS_0": {
  85004. vertexData.matricesIndices = new Float32Array(Array.prototype.slice.apply(data));
  85005. break;
  85006. }
  85007. case "WEIGHTS_0": {
  85008. //TODO: need to add support for normalized weights.
  85009. vertexData.matricesWeights = data;
  85010. break;
  85011. }
  85012. case "COLOR_0": {
  85013. vertexData.colors = _this._convertToFloat4ColorArray(context, data, accessor);
  85014. var hasVertexAlpha = GLTFLoader._GetNumComponents(context, accessor.type) === 4;
  85015. if (!mesh.hasVertexAlpha && hasVertexAlpha) {
  85016. mesh.hasVertexAlpha = hasVertexAlpha;
  85017. }
  85018. break;
  85019. }
  85020. default: {
  85021. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  85022. break;
  85023. }
  85024. }
  85025. if (--numRemainingAttributes === 0) {
  85026. if (primitive.indices == null) {
  85027. vertexData.indices = new Uint32Array(vertexData.positions.length / 3);
  85028. for (var i = 0; i < vertexData.indices.length; i++) {
  85029. vertexData.indices[i] = i;
  85030. }
  85031. onSuccess(vertexData);
  85032. }
  85033. else {
  85034. var indicesAccessor = GLTFLoader._GetProperty(_this._gltf.accessors, primitive.indices);
  85035. if (!indicesAccessor) {
  85036. throw new Error(context + ": Failed to find indices accessor " + primitive.indices);
  85037. }
  85038. _this._loadAccessorAsync("#/accessors/" + indicesAccessor.index, indicesAccessor, function (data) {
  85039. vertexData.indices = data;
  85040. onSuccess(vertexData);
  85041. });
  85042. }
  85043. }
  85044. });
  85045. };
  85046. var this_3 = this;
  85047. for (var attribute in attributes) {
  85048. _loop_3(attribute);
  85049. }
  85050. };
  85051. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh) {
  85052. var primitives = mesh.primitives;
  85053. var targets = primitives[0].targets;
  85054. if (!targets) {
  85055. return;
  85056. }
  85057. for (var _i = 0, primitives_2 = primitives; _i < primitives_2.length; _i++) {
  85058. var primitive = primitives_2[_i];
  85059. if (!primitive.targets || primitive.targets.length != targets.length) {
  85060. throw new Error(context + ": All primitives are required to list the same number of targets");
  85061. }
  85062. }
  85063. var morphTargetManager = new BABYLON.MorphTargetManager();
  85064. node.babylonMesh.morphTargetManager = morphTargetManager;
  85065. for (var index = 0; index < targets.length; index++) {
  85066. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  85067. morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  85068. }
  85069. };
  85070. GLTFLoader.prototype._loadMorphTargets = function (context, node, mesh) {
  85071. var morphTargetManager = node.babylonMesh.morphTargetManager;
  85072. if (!morphTargetManager) {
  85073. return;
  85074. }
  85075. this._loadAllMorphTargetVertexDataAsync(context, node, mesh, function () {
  85076. var numTargets = morphTargetManager.numTargets;
  85077. for (var index = 0; index < numTargets; index++) {
  85078. var vertexData = new BABYLON.VertexData();
  85079. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  85080. var primitive = _a[_i];
  85081. vertexData.merge(primitive.targetsVertexData[index], { tangentLength: 3 });
  85082. }
  85083. if (!vertexData.positions) {
  85084. throw new Error(context + ": Positions are missing");
  85085. }
  85086. var target = morphTargetManager.getTarget(index);
  85087. target.setPositions(vertexData.positions);
  85088. target.setNormals(vertexData.normals);
  85089. target.setTangents(vertexData.tangents);
  85090. }
  85091. });
  85092. };
  85093. GLTFLoader.prototype._loadAllMorphTargetVertexDataAsync = function (context, node, mesh, onSuccess) {
  85094. var numRemainingTargets = mesh.primitives.length * node.babylonMesh.morphTargetManager.numTargets;
  85095. var _loop_4 = function (primitive) {
  85096. var targets = primitive.targets;
  85097. primitive.targetsVertexData = new Array(targets.length);
  85098. var _loop_5 = function (index) {
  85099. this_4._loadMorphTargetVertexDataAsync(context + "/targets/" + index, primitive.vertexData, targets[index], function (vertexData) {
  85100. primitive.targetsVertexData[index] = vertexData;
  85101. if (--numRemainingTargets === 0) {
  85102. onSuccess();
  85103. }
  85104. });
  85105. };
  85106. for (var index = 0; index < targets.length; index++) {
  85107. _loop_5(index);
  85108. }
  85109. };
  85110. var this_4 = this;
  85111. for (var _i = 0, _a = mesh.primitives; _i < _a.length; _i++) {
  85112. var primitive = _a[_i];
  85113. _loop_4(primitive);
  85114. }
  85115. };
  85116. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, vertexData, attributes, onSuccess) {
  85117. var targetVertexData = new BABYLON.VertexData();
  85118. var numRemainingAttributes = Object.keys(attributes).length;
  85119. var _loop_6 = function (attribute) {
  85120. var accessor = GLTFLoader._GetProperty(this_5._gltf.accessors, attributes[attribute]);
  85121. if (!accessor) {
  85122. throw new Error(context + ": Failed to find attribute '" + attribute + "' accessor " + attributes[attribute]);
  85123. }
  85124. this_5._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85125. // glTF stores morph target information as deltas while babylon.js expects the final data.
  85126. // As a result we have to add the original data to the delta to calculate the final data.
  85127. var values = data;
  85128. switch (attribute) {
  85129. case "POSITION": {
  85130. for (var i = 0; i < values.length; i++) {
  85131. values[i] += vertexData.positions[i];
  85132. }
  85133. targetVertexData.positions = values;
  85134. break;
  85135. }
  85136. case "NORMAL": {
  85137. for (var i = 0; i < values.length; i++) {
  85138. values[i] += vertexData.normals[i];
  85139. }
  85140. targetVertexData.normals = values;
  85141. break;
  85142. }
  85143. case "TANGENT": {
  85144. // Tangent data for morph targets is stored as xyz delta.
  85145. // The vertexData.tangent is stored as xyzw.
  85146. // So we need to skip every fourth vertexData.tangent.
  85147. for (var i = 0, j = 0; i < values.length; i++, j++) {
  85148. values[i] += vertexData.tangents[j];
  85149. if ((i + 1) % 3 == 0) {
  85150. j++;
  85151. }
  85152. }
  85153. targetVertexData.tangents = values;
  85154. break;
  85155. }
  85156. default: {
  85157. BABYLON.Tools.Warn(context + ": Ignoring unrecognized attribute '" + attribute + "'");
  85158. break;
  85159. }
  85160. }
  85161. if (--numRemainingAttributes === 0) {
  85162. onSuccess(targetVertexData);
  85163. }
  85164. });
  85165. };
  85166. var this_5 = this;
  85167. for (var attribute in attributes) {
  85168. _loop_6(attribute);
  85169. }
  85170. };
  85171. GLTFLoader.prototype._loadTransform = function (node) {
  85172. var position = BABYLON.Vector3.Zero();
  85173. var rotation = BABYLON.Quaternion.Identity();
  85174. var scaling = BABYLON.Vector3.One();
  85175. if (node.matrix) {
  85176. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  85177. matrix.decompose(scaling, rotation, position);
  85178. }
  85179. else {
  85180. if (node.translation)
  85181. position = BABYLON.Vector3.FromArray(node.translation);
  85182. if (node.rotation)
  85183. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  85184. if (node.scale)
  85185. scaling = BABYLON.Vector3.FromArray(node.scale);
  85186. }
  85187. node.babylonMesh.position = position;
  85188. node.babylonMesh.rotationQuaternion = rotation;
  85189. node.babylonMesh.scaling = scaling;
  85190. };
  85191. GLTFLoader.prototype._loadSkinAsync = function (context, skin, onSuccess) {
  85192. var _this = this;
  85193. if (skin.babylonSkeleton) {
  85194. onSuccess();
  85195. return;
  85196. }
  85197. var skeletonId = "skeleton" + skin.index;
  85198. skin.babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  85199. if (skin.inverseBindMatrices == null) {
  85200. this._loadBones(context, skin, null);
  85201. onSuccess();
  85202. }
  85203. else {
  85204. var accessor = GLTFLoader._GetProperty(this._gltf.accessors, skin.inverseBindMatrices);
  85205. if (!accessor) {
  85206. throw new Error(context + ": Failed to find inverse bind matrices attribute " + skin.inverseBindMatrices);
  85207. }
  85208. this._loadAccessorAsync("#/accessors/" + accessor.index, accessor, function (data) {
  85209. _this._loadBones(context, skin, data);
  85210. onSuccess();
  85211. });
  85212. }
  85213. };
  85214. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  85215. var babylonBone = new BABYLON.Bone(node.name || "bone" + node.index, skin.babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  85216. node.babylonAnimationTargets = node.babylonAnimationTargets || [];
  85217. node.babylonAnimationTargets.push(babylonBone);
  85218. return babylonBone;
  85219. };
  85220. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatrixData) {
  85221. var babylonBones = {};
  85222. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  85223. var index = _a[_i];
  85224. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85225. if (!node) {
  85226. throw new Error(context + ": Failed to find joint " + index);
  85227. }
  85228. this._loadBone(node, skin, inverseBindMatrixData, babylonBones);
  85229. }
  85230. };
  85231. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatrixData, babylonBones) {
  85232. var babylonBone = babylonBones[node.index];
  85233. if (babylonBone) {
  85234. return babylonBone;
  85235. }
  85236. var boneIndex = skin.joints.indexOf(node.index);
  85237. var baseMatrix = BABYLON.Matrix.Identity();
  85238. if (inverseBindMatrixData && boneIndex !== -1) {
  85239. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatrixData, boneIndex * 16);
  85240. baseMatrix.invertToRef(baseMatrix);
  85241. }
  85242. var babylonParentBone = null;
  85243. if (node.parent !== this._rootNode) {
  85244. babylonParentBone = this._loadBone(node.parent, skin, inverseBindMatrixData, babylonBones);
  85245. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  85246. }
  85247. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  85248. babylonBones[node.index] = babylonBone;
  85249. return babylonBone;
  85250. };
  85251. GLTFLoader.prototype._getNodeMatrix = function (node) {
  85252. return node.matrix ?
  85253. BABYLON.Matrix.FromArray(node.matrix) :
  85254. 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());
  85255. };
  85256. GLTFLoader.prototype._traverseNodes = function (context, indices, action, parentNode) {
  85257. for (var _i = 0, indices_1 = indices; _i < indices_1.length; _i++) {
  85258. var index = indices_1[_i];
  85259. var node = GLTFLoader._GetProperty(this._gltf.nodes, index);
  85260. if (!node) {
  85261. throw new Error(context + ": Failed to find node " + index);
  85262. }
  85263. this._traverseNode(context, node, action, parentNode);
  85264. }
  85265. };
  85266. GLTFLoader.prototype._traverseNode = function (context, node, action, parentNode) {
  85267. if (GLTF2.GLTFLoaderExtension.TraverseNode(this, context, node, action, parentNode)) {
  85268. return;
  85269. }
  85270. if (!action(node, parentNode)) {
  85271. return;
  85272. }
  85273. if (node.children) {
  85274. this._traverseNodes(context, node.children, action, node);
  85275. }
  85276. };
  85277. GLTFLoader.prototype._loadAnimations = function () {
  85278. var animations = this._gltf.animations;
  85279. if (!animations) {
  85280. return;
  85281. }
  85282. for (var index = 0; index < animations.length; index++) {
  85283. var animation = animations[index];
  85284. this._loadAnimation("#/animations/" + index, animation);
  85285. }
  85286. };
  85287. GLTFLoader.prototype._loadAnimation = function (context, animation) {
  85288. animation.babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation.index, this._babylonScene);
  85289. for (var index = 0; index < animation.channels.length; index++) {
  85290. var channel = GLTFLoader._GetProperty(animation.channels, index);
  85291. if (!channel) {
  85292. throw new Error(context + ": Failed to find channel " + index);
  85293. }
  85294. var sampler = GLTFLoader._GetProperty(animation.samplers, channel.sampler);
  85295. if (!sampler) {
  85296. throw new Error(context + ": Failed to find sampler " + channel.sampler);
  85297. }
  85298. this._loadAnimationChannel(animation, context + "/channels/" + index, channel, context + "/samplers/" + channel.sampler, sampler);
  85299. }
  85300. };
  85301. GLTFLoader.prototype._loadAnimationChannel = function (animation, channelContext, channel, samplerContext, sampler) {
  85302. var targetNode = GLTFLoader._GetProperty(this._gltf.nodes, channel.target.node);
  85303. if (!targetNode) {
  85304. throw new Error(channelContext + ": Failed to find target node " + channel.target.node);
  85305. }
  85306. var targetPath;
  85307. var animationType;
  85308. switch (channel.target.path) {
  85309. case "translation": {
  85310. targetPath = "position";
  85311. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85312. break;
  85313. }
  85314. case "rotation": {
  85315. targetPath = "rotationQuaternion";
  85316. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  85317. break;
  85318. }
  85319. case "scale": {
  85320. targetPath = "scaling";
  85321. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  85322. break;
  85323. }
  85324. case "weights": {
  85325. targetPath = "influence";
  85326. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  85327. break;
  85328. }
  85329. default: {
  85330. throw new Error(channelContext + ": Invalid target path " + channel.target.path);
  85331. }
  85332. }
  85333. var inputData;
  85334. var outputData;
  85335. var checkSuccess = function () {
  85336. if (!inputData || !outputData) {
  85337. return;
  85338. }
  85339. var outputBufferOffset = 0;
  85340. var getNextOutputValue;
  85341. switch (targetPath) {
  85342. case "position": {
  85343. getNextOutputValue = function () {
  85344. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85345. outputBufferOffset += 3;
  85346. return value;
  85347. };
  85348. break;
  85349. }
  85350. case "rotationQuaternion": {
  85351. getNextOutputValue = function () {
  85352. var value = BABYLON.Quaternion.FromArray(outputData, outputBufferOffset);
  85353. outputBufferOffset += 4;
  85354. return value;
  85355. };
  85356. break;
  85357. }
  85358. case "scaling": {
  85359. getNextOutputValue = function () {
  85360. var value = BABYLON.Vector3.FromArray(outputData, outputBufferOffset);
  85361. outputBufferOffset += 3;
  85362. return value;
  85363. };
  85364. break;
  85365. }
  85366. case "influence": {
  85367. getNextOutputValue = function () {
  85368. var numTargets = targetNode.babylonMesh.morphTargetManager.numTargets;
  85369. var value = new Array(numTargets);
  85370. for (var i = 0; i < numTargets; i++) {
  85371. value[i] = outputData[outputBufferOffset++];
  85372. }
  85373. return value;
  85374. };
  85375. break;
  85376. }
  85377. }
  85378. sampler.interpolation = sampler.interpolation || "LINEAR";
  85379. var getNextKey;
  85380. switch (sampler.interpolation) {
  85381. case "STEP": {
  85382. getNextKey = function (frameIndex) { return ({
  85383. frame: inputData[frameIndex],
  85384. value: getNextOutputValue(),
  85385. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  85386. }); };
  85387. break;
  85388. }
  85389. case "LINEAR": {
  85390. getNextKey = function (frameIndex) { return ({
  85391. frame: inputData[frameIndex],
  85392. value: getNextOutputValue()
  85393. }); };
  85394. break;
  85395. }
  85396. case "CUBICSPLINE": {
  85397. getNextKey = function (frameIndex) { return ({
  85398. frame: inputData[frameIndex],
  85399. inTangent: getNextOutputValue(),
  85400. value: getNextOutputValue(),
  85401. outTangent: getNextOutputValue()
  85402. }); };
  85403. break;
  85404. }
  85405. default: {
  85406. throw new Error(samplerContext + ": Invalid interpolation " + sampler.interpolation);
  85407. }
  85408. }
  85409. ;
  85410. var keys;
  85411. if (inputData.length === 1) {
  85412. var key = getNextKey(0);
  85413. keys = [
  85414. { frame: key.frame, value: key.value },
  85415. { frame: key.frame + 1, value: key.value }
  85416. ];
  85417. }
  85418. else {
  85419. keys = new Array(inputData.length);
  85420. for (var frameIndex = 0; frameIndex < inputData.length; frameIndex++) {
  85421. keys[frameIndex] = getNextKey(frameIndex);
  85422. }
  85423. }
  85424. if (targetPath === "influence") {
  85425. var morphTargetManager = targetNode.babylonMesh.morphTargetManager;
  85426. var _loop_7 = function (targetIndex) {
  85427. var morphTarget = morphTargetManager.getTarget(targetIndex);
  85428. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  85429. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85430. babylonAnimation.setKeys(keys.map(function (key) { return ({
  85431. frame: key.frame,
  85432. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  85433. value: key.value[targetIndex],
  85434. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  85435. }); }));
  85436. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  85437. };
  85438. for (var targetIndex = 0; targetIndex < morphTargetManager.numTargets; targetIndex++) {
  85439. _loop_7(targetIndex);
  85440. }
  85441. }
  85442. else {
  85443. var animationName = animation.babylonAnimationGroup.name + "_channel" + animation.babylonAnimationGroup.targetedAnimations.length;
  85444. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  85445. babylonAnimation.setKeys(keys);
  85446. if (targetNode.babylonAnimationTargets) {
  85447. for (var _i = 0, _a = targetNode.babylonAnimationTargets; _i < _a.length; _i++) {
  85448. var target = _a[_i];
  85449. animation.babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  85450. }
  85451. }
  85452. }
  85453. };
  85454. var inputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.input);
  85455. if (!inputAccessor) {
  85456. throw new Error(samplerContext + ": Failed to find input accessor " + sampler.input);
  85457. }
  85458. this._loadAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor, function (data) {
  85459. inputData = data;
  85460. checkSuccess();
  85461. });
  85462. var outputAccessor = GLTFLoader._GetProperty(this._gltf.accessors, sampler.output);
  85463. if (!outputAccessor) {
  85464. throw new Error(samplerContext + ": Failed to find output accessor " + sampler.output);
  85465. }
  85466. this._loadAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor, function (data) {
  85467. outputData = data;
  85468. checkSuccess();
  85469. });
  85470. };
  85471. GLTFLoader.prototype._loadBufferAsync = function (context, buffer, onSuccess) {
  85472. var _this = this;
  85473. this._addPendingData(buffer);
  85474. if (buffer.loadedData) {
  85475. onSuccess(buffer.loadedData);
  85476. this._removePendingData(buffer);
  85477. }
  85478. else if (buffer.loadedObservable) {
  85479. buffer.loadedObservable.add(function (buffer) {
  85480. onSuccess(buffer.loadedData);
  85481. _this._removePendingData(buffer);
  85482. });
  85483. }
  85484. else {
  85485. if (!buffer.uri) {
  85486. throw new Error(context + ": Uri is missing");
  85487. }
  85488. buffer.loadedObservable = new BABYLON.Observable();
  85489. buffer.loadedObservable.add(function (buffer) {
  85490. onSuccess(buffer.loadedData);
  85491. _this._removePendingData(buffer);
  85492. });
  85493. this._loadUriAsync(context, buffer.uri, function (data) {
  85494. buffer.loadedData = data;
  85495. buffer.loadedObservable.notifyObservers(buffer);
  85496. buffer.loadedObservable = undefined;
  85497. });
  85498. }
  85499. };
  85500. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView, onSuccess) {
  85501. var buffer = GLTFLoader._GetProperty(this._gltf.buffers, bufferView.buffer);
  85502. if (!buffer) {
  85503. throw new Error(context + ": Failed to find buffer " + bufferView.buffer);
  85504. }
  85505. this._loadBufferAsync("#/buffers/" + buffer.index, buffer, function (bufferData) {
  85506. var data;
  85507. try {
  85508. data = new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  85509. }
  85510. catch (e) {
  85511. throw new Error(context + ": " + e.message);
  85512. }
  85513. onSuccess(data);
  85514. });
  85515. };
  85516. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor, onSuccess) {
  85517. var _this = this;
  85518. if (accessor.sparse) {
  85519. throw new Error(context + ": Sparse accessors are not currently supported");
  85520. }
  85521. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, accessor.bufferView);
  85522. if (!bufferView) {
  85523. throw new Error(context + ": Failed to find buffer view " + accessor.bufferView);
  85524. }
  85525. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, function (bufferViewData) {
  85526. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  85527. var data;
  85528. var byteOffset = accessor.byteOffset || 0;
  85529. var byteStride = bufferView.byteStride;
  85530. if (byteStride === 0) {
  85531. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  85532. }
  85533. try {
  85534. switch (accessor.componentType) {
  85535. case GLTF2.EComponentType.BYTE: {
  85536. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85537. break;
  85538. }
  85539. case GLTF2.EComponentType.UNSIGNED_BYTE: {
  85540. data = _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85541. break;
  85542. }
  85543. case GLTF2.EComponentType.SHORT: {
  85544. data = _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85545. break;
  85546. }
  85547. case GLTF2.EComponentType.UNSIGNED_SHORT: {
  85548. data = _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85549. break;
  85550. }
  85551. case GLTF2.EComponentType.UNSIGNED_INT: {
  85552. data = _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85553. break;
  85554. }
  85555. case GLTF2.EComponentType.FLOAT: {
  85556. data = _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  85557. break;
  85558. }
  85559. default: {
  85560. throw new Error(context + ": Invalid component type " + accessor.componentType);
  85561. }
  85562. }
  85563. }
  85564. catch (e) {
  85565. throw new Error(context + ": " + e);
  85566. }
  85567. onSuccess(data);
  85568. });
  85569. };
  85570. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  85571. byteOffset += data.byteOffset;
  85572. var targetLength = count * numComponents;
  85573. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  85574. return new typedArray(data.buffer, byteOffset, targetLength);
  85575. }
  85576. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  85577. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  85578. var targetBuffer = new typedArray(targetLength);
  85579. var sourceIndex = 0;
  85580. var targetIndex = 0;
  85581. while (targetIndex < targetLength) {
  85582. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  85583. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  85584. targetIndex++;
  85585. }
  85586. sourceIndex += elementStride;
  85587. }
  85588. return targetBuffer;
  85589. };
  85590. GLTFLoader.prototype._addPendingData = function (data) {
  85591. if (!this._renderReady) {
  85592. this._renderPendingCount++;
  85593. }
  85594. this._addLoaderPendingData(data);
  85595. };
  85596. GLTFLoader.prototype._removePendingData = function (data) {
  85597. var _this = this;
  85598. if (!this._renderReady) {
  85599. if (--this._renderPendingCount === 0) {
  85600. this._addLoaderPendingData(this);
  85601. this._compileMaterialsAsync(function () {
  85602. _this._compileShadowGeneratorsAsync(function () {
  85603. _this._removeLoaderPendingData(_this);
  85604. _this._renderReady = true;
  85605. _this._onRenderReady();
  85606. });
  85607. });
  85608. }
  85609. }
  85610. this._removeLoaderPendingData(data);
  85611. };
  85612. GLTFLoader.prototype._addLoaderPendingData = function (data) {
  85613. this._loaderPendingCount++;
  85614. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85615. var tracker = _a[_i];
  85616. tracker._addPendingData(data);
  85617. }
  85618. };
  85619. GLTFLoader.prototype._removeLoaderPendingData = function (data) {
  85620. for (var _i = 0, _a = this._loaderTrackers; _i < _a.length; _i++) {
  85621. var tracker = _a[_i];
  85622. tracker._removePendingData(data);
  85623. }
  85624. if (--this._loaderPendingCount === 0) {
  85625. this._onComplete();
  85626. }
  85627. };
  85628. GLTFLoader.prototype._whenAction = function (action, onComplete) {
  85629. var _this = this;
  85630. var tracker = new GLTFLoaderTracker(function () {
  85631. _this._loaderTrackers.splice(_this._loaderTrackers.indexOf(tracker), 1);
  85632. onComplete();
  85633. });
  85634. this._loaderTrackers.push(tracker);
  85635. this._addLoaderPendingData(tracker);
  85636. action();
  85637. this._removeLoaderPendingData(tracker);
  85638. };
  85639. GLTFLoader.prototype._getDefaultMaterial = function () {
  85640. if (!this._defaultMaterial) {
  85641. var id = "__gltf_default";
  85642. var material = this._babylonScene.getMaterialByName(id);
  85643. if (!material) {
  85644. material = new BABYLON.PBRMaterial(id, this._babylonScene);
  85645. material.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85646. material.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85647. material.metallic = 1;
  85648. material.roughness = 1;
  85649. }
  85650. this._defaultMaterial = material;
  85651. }
  85652. return this._defaultMaterial;
  85653. };
  85654. GLTFLoader.prototype._loadMaterialMetallicRoughnessProperties = function (context, material) {
  85655. var babylonMaterial = material.babylonMaterial;
  85656. // Ensure metallic workflow
  85657. babylonMaterial.metallic = 1;
  85658. babylonMaterial.roughness = 1;
  85659. var properties = material.pbrMetallicRoughness;
  85660. if (!properties) {
  85661. return;
  85662. }
  85663. babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  85664. babylonMaterial.metallic = properties.metallicFactor == null ? 1 : properties.metallicFactor;
  85665. babylonMaterial.roughness = properties.roughnessFactor == null ? 1 : properties.roughnessFactor;
  85666. if (properties.baseColorTexture) {
  85667. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.baseColorTexture.index);
  85668. if (!texture) {
  85669. throw new Error(context + ": Failed to find base color texture " + properties.baseColorTexture.index);
  85670. }
  85671. babylonMaterial.albedoTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.baseColorTexture.texCoord);
  85672. }
  85673. if (properties.metallicRoughnessTexture) {
  85674. var texture = GLTFLoader._GetProperty(this._gltf.textures, properties.metallicRoughnessTexture.index);
  85675. if (!texture) {
  85676. throw new Error(context + ": Failed to find metallic roughness texture " + properties.metallicRoughnessTexture.index);
  85677. }
  85678. babylonMaterial.metallicTexture = this._loadTexture("#/textures/" + texture.index, texture, properties.metallicRoughnessTexture.texCoord);
  85679. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  85680. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  85681. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  85682. }
  85683. this._loadMaterialAlphaProperties(context, material, properties.baseColorFactor);
  85684. };
  85685. GLTFLoader.prototype._loadMaterial = function (context, material, assign) {
  85686. if (material.babylonMaterial) {
  85687. assign(material.babylonMaterial, false);
  85688. return;
  85689. }
  85690. if (GLTF2.GLTFLoaderExtension.LoadMaterial(this, context, material, assign)) {
  85691. return;
  85692. }
  85693. this._createPbrMaterial(material);
  85694. this._loadMaterialBaseProperties(context, material);
  85695. this._loadMaterialMetallicRoughnessProperties(context, material);
  85696. assign(material.babylonMaterial, true);
  85697. };
  85698. GLTFLoader.prototype._createPbrMaterial = function (material) {
  85699. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + material.index, this._babylonScene);
  85700. babylonMaterial.sideOrientation = BABYLON.Material.ClockWiseSideOrientation;
  85701. material.babylonMaterial = babylonMaterial;
  85702. };
  85703. GLTFLoader.prototype._loadMaterialBaseProperties = function (context, material) {
  85704. var babylonMaterial = material.babylonMaterial;
  85705. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  85706. if (material.doubleSided) {
  85707. babylonMaterial.backFaceCulling = false;
  85708. babylonMaterial.twoSidedLighting = true;
  85709. }
  85710. if (material.normalTexture) {
  85711. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.normalTexture.index);
  85712. if (!texture) {
  85713. throw new Error(context + ": Failed to find normal texture " + material.normalTexture.index);
  85714. }
  85715. babylonMaterial.bumpTexture = this._loadTexture("#/textures/" + texture.index, texture, material.normalTexture.texCoord);
  85716. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  85717. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  85718. if (material.normalTexture.scale != null) {
  85719. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  85720. }
  85721. }
  85722. if (material.occlusionTexture) {
  85723. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.occlusionTexture.index);
  85724. if (!texture) {
  85725. throw new Error(context + ": Failed to find occlusion texture " + material.occlusionTexture.index);
  85726. }
  85727. babylonMaterial.ambientTexture = this._loadTexture("#/textures/" + texture.index, texture, material.occlusionTexture.texCoord);
  85728. babylonMaterial.useAmbientInGrayScale = true;
  85729. if (material.occlusionTexture.strength != null) {
  85730. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  85731. }
  85732. }
  85733. if (material.emissiveTexture) {
  85734. var texture = GLTFLoader._GetProperty(this._gltf.textures, material.emissiveTexture.index);
  85735. if (!texture) {
  85736. throw new Error(context + ": Failed to find emissive texture " + material.emissiveTexture.index);
  85737. }
  85738. babylonMaterial.emissiveTexture = this._loadTexture("#/textures/" + texture.index, texture, material.emissiveTexture.texCoord);
  85739. }
  85740. };
  85741. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, colorFactor) {
  85742. var babylonMaterial = material.babylonMaterial;
  85743. var alphaMode = material.alphaMode || "OPAQUE";
  85744. switch (alphaMode) {
  85745. case "OPAQUE": {
  85746. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  85747. break;
  85748. }
  85749. case "MASK": {
  85750. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  85751. babylonMaterial.alphaCutOff = (material.alphaCutoff == null ? 0.5 : material.alphaCutoff);
  85752. if (colorFactor) {
  85753. if (colorFactor[3] == 0) {
  85754. babylonMaterial.alphaCutOff = 1;
  85755. }
  85756. else {
  85757. babylonMaterial.alphaCutOff /= colorFactor[3];
  85758. }
  85759. }
  85760. if (babylonMaterial.albedoTexture) {
  85761. babylonMaterial.albedoTexture.hasAlpha = true;
  85762. }
  85763. break;
  85764. }
  85765. case "BLEND": {
  85766. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  85767. if (colorFactor) {
  85768. babylonMaterial.alpha = colorFactor[3];
  85769. }
  85770. if (babylonMaterial.albedoTexture) {
  85771. babylonMaterial.albedoTexture.hasAlpha = true;
  85772. babylonMaterial.useAlphaFromAlbedoTexture = true;
  85773. }
  85774. break;
  85775. }
  85776. default: {
  85777. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  85778. }
  85779. }
  85780. };
  85781. GLTFLoader.prototype._loadTexture = function (context, texture, coordinatesIndex) {
  85782. var _this = this;
  85783. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(this._gltf.samplers, texture.sampler));
  85784. if (!sampler) {
  85785. throw new Error(context + ": Failed to find sampler " + texture.sampler);
  85786. }
  85787. this._loadSampler("#/samplers/" + sampler.index, sampler);
  85788. this._addPendingData(texture);
  85789. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, sampler.noMipMaps, false, sampler.samplingMode, function () {
  85790. _this._tryCatchOnError(function () {
  85791. _this._removePendingData(texture);
  85792. });
  85793. }, function (message) {
  85794. _this._tryCatchOnError(function () {
  85795. throw new Error(context + ": " + message);
  85796. });
  85797. });
  85798. if (texture.url) {
  85799. babylonTexture.updateURL(texture.url);
  85800. }
  85801. else if (texture.dataReadyObservable) {
  85802. texture.dataReadyObservable.add(function (texture) {
  85803. babylonTexture.updateURL(texture.url);
  85804. });
  85805. }
  85806. else {
  85807. texture.dataReadyObservable = new BABYLON.Observable();
  85808. texture.dataReadyObservable.add(function (texture) {
  85809. babylonTexture.updateURL(texture.url);
  85810. });
  85811. var image_1 = GLTFLoader._GetProperty(this._gltf.images, texture.source);
  85812. if (!image_1) {
  85813. throw new Error(context + ": Failed to find source " + texture.source);
  85814. }
  85815. this._loadImageAsync("#/images/" + image_1.index, image_1, function (data) {
  85816. texture.url = URL.createObjectURL(new Blob([data], { type: image_1.mimeType }));
  85817. texture.dataReadyObservable.notifyObservers(texture);
  85818. texture.dataReadyObservable = undefined;
  85819. });
  85820. }
  85821. babylonTexture.coordinatesIndex = coordinatesIndex || 0;
  85822. babylonTexture.wrapU = sampler.wrapU;
  85823. babylonTexture.wrapV = sampler.wrapV;
  85824. babylonTexture.name = texture.name || "texture" + texture.index;
  85825. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  85826. return babylonTexture;
  85827. };
  85828. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  85829. if (sampler.noMipMaps != undefined) {
  85830. return;
  85831. }
  85832. sampler.noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  85833. sampler.samplingMode = GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter);
  85834. sampler.wrapU = GLTFLoader._GetTextureWrapMode(context, sampler.wrapS);
  85835. sampler.wrapV = GLTFLoader._GetTextureWrapMode(context, sampler.wrapT);
  85836. };
  85837. GLTFLoader.prototype._loadImageAsync = function (context, image, onSuccess) {
  85838. if (image.uri) {
  85839. this._loadUriAsync(context, image.uri, onSuccess);
  85840. }
  85841. else {
  85842. var bufferView = GLTFLoader._GetProperty(this._gltf.bufferViews, image.bufferView);
  85843. if (!bufferView) {
  85844. throw new Error(context + ": Failed to find buffer view " + image.bufferView);
  85845. }
  85846. this._loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView, onSuccess);
  85847. }
  85848. };
  85849. GLTFLoader.prototype._loadUriAsync = function (context, uri, onSuccess) {
  85850. var _this = this;
  85851. if (GLTF2.GLTFUtils.IsBase64(uri)) {
  85852. onSuccess(new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(uri)));
  85853. return;
  85854. }
  85855. if (!GLTF2.GLTFUtils.ValidateUri(uri)) {
  85856. throw new Error(context + ": Uri '" + uri + "' is invalid");
  85857. }
  85858. var request = BABYLON.Tools.LoadFile(this._rootUrl + uri, function (data) {
  85859. _this._tryCatchOnError(function () {
  85860. onSuccess(new Uint8Array(data));
  85861. });
  85862. }, function (event) {
  85863. _this._tryCatchOnError(function () {
  85864. if (request && !_this._renderReady) {
  85865. request._lengthComputable = event.lengthComputable;
  85866. request._loaded = event.loaded;
  85867. request._total = event.total;
  85868. _this._onProgress();
  85869. }
  85870. });
  85871. }, this._babylonScene.database, true, function (request, exception) {
  85872. _this._tryCatchOnError(function () {
  85873. throw new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request);
  85874. });
  85875. });
  85876. this._requests.push(request);
  85877. request.onCompleteObservable.add(function () {
  85878. _this._requests.splice(_this._requests.indexOf(request), 1);
  85879. });
  85880. };
  85881. GLTFLoader.prototype._tryCatchOnError = function (handler) {
  85882. if (this._disposed) {
  85883. return;
  85884. }
  85885. try {
  85886. handler();
  85887. }
  85888. catch (e) {
  85889. BABYLON.Tools.Error("glTF Loader: " + e.message);
  85890. if (this._errorCallback) {
  85891. this._errorCallback(e.message, e);
  85892. }
  85893. this.dispose();
  85894. }
  85895. };
  85896. GLTFLoader._AssignIndices = function (array) {
  85897. if (array) {
  85898. for (var index = 0; index < array.length; index++) {
  85899. array[index].index = index;
  85900. }
  85901. }
  85902. };
  85903. GLTFLoader._GetProperty = function (array, index) {
  85904. if (!array || index == undefined || !array[index]) {
  85905. return null;
  85906. }
  85907. return array[index];
  85908. };
  85909. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  85910. // Set defaults if undefined
  85911. mode = mode == undefined ? GLTF2.ETextureWrapMode.REPEAT : mode;
  85912. switch (mode) {
  85913. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  85914. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  85915. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  85916. default:
  85917. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  85918. return BABYLON.Texture.WRAP_ADDRESSMODE;
  85919. }
  85920. };
  85921. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  85922. // Set defaults if undefined
  85923. magFilter = magFilter == undefined ? GLTF2.ETextureMagFilter.LINEAR : magFilter;
  85924. minFilter = minFilter == undefined ? GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR : minFilter;
  85925. if (magFilter === GLTF2.ETextureMagFilter.LINEAR) {
  85926. switch (minFilter) {
  85927. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.LINEAR_NEAREST;
  85928. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.LINEAR_LINEAR;
  85929. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  85930. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  85931. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  85932. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85933. default:
  85934. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85935. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  85936. }
  85937. }
  85938. else {
  85939. if (magFilter !== GLTF2.ETextureMagFilter.NEAREST) {
  85940. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  85941. }
  85942. switch (minFilter) {
  85943. case GLTF2.ETextureMinFilter.NEAREST: return BABYLON.Texture.NEAREST_NEAREST;
  85944. case GLTF2.ETextureMinFilter.LINEAR: return BABYLON.Texture.NEAREST_LINEAR;
  85945. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85946. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  85947. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  85948. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  85949. default:
  85950. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  85951. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  85952. }
  85953. }
  85954. };
  85955. GLTFLoader._GetNumComponents = function (context, type) {
  85956. switch (type) {
  85957. case "SCALAR": return 1;
  85958. case "VEC2": return 2;
  85959. case "VEC3": return 3;
  85960. case "VEC4": return 4;
  85961. case "MAT2": return 4;
  85962. case "MAT3": return 9;
  85963. case "MAT4": return 16;
  85964. }
  85965. throw new Error(context + ": Invalid type " + type);
  85966. };
  85967. GLTFLoader.prototype._compileMaterialAsync = function (babylonMaterial, babylonMesh, onSuccess) {
  85968. var _this = this;
  85969. if (this.useClipPlane) {
  85970. babylonMaterial.forceCompilation(babylonMesh, function () {
  85971. babylonMaterial.forceCompilation(babylonMesh, function () {
  85972. _this._tryCatchOnError(onSuccess);
  85973. }, { clipPlane: true });
  85974. });
  85975. }
  85976. else {
  85977. babylonMaterial.forceCompilation(babylonMesh, function () {
  85978. _this._tryCatchOnError(onSuccess);
  85979. });
  85980. }
  85981. };
  85982. GLTFLoader.prototype._compileMaterialsAsync = function (onSuccess) {
  85983. if (!this.compileMaterials || !this._gltf.materials) {
  85984. onSuccess();
  85985. return;
  85986. }
  85987. var meshes = this._getMeshes();
  85988. var remaining = 0;
  85989. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  85990. var mesh = meshes_1[_i];
  85991. if (mesh.material instanceof BABYLON.MultiMaterial) {
  85992. for (var _a = 0, _b = mesh.material.subMaterials; _a < _b.length; _a++) {
  85993. var subMaterial = _b[_a];
  85994. if (subMaterial) {
  85995. remaining++;
  85996. }
  85997. }
  85998. }
  85999. else if (mesh.material) {
  86000. remaining++;
  86001. }
  86002. }
  86003. if (remaining === 0) {
  86004. onSuccess();
  86005. return;
  86006. }
  86007. for (var _c = 0, meshes_2 = meshes; _c < meshes_2.length; _c++) {
  86008. var mesh = meshes_2[_c];
  86009. if (mesh.material instanceof BABYLON.MultiMaterial) {
  86010. for (var _d = 0, _e = mesh.material.subMaterials; _d < _e.length; _d++) {
  86011. var subMaterial = _e[_d];
  86012. if (subMaterial) {
  86013. this._compileMaterialAsync(subMaterial, mesh, function () {
  86014. if (--remaining === 0) {
  86015. onSuccess();
  86016. }
  86017. });
  86018. }
  86019. }
  86020. }
  86021. else if (mesh.material) {
  86022. this._compileMaterialAsync(mesh.material, mesh, function () {
  86023. if (--remaining === 0) {
  86024. onSuccess();
  86025. }
  86026. });
  86027. }
  86028. }
  86029. };
  86030. GLTFLoader.prototype._compileShadowGeneratorsAsync = function (onSuccess) {
  86031. var _this = this;
  86032. if (!this.compileShadowGenerators) {
  86033. onSuccess();
  86034. return;
  86035. }
  86036. var lights = this._babylonScene.lights;
  86037. var remaining = 0;
  86038. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  86039. var light = lights_1[_i];
  86040. var generator = light.getShadowGenerator();
  86041. if (generator) {
  86042. remaining++;
  86043. }
  86044. }
  86045. if (remaining === 0) {
  86046. onSuccess();
  86047. return;
  86048. }
  86049. for (var _a = 0, lights_2 = lights; _a < lights_2.length; _a++) {
  86050. var light = lights_2[_a];
  86051. var generator = light.getShadowGenerator();
  86052. if (generator) {
  86053. generator.forceCompilation(function () {
  86054. if (--remaining === 0) {
  86055. _this._tryCatchOnError(onSuccess);
  86056. }
  86057. });
  86058. }
  86059. }
  86060. };
  86061. GLTFLoader.prototype._abortRequests = function () {
  86062. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  86063. var request = _a[_i];
  86064. request.abort();
  86065. }
  86066. this._requests.length = 0;
  86067. };
  86068. GLTFLoader.prototype._releaseResources = function () {
  86069. if (this._gltf.textures) {
  86070. for (var _i = 0, _a = this._gltf.textures; _i < _a.length; _i++) {
  86071. var texture = _a[_i];
  86072. if (texture.url) {
  86073. URL.revokeObjectURL(texture.url);
  86074. texture.url = undefined;
  86075. }
  86076. }
  86077. }
  86078. };
  86079. GLTFLoader.Extensions = {};
  86080. return GLTFLoader;
  86081. }());
  86082. GLTF2.GLTFLoader = GLTFLoader;
  86083. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  86084. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86085. })(BABYLON || (BABYLON = {}));
  86086. //# sourceMappingURL=babylon.glTFLoader.js.map
  86087. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86088. var BABYLON;
  86089. (function (BABYLON) {
  86090. var GLTF2;
  86091. (function (GLTF2) {
  86092. /**
  86093. * Utils functions for GLTF
  86094. */
  86095. var GLTFUtils = /** @class */ (function () {
  86096. function GLTFUtils() {
  86097. }
  86098. /**
  86099. * If the uri is a base64 string
  86100. * @param uri: the uri to test
  86101. */
  86102. GLTFUtils.IsBase64 = function (uri) {
  86103. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  86104. };
  86105. /**
  86106. * Decode the base64 uri
  86107. * @param uri: the uri to decode
  86108. */
  86109. GLTFUtils.DecodeBase64 = function (uri) {
  86110. var decodedString = atob(uri.split(",")[1]);
  86111. var bufferLength = decodedString.length;
  86112. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  86113. for (var i = 0; i < bufferLength; i++) {
  86114. bufferView[i] = decodedString.charCodeAt(i);
  86115. }
  86116. return bufferView.buffer;
  86117. };
  86118. GLTFUtils.ValidateUri = function (uri) {
  86119. return (uri.indexOf("..") === -1);
  86120. };
  86121. return GLTFUtils;
  86122. }());
  86123. GLTF2.GLTFUtils = GLTFUtils;
  86124. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86125. })(BABYLON || (BABYLON = {}));
  86126. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  86127. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  86128. var BABYLON;
  86129. (function (BABYLON) {
  86130. var GLTF2;
  86131. (function (GLTF2) {
  86132. var GLTFLoaderExtension = /** @class */ (function () {
  86133. function GLTFLoaderExtension() {
  86134. this.enabled = true;
  86135. }
  86136. GLTFLoaderExtension.prototype._traverseNode = function (loader, context, node, action, parentNode) { return false; };
  86137. GLTFLoaderExtension.prototype._loadNode = function (loader, context, node) { return false; };
  86138. GLTFLoaderExtension.prototype._loadMaterial = function (loader, context, material, assign) { return false; };
  86139. GLTFLoaderExtension.prototype._loadExtension = function (context, property, action) {
  86140. var _this = this;
  86141. if (!property.extensions) {
  86142. return false;
  86143. }
  86144. var extension = property.extensions[this.name];
  86145. if (!extension) {
  86146. return false;
  86147. }
  86148. // Clear out the extension before executing the action to avoid recursing into the same property.
  86149. property.extensions[this.name] = undefined;
  86150. action(context + "extensions/" + this.name, extension, function () {
  86151. // Restore the extension after completing the action.
  86152. property.extensions[_this.name] = extension;
  86153. });
  86154. return true;
  86155. };
  86156. GLTFLoaderExtension.TraverseNode = function (loader, context, node, action, parentNode) {
  86157. return this._ApplyExtensions(function (extension) { return extension._traverseNode(loader, context, node, action, parentNode); });
  86158. };
  86159. GLTFLoaderExtension.LoadNode = function (loader, context, node) {
  86160. return this._ApplyExtensions(function (extension) { return extension._loadNode(loader, context, node); });
  86161. };
  86162. GLTFLoaderExtension.LoadMaterial = function (loader, context, material, assign) {
  86163. return this._ApplyExtensions(function (extension) { return extension._loadMaterial(loader, context, material, assign); });
  86164. };
  86165. GLTFLoaderExtension._ApplyExtensions = function (action) {
  86166. var extensions = GLTFLoaderExtension._Extensions;
  86167. if (!extensions) {
  86168. return false;
  86169. }
  86170. for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
  86171. var extension = extensions_1[_i];
  86172. if (extension.enabled && action(extension)) {
  86173. return true;
  86174. }
  86175. }
  86176. return false;
  86177. };
  86178. //
  86179. // Utilities
  86180. //
  86181. GLTFLoaderExtension._Extensions = [];
  86182. return GLTFLoaderExtension;
  86183. }());
  86184. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  86185. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86186. })(BABYLON || (BABYLON = {}));
  86187. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  86188. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  86189. var BABYLON;
  86190. (function (BABYLON) {
  86191. var GLTF2;
  86192. (function (GLTF2) {
  86193. var Extensions;
  86194. (function (Extensions) {
  86195. // See https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod for more information about this extension.
  86196. var MSFTLOD = /** @class */ (function (_super) {
  86197. __extends(MSFTLOD, _super);
  86198. function MSFTLOD() {
  86199. var _this = _super !== null && _super.apply(this, arguments) || this;
  86200. /**
  86201. * Specify the minimal delay between LODs in ms (default = 250)
  86202. */
  86203. _this.Delay = 250;
  86204. return _this;
  86205. }
  86206. Object.defineProperty(MSFTLOD.prototype, "name", {
  86207. get: function () {
  86208. return "MSFT_lod";
  86209. },
  86210. enumerable: true,
  86211. configurable: true
  86212. });
  86213. MSFTLOD.prototype._traverseNode = function (loader, context, node, action, parentNode) {
  86214. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86215. for (var i = extension.ids.length - 1; i >= 0; i--) {
  86216. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, extension.ids[i]);
  86217. if (!lodNode) {
  86218. throw new Error(context + ": Failed to find node " + extension.ids[i]);
  86219. }
  86220. loader._traverseNode(context, lodNode, action, parentNode);
  86221. }
  86222. loader._traverseNode(context, node, action, parentNode);
  86223. onComplete();
  86224. });
  86225. };
  86226. MSFTLOD.prototype._loadNode = function (loader, context, node) {
  86227. var _this = this;
  86228. return this._loadExtension(context, node, function (context, extension, onComplete) {
  86229. var nodes = [node];
  86230. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86231. var index = _a[_i];
  86232. var lodNode = GLTF2.GLTFLoader._GetProperty(loader._gltf.nodes, index);
  86233. if (!lodNode) {
  86234. throw new Error(context + ": Failed to find node " + index);
  86235. }
  86236. nodes.push(lodNode);
  86237. }
  86238. loader._addLoaderPendingData(node);
  86239. _this._loadNodeLOD(loader, context, nodes, nodes.length - 1, function () {
  86240. loader._removeLoaderPendingData(node);
  86241. onComplete();
  86242. });
  86243. });
  86244. };
  86245. MSFTLOD.prototype._loadNodeLOD = function (loader, context, nodes, index, onComplete) {
  86246. var _this = this;
  86247. loader._whenAction(function () {
  86248. loader._loadNode(context, nodes[index]);
  86249. }, function () {
  86250. if (index !== nodes.length - 1) {
  86251. var previousNode = nodes[index + 1];
  86252. previousNode.babylonMesh.setEnabled(false);
  86253. }
  86254. if (index === 0) {
  86255. onComplete();
  86256. return;
  86257. }
  86258. setTimeout(function () {
  86259. loader._tryCatchOnError(function () {
  86260. _this._loadNodeLOD(loader, context, nodes, index - 1, onComplete);
  86261. });
  86262. }, _this.Delay);
  86263. });
  86264. };
  86265. MSFTLOD.prototype._loadMaterial = function (loader, context, material, assign) {
  86266. var _this = this;
  86267. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86268. var materials = [material];
  86269. for (var _i = 0, _a = extension.ids; _i < _a.length; _i++) {
  86270. var index = _a[_i];
  86271. var lodMaterial = GLTF2.GLTFLoader._GetProperty(loader._gltf.materials, index);
  86272. if (!lodMaterial) {
  86273. throw new Error(context + ": Failed to find material " + index);
  86274. }
  86275. materials.push(lodMaterial);
  86276. }
  86277. loader._addLoaderPendingData(material);
  86278. _this._loadMaterialLOD(loader, context, materials, materials.length - 1, assign, function () {
  86279. loader._removeLoaderPendingData(material);
  86280. onComplete();
  86281. });
  86282. });
  86283. };
  86284. MSFTLOD.prototype._loadMaterialLOD = function (loader, context, materials, index, assign, onComplete) {
  86285. var _this = this;
  86286. loader._loadMaterial(context, materials[index], function (babylonMaterial, isNew) {
  86287. if (index === materials.length - 1) {
  86288. assign(babylonMaterial, isNew);
  86289. // Load the next LOD when the loader is ready to render.
  86290. loader._executeWhenRenderReady(function () {
  86291. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86292. });
  86293. }
  86294. else {
  86295. BABYLON.BaseTexture.WhenAllReady(babylonMaterial.getActiveTextures(), function () {
  86296. assign(babylonMaterial, isNew);
  86297. if (index === 0) {
  86298. onComplete();
  86299. }
  86300. else {
  86301. setTimeout(function () {
  86302. loader._tryCatchOnError(function () {
  86303. _this._loadMaterialLOD(loader, context, materials, index - 1, assign, onComplete);
  86304. });
  86305. }, _this.Delay);
  86306. }
  86307. });
  86308. }
  86309. });
  86310. };
  86311. return MSFTLOD;
  86312. }(GLTF2.GLTFLoaderExtension));
  86313. Extensions.MSFTLOD = MSFTLOD;
  86314. GLTF2.GLTFLoader.RegisterExtension(new MSFTLOD());
  86315. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86316. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86317. })(BABYLON || (BABYLON = {}));
  86318. //# sourceMappingURL=MSFT_lod.js.map
  86319. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  86320. var BABYLON;
  86321. (function (BABYLON) {
  86322. var GLTF2;
  86323. (function (GLTF2) {
  86324. var Extensions;
  86325. (function (Extensions) {
  86326. var KHRMaterialsPbrSpecularGlossiness = /** @class */ (function (_super) {
  86327. __extends(KHRMaterialsPbrSpecularGlossiness, _super);
  86328. function KHRMaterialsPbrSpecularGlossiness() {
  86329. return _super !== null && _super.apply(this, arguments) || this;
  86330. }
  86331. Object.defineProperty(KHRMaterialsPbrSpecularGlossiness.prototype, "name", {
  86332. get: function () {
  86333. return "KHR_materials_pbrSpecularGlossiness";
  86334. },
  86335. enumerable: true,
  86336. configurable: true
  86337. });
  86338. KHRMaterialsPbrSpecularGlossiness.prototype._loadMaterial = function (loader, context, material, assign) {
  86339. var _this = this;
  86340. return this._loadExtension(context, material, function (context, extension, onComplete) {
  86341. loader._createPbrMaterial(material);
  86342. loader._loadMaterialBaseProperties(context, material);
  86343. _this._loadSpecularGlossinessProperties(loader, context, material, extension);
  86344. assign(material.babylonMaterial, true);
  86345. onComplete();
  86346. });
  86347. };
  86348. KHRMaterialsPbrSpecularGlossiness.prototype._loadSpecularGlossinessProperties = function (loader, context, material, properties) {
  86349. var babylonMaterial = material.babylonMaterial;
  86350. babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  86351. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  86352. babylonMaterial.microSurface = properties.glossinessFactor == null ? 1 : properties.glossinessFactor;
  86353. if (properties.diffuseTexture) {
  86354. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.diffuseTexture.index);
  86355. if (!texture) {
  86356. throw new Error(context + ": Failed to find diffuse texture " + properties.diffuseTexture.index);
  86357. }
  86358. babylonMaterial.albedoTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.diffuseTexture.texCoord);
  86359. }
  86360. if (properties.specularGlossinessTexture) {
  86361. var texture = GLTF2.GLTFLoader._GetProperty(loader._gltf.textures, properties.specularGlossinessTexture.index);
  86362. if (!texture) {
  86363. throw new Error(context + ": Failed to find diffuse texture " + properties.specularGlossinessTexture.index);
  86364. }
  86365. babylonMaterial.reflectivityTexture = loader._loadTexture("textures[" + texture.index + "]", texture, properties.specularGlossinessTexture.texCoord);
  86366. babylonMaterial.reflectivityTexture.hasAlpha = true;
  86367. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  86368. }
  86369. loader._loadMaterialAlphaProperties(context, material, properties.diffuseFactor);
  86370. };
  86371. return KHRMaterialsPbrSpecularGlossiness;
  86372. }(GLTF2.GLTFLoaderExtension));
  86373. Extensions.KHRMaterialsPbrSpecularGlossiness = KHRMaterialsPbrSpecularGlossiness;
  86374. GLTF2.GLTFLoader.RegisterExtension(new KHRMaterialsPbrSpecularGlossiness());
  86375. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  86376. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  86377. })(BABYLON || (BABYLON = {}));
  86378. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  86379. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  86380. globalObject["BABYLON"] = BABYLON;
  86381. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var _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 AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;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 PostProcessRenderPass = BABYLON.PostProcessRenderPass;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 DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var HighlightLayer = BABYLON.HighlightLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var GridMaterial = BABYLON.GridMaterial;var GLTFFileLoader = BABYLON.GLTFFileLoader;
  86382. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,AssetContainer,Buffer,VertexBuffer,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,PostProcessRenderPass,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,HighlightLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,GridMaterial,GLTFFileLoader };